// Generated by Construct, the game and animation creation tool
// Visit: https://www.construct.net

// ../3rdparty/glmatrix.js
{
/*!
@fileoverview gl-matrix - High performance matrix and vector operations
@author Brandon Jones
@author Colin MacKenzie IV
@version 3.4.1

Copyright (c) 2015-2021, Brandon Jones, Colin MacKenzie IV.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
var EPSILON=1e-6,ARRAY_TYPE="undefined"!=typeof Float32Array?Float32Array:Array,RANDOM=Math.random,ANGLE_ORDER="zyx";function setMatrixArrayType(t){ARRAY_TYPE=t}var degree=Math.PI/180;function toRadian(t){return t*degree}function equals$9(t,a){return Math.abs(t-a)<=EPSILON*Math.max(1,Math.abs(t),Math.abs(a))}Math.hypot||(Math.hypot=function(){for(var t=0,a=arguments.length;a--;)t+=arguments[a]*arguments[a];return Math.sqrt(t)});var common={__proto__:null,EPSILON:EPSILON,get ARRAY_TYPE(){return ARRAY_TYPE},RANDOM:RANDOM,ANGLE_ORDER:ANGLE_ORDER,setMatrixArrayType:setMatrixArrayType,toRadian:toRadian,equals:equals$9};function create$8(){var t=new ARRAY_TYPE(4);return ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t}function clone$8(t){var a=new ARRAY_TYPE(4);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a}function copy$8(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t}function identity$5(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t}function fromValues$8(t,a,r,n){var e=new ARRAY_TYPE(4);return e[0]=t,e[1]=a,e[2]=r,e[3]=n,e}function set$8(t,a,r,n,e){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t}function transpose$2(t,a){if(t===a){var r=a[1];t[1]=a[2],t[2]=r}else t[0]=a[0],t[1]=a[2],t[2]=a[1],t[3]=a[3];return t}function invert$5(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r*o-e*n;return u?(u=1/u,t[0]=o*u,t[1]=-n*u,t[2]=-e*u,t[3]=r*u,t):null}function adjoint$2(t,a){var r=a[0];return t[0]=a[3],t[1]=-a[1],t[2]=-a[2],t[3]=r,t}function determinant$3(t){return t[0]*t[3]-t[2]*t[1]}function multiply$8(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[0],i=r[1],c=r[2],l=r[3];return t[0]=n*s+o*i,t[1]=e*s+u*i,t[2]=n*c+o*l,t[3]=e*c+u*l,t}function rotate$4(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=Math.sin(r),i=Math.cos(r);return t[0]=n*i+o*s,t[1]=e*i+u*s,t[2]=n*-s+o*i,t[3]=e*-s+u*i,t}function scale$8(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[0],i=r[1];return t[0]=n*s,t[1]=e*s,t[2]=o*i,t[3]=u*i,t}function fromRotation$4(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=r,t[2]=-r,t[3]=n,t}function fromScaling$3(t,a){return t[0]=a[0],t[1]=0,t[2]=0,t[3]=a[1],t}function str$8(t){return"mat2("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}function frob$3(t){return Math.hypot(t[0],t[1],t[2],t[3])}function LDU(t,a,r,n){return t[2]=n[2]/n[0],r[0]=n[0],r[1]=n[1],r[3]=n[3]-t[2]*r[1],[t,a,r]}function add$8(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t}function subtract$6(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t}function exactEquals$8(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]}function equals$8(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=a[0],s=a[1],i=a[2],c=a[3];return Math.abs(r-u)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(u))&&Math.abs(n-s)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(s))&&Math.abs(e-i)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(i))&&Math.abs(o-c)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(c))}function multiplyScalar$3(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t}function multiplyScalarAndAdd$3(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t}var mul$8=multiply$8,sub$6=subtract$6,mat2=Object.freeze({__proto__:null,create:create$8,clone:clone$8,copy:copy$8,identity:identity$5,fromValues:fromValues$8,set:set$8,transpose:transpose$2,invert:invert$5,adjoint:adjoint$2,determinant:determinant$3,multiply:multiply$8,rotate:rotate$4,scale:scale$8,fromRotation:fromRotation$4,fromScaling:fromScaling$3,str:str$8,frob:frob$3,LDU:LDU,add:add$8,subtract:subtract$6,exactEquals:exactEquals$8,equals:equals$8,multiplyScalar:multiplyScalar$3,multiplyScalarAndAdd:multiplyScalarAndAdd$3,mul:mul$8,sub:sub$6});function create$7(){var t=new ARRAY_TYPE(6);return ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0,t[4]=0,t[5]=0),t[0]=1,t[3]=1,t}function clone$7(t){var a=new ARRAY_TYPE(6);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a[4]=t[4],a[5]=t[5],a}function copy$7(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=a[4],t[5]=a[5],t}function identity$4(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function fromValues$7(t,a,r,n,e,o){var u=new ARRAY_TYPE(6);return u[0]=t,u[1]=a,u[2]=r,u[3]=n,u[4]=e,u[5]=o,u}function set$7(t,a,r,n,e,o,u){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t[4]=o,t[5]=u,t}function invert$4(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=r*o-n*e;return i?(i=1/i,t[0]=o*i,t[1]=-n*i,t[2]=-e*i,t[3]=r*i,t[4]=(e*s-o*u)*i,t[5]=(n*u-r*s)*i,t):null}function determinant$2(t){return t[0]*t[3]-t[1]*t[2]}function multiply$7(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=r[0],l=r[1],$=r[2],h=r[3],f=r[4],M=r[5];return t[0]=n*c+o*l,t[1]=e*c+u*l,t[2]=n*$+o*h,t[3]=e*$+u*h,t[4]=n*f+o*M+s,t[5]=e*f+u*M+i,t}function rotate$3(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=Math.sin(r),l=Math.cos(r);return t[0]=n*l+o*c,t[1]=e*l+u*c,t[2]=n*-c+o*l,t[3]=e*-c+u*l,t[4]=s,t[5]=i,t}function scale$7(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=r[0],l=r[1];return t[0]=n*c,t[1]=e*c,t[2]=o*l,t[3]=u*l,t[4]=s,t[5]=i,t}function translate$3(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=r[0],l=r[1];return t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=n*c+o*l+s,t[5]=e*c+u*l+i,t}function fromRotation$3(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=r,t[2]=-r,t[3]=n,t[4]=0,t[5]=0,t}function fromScaling$2(t,a){return t[0]=a[0],t[1]=0,t[2]=0,t[3]=a[1],t[4]=0,t[5]=0,t}function fromTranslation$3(t,a){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=a[0],t[5]=a[1],t}function str$7(t){return"mat2d("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+")"}function frob$2(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],1)}function add$7(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t[4]=a[4]+r[4],t[5]=a[5]+r[5],t}function subtract$5(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t[4]=a[4]-r[4],t[5]=a[5]-r[5],t}function multiplyScalar$2(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t[4]=a[4]*r,t[5]=a[5]*r,t}function multiplyScalarAndAdd$2(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t[4]=a[4]+r[4]*n,t[5]=a[5]+r[5]*n,t}function exactEquals$7(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]&&t[4]===a[4]&&t[5]===a[5]}function equals$7(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=t[4],s=t[5],i=a[0],c=a[1],l=a[2],$=a[3],h=a[4],f=a[5];return Math.abs(r-i)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(i))&&Math.abs(n-c)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(c))&&Math.abs(e-l)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(l))&&Math.abs(o-$)<=EPSILON*Math.max(1,Math.abs(o),Math.abs($))&&Math.abs(u-h)<=EPSILON*Math.max(1,Math.abs(u),Math.abs(h))&&Math.abs(s-f)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(f))}var mul$7=multiply$7,sub$5=subtract$5,mat2d=Object.freeze({__proto__:null,create:create$7,clone:clone$7,copy:copy$7,identity:identity$4,fromValues:fromValues$7,set:set$7,invert:invert$4,determinant:determinant$2,multiply:multiply$7,rotate:rotate$3,scale:scale$7,translate:translate$3,fromRotation:fromRotation$3,fromScaling:fromScaling$2,fromTranslation:fromTranslation$3,str:str$7,frob:frob$2,add:add$7,subtract:subtract$5,multiplyScalar:multiplyScalar$2,multiplyScalarAndAdd:multiplyScalarAndAdd$2,exactEquals:exactEquals$7,equals:equals$7,mul:mul$7,sub:sub$5});function create$6(){var t=new ARRAY_TYPE(9);return ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}function fromMat4$1(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[4],t[4]=a[5],t[5]=a[6],t[6]=a[8],t[7]=a[9],t[8]=a[10],t}function clone$6(t){var a=new ARRAY_TYPE(9);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a[4]=t[4],a[5]=t[5],a[6]=t[6],a[7]=t[7],a[8]=t[8],a}function copy$6(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=a[4],t[5]=a[5],t[6]=a[6],t[7]=a[7],t[8]=a[8],t}function fromValues$6(t,a,r,n,e,o,u,s,i){var c=new ARRAY_TYPE(9);return c[0]=t,c[1]=a,c[2]=r,c[3]=n,c[4]=e,c[5]=o,c[6]=u,c[7]=s,c[8]=i,c}function set$6(t,a,r,n,e,o,u,s,i,c){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t[4]=o,t[5]=u,t[6]=s,t[7]=i,t[8]=c,t}function identity$3(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function transpose$1(t,a){if(t===a){var r=a[1],n=a[2],e=a[5];t[1]=a[3],t[2]=a[6],t[3]=r,t[5]=a[7],t[6]=n,t[7]=e}else t[0]=a[0],t[1]=a[3],t[2]=a[6],t[3]=a[1],t[4]=a[4],t[5]=a[7],t[6]=a[2],t[7]=a[5],t[8]=a[8];return t}function invert$3(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8],$=l*u-s*c,h=-l*o+s*i,f=c*o-u*i,M=r*$+n*h+e*f;return M?(M=1/M,t[0]=$*M,t[1]=(-l*n+e*c)*M,t[2]=(s*n-e*u)*M,t[3]=h*M,t[4]=(l*r-e*i)*M,t[5]=(-s*r+e*o)*M,t[6]=f*M,t[7]=(-c*r+n*i)*M,t[8]=(u*r-n*o)*M,t):null}function adjoint$1(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8];return t[0]=u*l-s*c,t[1]=e*c-n*l,t[2]=n*s-e*u,t[3]=s*i-o*l,t[4]=r*l-e*i,t[5]=e*o-r*s,t[6]=o*c-u*i,t[7]=n*i-r*c,t[8]=r*u-n*o,t}function determinant$1(t){var a=t[0],r=t[1],n=t[2],e=t[3],o=t[4],u=t[5],s=t[6],i=t[7],c=t[8];return a*(c*o-u*i)+r*(-c*e+u*s)+n*(i*e-o*s)}function multiply$6(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=r[0],f=r[1],M=r[2],m=r[3],d=r[4],v=r[5],b=r[6],p=r[7],A=r[8];return t[0]=h*n+f*u+M*c,t[1]=h*e+f*s+M*l,t[2]=h*o+f*i+M*$,t[3]=m*n+d*u+v*c,t[4]=m*e+d*s+v*l,t[5]=m*o+d*i+v*$,t[6]=b*n+p*u+A*c,t[7]=b*e+p*s+A*l,t[8]=b*o+p*i+A*$,t}function translate$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=r[0],f=r[1];return t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=s,t[5]=i,t[6]=h*n+f*u+c,t[7]=h*e+f*s+l,t[8]=h*o+f*i+$,t}function rotate$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=Math.sin(r),f=Math.cos(r);return t[0]=f*n+h*u,t[1]=f*e+h*s,t[2]=f*o+h*i,t[3]=f*u-h*n,t[4]=f*s-h*e,t[5]=f*i-h*o,t[6]=c,t[7]=l,t[8]=$,t}function scale$6(t,a,r){var n=r[0],e=r[1];return t[0]=n*a[0],t[1]=n*a[1],t[2]=n*a[2],t[3]=e*a[3],t[4]=e*a[4],t[5]=e*a[5],t[6]=a[6],t[7]=a[7],t[8]=a[8],t}function fromTranslation$2(t,a){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=a[0],t[7]=a[1],t[8]=1,t}function fromRotation$2(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function fromScaling$1(t,a){return t[0]=a[0],t[1]=0,t[2]=0,t[3]=0,t[4]=a[1],t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function fromMat2d(t,a){return t[0]=a[0],t[1]=a[1],t[2]=0,t[3]=a[2],t[4]=a[3],t[5]=0,t[6]=a[4],t[7]=a[5],t[8]=1,t}function fromQuat$1(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r+r,s=n+n,i=e+e,c=r*u,l=n*u,$=n*s,h=e*u,f=e*s,M=e*i,m=o*u,d=o*s,v=o*i;return t[0]=1-$-M,t[3]=l-v,t[6]=h+d,t[1]=l+v,t[4]=1-c-M,t[7]=f-m,t[2]=h-d,t[5]=f+m,t[8]=1-c-$,t}function normalFromMat4(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8],$=a[9],h=a[10],f=a[11],M=a[12],m=a[13],d=a[14],v=a[15],b=r*s-n*u,p=r*i-e*u,A=r*c-o*u,y=n*i-e*s,g=n*c-o*s,R=e*c-o*i,E=l*m-$*M,q=l*d-h*M,x=l*v-f*M,P=$*d-h*m,L=$*v-f*m,O=h*v-f*d,S=b*O-p*L+A*P+y*x-g*q+R*E;return S?(S=1/S,t[0]=(s*O-i*L+c*P)*S,t[1]=(i*x-u*O-c*q)*S,t[2]=(u*L-s*x+c*E)*S,t[3]=(e*L-n*O-o*P)*S,t[4]=(r*O-e*x+o*q)*S,t[5]=(n*x-r*L-o*E)*S,t[6]=(m*R-d*g+v*y)*S,t[7]=(d*A-M*R-v*p)*S,t[8]=(M*g-m*A+v*b)*S,t):null}function projection(t,a,r){return t[0]=2/a,t[1]=0,t[2]=0,t[3]=0,t[4]=-2/r,t[5]=0,t[6]=-1,t[7]=1,t[8]=1,t}function str$6(t){return"mat3("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+")"}function frob$1(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])}function add$6(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t[4]=a[4]+r[4],t[5]=a[5]+r[5],t[6]=a[6]+r[6],t[7]=a[7]+r[7],t[8]=a[8]+r[8],t}function subtract$4(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t[4]=a[4]-r[4],t[5]=a[5]-r[5],t[6]=a[6]-r[6],t[7]=a[7]-r[7],t[8]=a[8]-r[8],t}function multiplyScalar$1(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t[4]=a[4]*r,t[5]=a[5]*r,t[6]=a[6]*r,t[7]=a[7]*r,t[8]=a[8]*r,t}function multiplyScalarAndAdd$1(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t[4]=a[4]+r[4]*n,t[5]=a[5]+r[5]*n,t[6]=a[6]+r[6]*n,t[7]=a[7]+r[7]*n,t[8]=a[8]+r[8]*n,t}function exactEquals$6(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]&&t[4]===a[4]&&t[5]===a[5]&&t[6]===a[6]&&t[7]===a[7]&&t[8]===a[8]}function equals$6(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=t[4],s=t[5],i=t[6],c=t[7],l=t[8],$=a[0],h=a[1],f=a[2],M=a[3],m=a[4],d=a[5],v=a[6],b=a[7],p=a[8];return Math.abs(r-$)<=EPSILON*Math.max(1,Math.abs(r),Math.abs($))&&Math.abs(n-h)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(h))&&Math.abs(e-f)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(f))&&Math.abs(o-M)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(M))&&Math.abs(u-m)<=EPSILON*Math.max(1,Math.abs(u),Math.abs(m))&&Math.abs(s-d)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(d))&&Math.abs(i-v)<=EPSILON*Math.max(1,Math.abs(i),Math.abs(v))&&Math.abs(c-b)<=EPSILON*Math.max(1,Math.abs(c),Math.abs(b))&&Math.abs(l-p)<=EPSILON*Math.max(1,Math.abs(l),Math.abs(p))}var mul$6=multiply$6,sub$4=subtract$4,mat3=Object.freeze({__proto__:null,create:create$6,fromMat4:fromMat4$1,clone:clone$6,copy:copy$6,fromValues:fromValues$6,set:set$6,identity:identity$3,transpose:transpose$1,invert:invert$3,adjoint:adjoint$1,determinant:determinant$1,multiply:multiply$6,translate:translate$2,rotate:rotate$2,scale:scale$6,fromTranslation:fromTranslation$2,fromRotation:fromRotation$2,fromScaling:fromScaling$1,fromMat2d:fromMat2d,fromQuat:fromQuat$1,normalFromMat4:normalFromMat4,projection:projection,str:str$6,frob:frob$1,add:add$6,subtract:subtract$4,multiplyScalar:multiplyScalar$1,multiplyScalarAndAdd:multiplyScalarAndAdd$1,exactEquals:exactEquals$6,equals:equals$6,mul:mul$6,sub:sub$4});function create$5(){var t=new ARRAY_TYPE(16);return ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function clone$5(t){var a=new ARRAY_TYPE(16);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a[4]=t[4],a[5]=t[5],a[6]=t[6],a[7]=t[7],a[8]=t[8],a[9]=t[9],a[10]=t[10],a[11]=t[11],a[12]=t[12],a[13]=t[13],a[14]=t[14],a[15]=t[15],a}function copy$5(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=a[4],t[5]=a[5],t[6]=a[6],t[7]=a[7],t[8]=a[8],t[9]=a[9],t[10]=a[10],t[11]=a[11],t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15],t}function fromValues$5(t,a,r,n,e,o,u,s,i,c,l,$,h,f,M,m){var d=new ARRAY_TYPE(16);return d[0]=t,d[1]=a,d[2]=r,d[3]=n,d[4]=e,d[5]=o,d[6]=u,d[7]=s,d[8]=i,d[9]=c,d[10]=l,d[11]=$,d[12]=h,d[13]=f,d[14]=M,d[15]=m,d}function set$5(t,a,r,n,e,o,u,s,i,c,l,$,h,f,M,m,d){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t[4]=o,t[5]=u,t[6]=s,t[7]=i,t[8]=c,t[9]=l,t[10]=$,t[11]=h,t[12]=f,t[13]=M,t[14]=m,t[15]=d,t}function identity$2(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function transpose(t,a){if(t===a){var r=a[1],n=a[2],e=a[3],o=a[6],u=a[7],s=a[11];t[1]=a[4],t[2]=a[8],t[3]=a[12],t[4]=r,t[6]=a[9],t[7]=a[13],t[8]=n,t[9]=o,t[11]=a[14],t[12]=e,t[13]=u,t[14]=s}else t[0]=a[0],t[1]=a[4],t[2]=a[8],t[3]=a[12],t[4]=a[1],t[5]=a[5],t[6]=a[9],t[7]=a[13],t[8]=a[2],t[9]=a[6],t[10]=a[10],t[11]=a[14],t[12]=a[3],t[13]=a[7],t[14]=a[11],t[15]=a[15];return t}function invert$2(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8],$=a[9],h=a[10],f=a[11],M=a[12],m=a[13],d=a[14],v=a[15],b=r*s-n*u,p=r*i-e*u,A=r*c-o*u,y=n*i-e*s,g=n*c-o*s,R=e*c-o*i,E=l*m-$*M,q=l*d-h*M,x=l*v-f*M,P=$*d-h*m,L=$*v-f*m,O=h*v-f*d,S=b*O-p*L+A*P+y*x-g*q+R*E;return S?(S=1/S,t[0]=(s*O-i*L+c*P)*S,t[1]=(e*L-n*O-o*P)*S,t[2]=(m*R-d*g+v*y)*S,t[3]=(h*g-$*R-f*y)*S,t[4]=(i*x-u*O-c*q)*S,t[5]=(r*O-e*x+o*q)*S,t[6]=(d*A-M*R-v*p)*S,t[7]=(l*R-h*A+f*p)*S,t[8]=(u*L-s*x+c*E)*S,t[9]=(n*x-r*L-o*E)*S,t[10]=(M*g-m*A+v*b)*S,t[11]=($*A-l*g-f*b)*S,t[12]=(s*q-u*P-i*E)*S,t[13]=(r*P-n*q+e*E)*S,t[14]=(m*p-M*y-d*b)*S,t[15]=(l*y-$*p+h*b)*S,t):null}function adjoint(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8],$=a[9],h=a[10],f=a[11],M=a[12],m=a[13],d=a[14],v=a[15],b=r*s-n*u,p=r*i-e*u,A=r*c-o*u,y=n*i-e*s,g=n*c-o*s,R=e*c-o*i,E=l*m-$*M,q=l*d-h*M,x=l*v-f*M,P=$*d-h*m,L=$*v-f*m,O=h*v-f*d;return t[0]=s*O-i*L+c*P,t[1]=e*L-n*O-o*P,t[2]=m*R-d*g+v*y,t[3]=h*g-$*R-f*y,t[4]=i*x-u*O-c*q,t[5]=r*O-e*x+o*q,t[6]=d*A-M*R-v*p,t[7]=l*R-h*A+f*p,t[8]=u*L-s*x+c*E,t[9]=n*x-r*L-o*E,t[10]=M*g-m*A+v*b,t[11]=$*A-l*g-f*b,t[12]=s*q-u*P-i*E,t[13]=r*P-n*q+e*E,t[14]=m*p-M*y-d*b,t[15]=l*y-$*p+h*b,t}function determinant(t){var a=t[0],r=t[1],n=t[2],e=t[3],o=t[4],u=t[5],s=t[6],i=t[7],c=t[8],l=t[9],$=t[10],h=t[11],f=t[12],M=t[13],m=t[14],d=a*u-r*o,v=a*s-n*o,b=r*s-n*u,p=c*M-l*f,A=c*m-$*f,y=l*m-$*M;return i*(a*y-r*A+n*p)-e*(o*y-u*A+s*p)+t[15]*(c*b-l*v+$*d)-h*(f*b-M*v+m*d)}function multiply$5(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=a[9],f=a[10],M=a[11],m=a[12],d=a[13],v=a[14],b=a[15],p=r[0],A=r[1],y=r[2],g=r[3];return t[0]=p*n+A*s+y*$+g*m,t[1]=p*e+A*i+y*h+g*d,t[2]=p*o+A*c+y*f+g*v,t[3]=p*u+A*l+y*M+g*b,p=r[4],A=r[5],y=r[6],g=r[7],t[4]=p*n+A*s+y*$+g*m,t[5]=p*e+A*i+y*h+g*d,t[6]=p*o+A*c+y*f+g*v,t[7]=p*u+A*l+y*M+g*b,p=r[8],A=r[9],y=r[10],g=r[11],t[8]=p*n+A*s+y*$+g*m,t[9]=p*e+A*i+y*h+g*d,t[10]=p*o+A*c+y*f+g*v,t[11]=p*u+A*l+y*M+g*b,p=r[12],A=r[13],y=r[14],g=r[15],t[12]=p*n+A*s+y*$+g*m,t[13]=p*e+A*i+y*h+g*d,t[14]=p*o+A*c+y*f+g*v,t[15]=p*u+A*l+y*M+g*b,t}function translate$1(t,a,r){var n,e,o,u,s,i,c,l,$,h,f,M,m=r[0],d=r[1],v=r[2];return a===t?(t[12]=a[0]*m+a[4]*d+a[8]*v+a[12],t[13]=a[1]*m+a[5]*d+a[9]*v+a[13],t[14]=a[2]*m+a[6]*d+a[10]*v+a[14],t[15]=a[3]*m+a[7]*d+a[11]*v+a[15]):(n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=a[9],f=a[10],M=a[11],t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=s,t[5]=i,t[6]=c,t[7]=l,t[8]=$,t[9]=h,t[10]=f,t[11]=M,t[12]=n*m+s*d+$*v+a[12],t[13]=e*m+i*d+h*v+a[13],t[14]=o*m+c*d+f*v+a[14],t[15]=u*m+l*d+M*v+a[15]),t}function scale$5(t,a,r){var n=r[0],e=r[1],o=r[2];return t[0]=a[0]*n,t[1]=a[1]*n,t[2]=a[2]*n,t[3]=a[3]*n,t[4]=a[4]*e,t[5]=a[5]*e,t[6]=a[6]*e,t[7]=a[7]*e,t[8]=a[8]*o,t[9]=a[9]*o,t[10]=a[10]*o,t[11]=a[11]*o,t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15],t}function rotate$1(t,a,r,n){var e,o,u,s,i,c,l,$,h,f,M,m,d,v,b,p,A,y,g,R,E,q,x,P,L=n[0],O=n[1],S=n[2],Y=Math.hypot(L,O,S);return Y<EPSILON?null:(L*=Y=1/Y,O*=Y,S*=Y,e=Math.sin(r),u=1-(o=Math.cos(r)),s=a[0],i=a[1],c=a[2],l=a[3],$=a[4],h=a[5],f=a[6],M=a[7],m=a[8],d=a[9],v=a[10],b=a[11],p=L*L*u+o,A=O*L*u+S*e,y=S*L*u-O*e,g=L*O*u-S*e,R=O*O*u+o,E=S*O*u+L*e,q=L*S*u+O*e,x=O*S*u-L*e,P=S*S*u+o,t[0]=s*p+$*A+m*y,t[1]=i*p+h*A+d*y,t[2]=c*p+f*A+v*y,t[3]=l*p+M*A+b*y,t[4]=s*g+$*R+m*E,t[5]=i*g+h*R+d*E,t[6]=c*g+f*R+v*E,t[7]=l*g+M*R+b*E,t[8]=s*q+$*x+m*P,t[9]=i*q+h*x+d*P,t[10]=c*q+f*x+v*P,t[11]=l*q+M*x+b*P,a!==t&&(t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15]),t)}function rotateX$3(t,a,r){var n=Math.sin(r),e=Math.cos(r),o=a[4],u=a[5],s=a[6],i=a[7],c=a[8],l=a[9],$=a[10],h=a[11];return a!==t&&(t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15]),t[4]=o*e+c*n,t[5]=u*e+l*n,t[6]=s*e+$*n,t[7]=i*e+h*n,t[8]=c*e-o*n,t[9]=l*e-u*n,t[10]=$*e-s*n,t[11]=h*e-i*n,t}function rotateY$3(t,a,r){var n=Math.sin(r),e=Math.cos(r),o=a[0],u=a[1],s=a[2],i=a[3],c=a[8],l=a[9],$=a[10],h=a[11];return a!==t&&(t[4]=a[4],t[5]=a[5],t[6]=a[6],t[7]=a[7],t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15]),t[0]=o*e-c*n,t[1]=u*e-l*n,t[2]=s*e-$*n,t[3]=i*e-h*n,t[8]=o*n+c*e,t[9]=u*n+l*e,t[10]=s*n+$*e,t[11]=i*n+h*e,t}function rotateZ$3(t,a,r){var n=Math.sin(r),e=Math.cos(r),o=a[0],u=a[1],s=a[2],i=a[3],c=a[4],l=a[5],$=a[6],h=a[7];return a!==t&&(t[8]=a[8],t[9]=a[9],t[10]=a[10],t[11]=a[11],t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15]),t[0]=o*e+c*n,t[1]=u*e+l*n,t[2]=s*e+$*n,t[3]=i*e+h*n,t[4]=c*e-o*n,t[5]=l*e-u*n,t[6]=$*e-s*n,t[7]=h*e-i*n,t}function fromTranslation$1(t,a){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=a[0],t[13]=a[1],t[14]=a[2],t[15]=1,t}function fromScaling(t,a){return t[0]=a[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=a[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function fromRotation$1(t,a,r){var n,e,o,u=r[0],s=r[1],i=r[2],c=Math.hypot(u,s,i);return c<EPSILON?null:(u*=c=1/c,s*=c,i*=c,n=Math.sin(a),o=1-(e=Math.cos(a)),t[0]=u*u*o+e,t[1]=s*u*o+i*n,t[2]=i*u*o-s*n,t[3]=0,t[4]=u*s*o-i*n,t[5]=s*s*o+e,t[6]=i*s*o+u*n,t[7]=0,t[8]=u*i*o+s*n,t[9]=s*i*o-u*n,t[10]=i*i*o+e,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t)}function fromXRotation(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=n,t[6]=r,t[7]=0,t[8]=0,t[9]=-r,t[10]=n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function fromYRotation(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=0,t[2]=-r,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=r,t[9]=0,t[10]=n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function fromZRotation(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=r,t[2]=0,t[3]=0,t[4]=-r,t[5]=n,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function fromRotationTranslation$1(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=n+n,i=e+e,c=o+o,l=n*s,$=n*i,h=n*c,f=e*i,M=e*c,m=o*c,d=u*s,v=u*i,b=u*c;return t[0]=1-(f+m),t[1]=$+b,t[2]=h-v,t[3]=0,t[4]=$-b,t[5]=1-(l+m),t[6]=M+d,t[7]=0,t[8]=h+v,t[9]=M-d,t[10]=1-(l+f),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function fromQuat2(t,a){var r=new ARRAY_TYPE(3),n=-a[0],e=-a[1],o=-a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=n*n+e*e+o*o+u*u;return $>0?(r[0]=2*(s*u+l*n+i*o-c*e)/$,r[1]=2*(i*u+l*e+c*n-s*o)/$,r[2]=2*(c*u+l*o+s*e-i*n)/$):(r[0]=2*(s*u+l*n+i*o-c*e),r[1]=2*(i*u+l*e+c*n-s*o),r[2]=2*(c*u+l*o+s*e-i*n)),fromRotationTranslation$1(t,a,r),t}function getTranslation$1(t,a){return t[0]=a[12],t[1]=a[13],t[2]=a[14],t}function getScaling(t,a){var r=a[0],n=a[1],e=a[2],o=a[4],u=a[5],s=a[6],i=a[8],c=a[9],l=a[10];return t[0]=Math.hypot(r,n,e),t[1]=Math.hypot(o,u,s),t[2]=Math.hypot(i,c,l),t}function getRotation(t,a){var r=new ARRAY_TYPE(3);getScaling(r,a);var n=1/r[0],e=1/r[1],o=1/r[2],u=a[0]*n,s=a[1]*e,i=a[2]*o,c=a[4]*n,l=a[5]*e,$=a[6]*o,h=a[8]*n,f=a[9]*e,M=a[10]*o,m=u+l+M,d=0;return m>0?(d=2*Math.sqrt(m+1),t[3]=.25*d,t[0]=($-f)/d,t[1]=(h-i)/d,t[2]=(s-c)/d):u>l&&u>M?(d=2*Math.sqrt(1+u-l-M),t[3]=($-f)/d,t[0]=.25*d,t[1]=(s+c)/d,t[2]=(h+i)/d):l>M?(d=2*Math.sqrt(1+l-u-M),t[3]=(h-i)/d,t[0]=(s+c)/d,t[1]=.25*d,t[2]=($+f)/d):(d=2*Math.sqrt(1+M-u-l),t[3]=(s-c)/d,t[0]=(h+i)/d,t[1]=($+f)/d,t[2]=.25*d),t}function decompose(t,a,r,n){a[0]=n[12],a[1]=n[13],a[2]=n[14];var e=n[0],o=n[1],u=n[2],s=n[4],i=n[5],c=n[6],l=n[8],$=n[9],h=n[10];r[0]=Math.hypot(e,o,u),r[1]=Math.hypot(s,i,c),r[2]=Math.hypot(l,$,h);var f=1/r[0],M=1/r[1],m=1/r[2],d=e*f,v=o*M,b=u*m,p=s*f,A=i*M,y=c*m,g=l*f,R=$*M,E=h*m,q=d+A+E,x=0;return q>0?(x=2*Math.sqrt(q+1),t[3]=.25*x,t[0]=(y-R)/x,t[1]=(g-b)/x,t[2]=(v-p)/x):d>A&&d>E?(x=2*Math.sqrt(1+d-A-E),t[3]=(y-R)/x,t[0]=.25*x,t[1]=(v+p)/x,t[2]=(g+b)/x):A>E?(x=2*Math.sqrt(1+A-d-E),t[3]=(g-b)/x,t[0]=(v+p)/x,t[1]=.25*x,t[2]=(y+R)/x):(x=2*Math.sqrt(1+E-d-A),t[3]=(v-p)/x,t[0]=(g+b)/x,t[1]=(y+R)/x,t[2]=.25*x),t}function fromRotationTranslationScale(t,a,r,n){var e=a[0],o=a[1],u=a[2],s=a[3],i=e+e,c=o+o,l=u+u,$=e*i,h=e*c,f=e*l,M=o*c,m=o*l,d=u*l,v=s*i,b=s*c,p=s*l,A=n[0],y=n[1],g=n[2];return t[0]=(1-(M+d))*A,t[1]=(h+p)*A,t[2]=(f-b)*A,t[3]=0,t[4]=(h-p)*y,t[5]=(1-($+d))*y,t[6]=(m+v)*y,t[7]=0,t[8]=(f+b)*g,t[9]=(m-v)*g,t[10]=(1-($+M))*g,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function fromRotationTranslationScaleOrigin(t,a,r,n,e){var o=a[0],u=a[1],s=a[2],i=a[3],c=o+o,l=u+u,$=s+s,h=o*c,f=o*l,M=o*$,m=u*l,d=u*$,v=s*$,b=i*c,p=i*l,A=i*$,y=n[0],g=n[1],R=n[2],E=e[0],q=e[1],x=e[2],P=(1-(m+v))*y,L=(f+A)*y,O=(M-p)*y,S=(f-A)*g,Y=(1-(h+v))*g,T=(d+b)*g,N=(M+p)*R,_=(d-b)*R,I=(1-(h+m))*R;return t[0]=P,t[1]=L,t[2]=O,t[3]=0,t[4]=S,t[5]=Y,t[6]=T,t[7]=0,t[8]=N,t[9]=_,t[10]=I,t[11]=0,t[12]=r[0]+E-(P*E+S*q+N*x),t[13]=r[1]+q-(L*E+Y*q+_*x),t[14]=r[2]+x-(O*E+T*q+I*x),t[15]=1,t}function fromQuat(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r+r,s=n+n,i=e+e,c=r*u,l=n*u,$=n*s,h=e*u,f=e*s,M=e*i,m=o*u,d=o*s,v=o*i;return t[0]=1-$-M,t[1]=l+v,t[2]=h-d,t[3]=0,t[4]=l-v,t[5]=1-c-M,t[6]=f+m,t[7]=0,t[8]=h+d,t[9]=f-m,t[10]=1-c-$,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function frustum(t,a,r,n,e,o,u){var s=1/(r-a),i=1/(e-n),c=1/(o-u);return t[0]=2*o*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*o*i,t[6]=0,t[7]=0,t[8]=(r+a)*s,t[9]=(e+n)*i,t[10]=(u+o)*c,t[11]=-1,t[12]=0,t[13]=0,t[14]=u*o*2*c,t[15]=0,t}function perspectiveNO(t,a,r,n,e){var o=1/Math.tan(a/2);if(t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=e&&e!==1/0){var u=1/(n-e);t[10]=(e+n)*u,t[14]=2*e*n*u}else t[10]=-1,t[14]=-2*n;return t}var perspective=perspectiveNO;function perspectiveZO(t,a,r,n,e){var o=1/Math.tan(a/2);if(t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=e&&e!==1/0){var u=1/(n-e);t[10]=e*u,t[14]=e*n*u}else t[10]=-1,t[14]=-n;return t}function perspectiveFromFieldOfView(t,a,r,n){var e=Math.tan(a.upDegrees*Math.PI/180),o=Math.tan(a.downDegrees*Math.PI/180),u=Math.tan(a.leftDegrees*Math.PI/180),s=Math.tan(a.rightDegrees*Math.PI/180),i=2/(u+s),c=2/(e+o);return t[0]=i,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=c,t[6]=0,t[7]=0,t[8]=-(u-s)*i*.5,t[9]=(e-o)*c*.5,t[10]=n/(r-n),t[11]=-1,t[12]=0,t[13]=0,t[14]=n*r/(r-n),t[15]=0,t}function orthoNO(t,a,r,n,e,o,u){var s=1/(a-r),i=1/(n-e),c=1/(o-u);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*i,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*c,t[11]=0,t[12]=(a+r)*s,t[13]=(e+n)*i,t[14]=(u+o)*c,t[15]=1,t}var ortho=orthoNO;function orthoZO(t,a,r,n,e,o,u){var s=1/(a-r),i=1/(n-e),c=1/(o-u);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*i,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=c,t[11]=0,t[12]=(a+r)*s,t[13]=(e+n)*i,t[14]=o*c,t[15]=1,t}function lookAt(t,a,r,n){var e,o,u,s,i,c,l,$,h,f,M=a[0],m=a[1],d=a[2],v=n[0],b=n[1],p=n[2],A=r[0],y=r[1],g=r[2];return Math.abs(M-A)<EPSILON&&Math.abs(m-y)<EPSILON&&Math.abs(d-g)<EPSILON?identity$2(t):(l=M-A,$=m-y,h=d-g,e=b*(h*=f=1/Math.hypot(l,$,h))-p*($*=f),o=p*(l*=f)-v*h,u=v*$-b*l,(f=Math.hypot(e,o,u))?(e*=f=1/f,o*=f,u*=f):(e=0,o=0,u=0),s=$*u-h*o,i=h*e-l*u,c=l*o-$*e,(f=Math.hypot(s,i,c))?(s*=f=1/f,i*=f,c*=f):(s=0,i=0,c=0),t[0]=e,t[1]=s,t[2]=l,t[3]=0,t[4]=o,t[5]=i,t[6]=$,t[7]=0,t[8]=u,t[9]=c,t[10]=h,t[11]=0,t[12]=-(e*M+o*m+u*d),t[13]=-(s*M+i*m+c*d),t[14]=-(l*M+$*m+h*d),t[15]=1,t)}function targetTo(t,a,r,n){var e=a[0],o=a[1],u=a[2],s=n[0],i=n[1],c=n[2],l=e-r[0],$=o-r[1],h=u-r[2],f=l*l+$*$+h*h;f>0&&(l*=f=1/Math.sqrt(f),$*=f,h*=f);var M=i*h-c*$,m=c*l-s*h,d=s*$-i*l;return(f=M*M+m*m+d*d)>0&&(M*=f=1/Math.sqrt(f),m*=f,d*=f),t[0]=M,t[1]=m,t[2]=d,t[3]=0,t[4]=$*d-h*m,t[5]=h*M-l*d,t[6]=l*m-$*M,t[7]=0,t[8]=l,t[9]=$,t[10]=h,t[11]=0,t[12]=e,t[13]=o,t[14]=u,t[15]=1,t}function str$5(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function frob(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function add$5(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t[4]=a[4]+r[4],t[5]=a[5]+r[5],t[6]=a[6]+r[6],t[7]=a[7]+r[7],t[8]=a[8]+r[8],t[9]=a[9]+r[9],t[10]=a[10]+r[10],t[11]=a[11]+r[11],t[12]=a[12]+r[12],t[13]=a[13]+r[13],t[14]=a[14]+r[14],t[15]=a[15]+r[15],t}function subtract$3(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t[4]=a[4]-r[4],t[5]=a[5]-r[5],t[6]=a[6]-r[6],t[7]=a[7]-r[7],t[8]=a[8]-r[8],t[9]=a[9]-r[9],t[10]=a[10]-r[10],t[11]=a[11]-r[11],t[12]=a[12]-r[12],t[13]=a[13]-r[13],t[14]=a[14]-r[14],t[15]=a[15]-r[15],t}function multiplyScalar(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t[4]=a[4]*r,t[5]=a[5]*r,t[6]=a[6]*r,t[7]=a[7]*r,t[8]=a[8]*r,t[9]=a[9]*r,t[10]=a[10]*r,t[11]=a[11]*r,t[12]=a[12]*r,t[13]=a[13]*r,t[14]=a[14]*r,t[15]=a[15]*r,t}function multiplyScalarAndAdd(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t[4]=a[4]+r[4]*n,t[5]=a[5]+r[5]*n,t[6]=a[6]+r[6]*n,t[7]=a[7]+r[7]*n,t[8]=a[8]+r[8]*n,t[9]=a[9]+r[9]*n,t[10]=a[10]+r[10]*n,t[11]=a[11]+r[11]*n,t[12]=a[12]+r[12]*n,t[13]=a[13]+r[13]*n,t[14]=a[14]+r[14]*n,t[15]=a[15]+r[15]*n,t}function exactEquals$5(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]&&t[4]===a[4]&&t[5]===a[5]&&t[6]===a[6]&&t[7]===a[7]&&t[8]===a[8]&&t[9]===a[9]&&t[10]===a[10]&&t[11]===a[11]&&t[12]===a[12]&&t[13]===a[13]&&t[14]===a[14]&&t[15]===a[15]}function equals$5(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=t[4],s=t[5],i=t[6],c=t[7],l=t[8],$=t[9],h=t[10],f=t[11],M=t[12],m=t[13],d=t[14],v=t[15],b=a[0],p=a[1],A=a[2],y=a[3],g=a[4],R=a[5],E=a[6],q=a[7],x=a[8],P=a[9],L=a[10],O=a[11],S=a[12],Y=a[13],T=a[14],N=a[15];return Math.abs(r-b)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(b))&&Math.abs(n-p)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(p))&&Math.abs(e-A)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(A))&&Math.abs(o-y)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(y))&&Math.abs(u-g)<=EPSILON*Math.max(1,Math.abs(u),Math.abs(g))&&Math.abs(s-R)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(R))&&Math.abs(i-E)<=EPSILON*Math.max(1,Math.abs(i),Math.abs(E))&&Math.abs(c-q)<=EPSILON*Math.max(1,Math.abs(c),Math.abs(q))&&Math.abs(l-x)<=EPSILON*Math.max(1,Math.abs(l),Math.abs(x))&&Math.abs($-P)<=EPSILON*Math.max(1,Math.abs($),Math.abs(P))&&Math.abs(h-L)<=EPSILON*Math.max(1,Math.abs(h),Math.abs(L))&&Math.abs(f-O)<=EPSILON*Math.max(1,Math.abs(f),Math.abs(O))&&Math.abs(M-S)<=EPSILON*Math.max(1,Math.abs(M),Math.abs(S))&&Math.abs(m-Y)<=EPSILON*Math.max(1,Math.abs(m),Math.abs(Y))&&Math.abs(d-T)<=EPSILON*Math.max(1,Math.abs(d),Math.abs(T))&&Math.abs(v-N)<=EPSILON*Math.max(1,Math.abs(v),Math.abs(N))}var mul$5=multiply$5,sub$3=subtract$3,mat4=Object.freeze({__proto__:null,create:create$5,clone:clone$5,copy:copy$5,fromValues:fromValues$5,set:set$5,identity:identity$2,transpose:transpose,invert:invert$2,adjoint:adjoint,determinant:determinant,multiply:multiply$5,translate:translate$1,scale:scale$5,rotate:rotate$1,rotateX:rotateX$3,rotateY:rotateY$3,rotateZ:rotateZ$3,fromTranslation:fromTranslation$1,fromScaling:fromScaling,fromRotation:fromRotation$1,fromXRotation:fromXRotation,fromYRotation:fromYRotation,fromZRotation:fromZRotation,fromRotationTranslation:fromRotationTranslation$1,fromQuat2:fromQuat2,getTranslation:getTranslation$1,getScaling:getScaling,getRotation:getRotation,decompose:decompose,fromRotationTranslationScale:fromRotationTranslationScale,fromRotationTranslationScaleOrigin:fromRotationTranslationScaleOrigin,fromQuat:fromQuat,frustum:frustum,perspectiveNO:perspectiveNO,perspective:perspective,perspectiveZO:perspectiveZO,perspectiveFromFieldOfView:perspectiveFromFieldOfView,orthoNO:orthoNO,ortho:ortho,orthoZO:orthoZO,lookAt:lookAt,targetTo:targetTo,str:str$5,frob:frob,add:add$5,subtract:subtract$3,multiplyScalar:multiplyScalar,multiplyScalarAndAdd:multiplyScalarAndAdd,exactEquals:exactEquals$5,equals:equals$5,mul:mul$5,sub:sub$3});function create$4(){var t=new ARRAY_TYPE(3);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function clone$4(t){var a=new ARRAY_TYPE(3);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a}function length$4(t){var a=t[0],r=t[1],n=t[2];return Math.hypot(a,r,n)}function fromValues$4(t,a,r){var n=new ARRAY_TYPE(3);return n[0]=t,n[1]=a,n[2]=r,n}function copy$4(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t}function set$4(t,a,r,n){return t[0]=a,t[1]=r,t[2]=n,t}function add$4(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t}function subtract$2(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t}function multiply$4(t,a,r){return t[0]=a[0]*r[0],t[1]=a[1]*r[1],t[2]=a[2]*r[2],t}function divide$2(t,a,r){return t[0]=a[0]/r[0],t[1]=a[1]/r[1],t[2]=a[2]/r[2],t}function ceil$2(t,a){return t[0]=Math.ceil(a[0]),t[1]=Math.ceil(a[1]),t[2]=Math.ceil(a[2]),t}function floor$2(t,a){return t[0]=Math.floor(a[0]),t[1]=Math.floor(a[1]),t[2]=Math.floor(a[2]),t}function min$2(t,a,r){return t[0]=Math.min(a[0],r[0]),t[1]=Math.min(a[1],r[1]),t[2]=Math.min(a[2],r[2]),t}function max$2(t,a,r){return t[0]=Math.max(a[0],r[0]),t[1]=Math.max(a[1],r[1]),t[2]=Math.max(a[2],r[2]),t}function round$2(t,a){return t[0]=Math.round(a[0]),t[1]=Math.round(a[1]),t[2]=Math.round(a[2]),t}function scale$4(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t}function scaleAndAdd$2(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t}function distance$2(t,a){var r=a[0]-t[0],n=a[1]-t[1],e=a[2]-t[2];return Math.hypot(r,n,e)}function squaredDistance$2(t,a){var r=a[0]-t[0],n=a[1]-t[1],e=a[2]-t[2];return r*r+n*n+e*e}function squaredLength$4(t){var a=t[0],r=t[1],n=t[2];return a*a+r*r+n*n}function negate$2(t,a){return t[0]=-a[0],t[1]=-a[1],t[2]=-a[2],t}function inverse$2(t,a){return t[0]=1/a[0],t[1]=1/a[1],t[2]=1/a[2],t}function normalize$4(t,a){var r=a[0],n=a[1],e=a[2],o=r*r+n*n+e*e;return o>0&&(o=1/Math.sqrt(o)),t[0]=a[0]*o,t[1]=a[1]*o,t[2]=a[2]*o,t}function dot$4(t,a){return t[0]*a[0]+t[1]*a[1]+t[2]*a[2]}function cross$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=r[0],s=r[1],i=r[2];return t[0]=e*i-o*s,t[1]=o*u-n*i,t[2]=n*s-e*u,t}function lerp$4(t,a,r,n){var e=a[0],o=a[1],u=a[2];return t[0]=e+n*(r[0]-e),t[1]=o+n*(r[1]-o),t[2]=u+n*(r[2]-u),t}function slerp$1(t,a,r,n){var e=Math.acos(Math.min(Math.max(dot$4(a,r),-1),1)),o=Math.sin(e),u=Math.sin((1-n)*e)/o,s=Math.sin(n*e)/o;return t[0]=u*a[0]+s*r[0],t[1]=u*a[1]+s*r[1],t[2]=u*a[2]+s*r[2],t}function hermite(t,a,r,n,e,o){var u=o*o,s=u*(2*o-3)+1,i=u*(o-2)+o,c=u*(o-1),l=u*(3-2*o);return t[0]=a[0]*s+r[0]*i+n[0]*c+e[0]*l,t[1]=a[1]*s+r[1]*i+n[1]*c+e[1]*l,t[2]=a[2]*s+r[2]*i+n[2]*c+e[2]*l,t}function bezier(t,a,r,n,e,o){var u=1-o,s=u*u,i=o*o,c=s*u,l=3*o*s,$=3*i*u,h=i*o;return t[0]=a[0]*c+r[0]*l+n[0]*$+e[0]*h,t[1]=a[1]*c+r[1]*l+n[1]*$+e[1]*h,t[2]=a[2]*c+r[2]*l+n[2]*$+e[2]*h,t}function random$3(t,a){a=a||1;var r=2*RANDOM()*Math.PI,n=2*RANDOM()-1,e=Math.sqrt(1-n*n)*a;return t[0]=Math.cos(r)*e,t[1]=Math.sin(r)*e,t[2]=n*a,t}function transformMat4$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=r[3]*n+r[7]*e+r[11]*o+r[15];return u=u||1,t[0]=(r[0]*n+r[4]*e+r[8]*o+r[12])/u,t[1]=(r[1]*n+r[5]*e+r[9]*o+r[13])/u,t[2]=(r[2]*n+r[6]*e+r[10]*o+r[14])/u,t}function transformMat3$1(t,a,r){var n=a[0],e=a[1],o=a[2];return t[0]=n*r[0]+e*r[3]+o*r[6],t[1]=n*r[1]+e*r[4]+o*r[7],t[2]=n*r[2]+e*r[5]+o*r[8],t}function transformQuat$1(t,a,r){var n=r[0],e=r[1],o=r[2],u=r[3],s=a[0],i=a[1],c=a[2],l=e*c-o*i,$=o*s-n*c,h=n*i-e*s,f=e*h-o*$,M=o*l-n*h,m=n*$-e*l,d=2*u;return l*=d,$*=d,h*=d,f*=2,M*=2,m*=2,t[0]=s+l+f,t[1]=i+$+M,t[2]=c+h+m,t}function rotateX$2(t,a,r,n){var e=[],o=[];return e[0]=a[0]-r[0],e[1]=a[1]-r[1],e[2]=a[2]-r[2],o[0]=e[0],o[1]=e[1]*Math.cos(n)-e[2]*Math.sin(n),o[2]=e[1]*Math.sin(n)+e[2]*Math.cos(n),t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function rotateY$2(t,a,r,n){var e=[],o=[];return e[0]=a[0]-r[0],e[1]=a[1]-r[1],e[2]=a[2]-r[2],o[0]=e[2]*Math.sin(n)+e[0]*Math.cos(n),o[1]=e[1],o[2]=e[2]*Math.cos(n)-e[0]*Math.sin(n),t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function rotateZ$2(t,a,r,n){var e=[],o=[];return e[0]=a[0]-r[0],e[1]=a[1]-r[1],e[2]=a[2]-r[2],o[0]=e[0]*Math.cos(n)-e[1]*Math.sin(n),o[1]=e[0]*Math.sin(n)+e[1]*Math.cos(n),o[2]=e[2],t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function angle$1(t,a){var r=t[0],n=t[1],e=t[2],o=a[0],u=a[1],s=a[2],i=Math.sqrt((r*r+n*n+e*e)*(o*o+u*u+s*s)),c=i&&dot$4(t,a)/i;return Math.acos(Math.min(Math.max(c,-1),1))}function zero$2(t){return t[0]=0,t[1]=0,t[2]=0,t}function str$4(t){return"vec3("+t[0]+", "+t[1]+", "+t[2]+")"}function exactEquals$4(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]}function equals$4(t,a){var r=t[0],n=t[1],e=t[2],o=a[0],u=a[1],s=a[2];return Math.abs(r-o)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(n-u)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(u))&&Math.abs(e-s)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(s))}var sub$2=subtract$2,mul$4=multiply$4,div$2=divide$2,dist$2=distance$2,sqrDist$2=squaredDistance$2,len$4=length$4,sqrLen$4=squaredLength$4,forEach$2=function(){var t=create$4();return function(a,r,n,e,o,u){var s,i;for(r||(r=3),n||(n=0),i=e?Math.min(e*r+n,a.length):a.length,s=n;s<i;s+=r)t[0]=a[s],t[1]=a[s+1],t[2]=a[s+2],o(t,t,u),a[s]=t[0],a[s+1]=t[1],a[s+2]=t[2];return a}}(),vec3=Object.freeze({__proto__:null,create:create$4,clone:clone$4,length:length$4,fromValues:fromValues$4,copy:copy$4,set:set$4,add:add$4,subtract:subtract$2,multiply:multiply$4,divide:divide$2,ceil:ceil$2,floor:floor$2,min:min$2,max:max$2,round:round$2,scale:scale$4,scaleAndAdd:scaleAndAdd$2,distance:distance$2,squaredDistance:squaredDistance$2,squaredLength:squaredLength$4,negate:negate$2,inverse:inverse$2,normalize:normalize$4,dot:dot$4,cross:cross$2,lerp:lerp$4,slerp:slerp$1,hermite:hermite,bezier:bezier,random:random$3,transformMat4:transformMat4$2,transformMat3:transformMat3$1,transformQuat:transformQuat$1,rotateX:rotateX$2,rotateY:rotateY$2,rotateZ:rotateZ$2,angle:angle$1,zero:zero$2,str:str$4,exactEquals:exactEquals$4,equals:equals$4,sub:sub$2,mul:mul$4,div:div$2,dist:dist$2,sqrDist:sqrDist$2,len:len$4,sqrLen:sqrLen$4,forEach:forEach$2});function create$3(){var t=new ARRAY_TYPE(4);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}function clone$3(t){var a=new ARRAY_TYPE(4);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a}function fromValues$3(t,a,r,n){var e=new ARRAY_TYPE(4);return e[0]=t,e[1]=a,e[2]=r,e[3]=n,e}function copy$3(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t}function set$3(t,a,r,n,e){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t}function add$3(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t}function subtract$1(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t}function multiply$3(t,a,r){return t[0]=a[0]*r[0],t[1]=a[1]*r[1],t[2]=a[2]*r[2],t[3]=a[3]*r[3],t}function divide$1(t,a,r){return t[0]=a[0]/r[0],t[1]=a[1]/r[1],t[2]=a[2]/r[2],t[3]=a[3]/r[3],t}function ceil$1(t,a){return t[0]=Math.ceil(a[0]),t[1]=Math.ceil(a[1]),t[2]=Math.ceil(a[2]),t[3]=Math.ceil(a[3]),t}function floor$1(t,a){return t[0]=Math.floor(a[0]),t[1]=Math.floor(a[1]),t[2]=Math.floor(a[2]),t[3]=Math.floor(a[3]),t}function min$1(t,a,r){return t[0]=Math.min(a[0],r[0]),t[1]=Math.min(a[1],r[1]),t[2]=Math.min(a[2],r[2]),t[3]=Math.min(a[3],r[3]),t}function max$1(t,a,r){return t[0]=Math.max(a[0],r[0]),t[1]=Math.max(a[1],r[1]),t[2]=Math.max(a[2],r[2]),t[3]=Math.max(a[3],r[3]),t}function round$1(t,a){return t[0]=Math.round(a[0]),t[1]=Math.round(a[1]),t[2]=Math.round(a[2]),t[3]=Math.round(a[3]),t}function scale$3(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t}function scaleAndAdd$1(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t}function distance$1(t,a){var r=a[0]-t[0],n=a[1]-t[1],e=a[2]-t[2],o=a[3]-t[3];return Math.hypot(r,n,e,o)}function squaredDistance$1(t,a){var r=a[0]-t[0],n=a[1]-t[1],e=a[2]-t[2],o=a[3]-t[3];return r*r+n*n+e*e+o*o}function length$3(t){var a=t[0],r=t[1],n=t[2],e=t[3];return Math.hypot(a,r,n,e)}function squaredLength$3(t){var a=t[0],r=t[1],n=t[2],e=t[3];return a*a+r*r+n*n+e*e}function negate$1(t,a){return t[0]=-a[0],t[1]=-a[1],t[2]=-a[2],t[3]=-a[3],t}function inverse$1(t,a){return t[0]=1/a[0],t[1]=1/a[1],t[2]=1/a[2],t[3]=1/a[3],t}function normalize$3(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r*r+n*n+e*e+o*o;return u>0&&(u=1/Math.sqrt(u)),t[0]=r*u,t[1]=n*u,t[2]=e*u,t[3]=o*u,t}function dot$3(t,a){return t[0]*a[0]+t[1]*a[1]+t[2]*a[2]+t[3]*a[3]}function cross$1(t,a,r,n){var e=r[0]*n[1]-r[1]*n[0],o=r[0]*n[2]-r[2]*n[0],u=r[0]*n[3]-r[3]*n[0],s=r[1]*n[2]-r[2]*n[1],i=r[1]*n[3]-r[3]*n[1],c=r[2]*n[3]-r[3]*n[2],l=a[0],$=a[1],h=a[2],f=a[3];return t[0]=$*c-h*i+f*s,t[1]=-l*c+h*u-f*o,t[2]=l*i-$*u+f*e,t[3]=-l*s+$*o-h*e,t}function lerp$3(t,a,r,n){var e=a[0],o=a[1],u=a[2],s=a[3];return t[0]=e+n*(r[0]-e),t[1]=o+n*(r[1]-o),t[2]=u+n*(r[2]-u),t[3]=s+n*(r[3]-s),t}function random$2(t,a){var r,n,e,o,u,s;a=a||1;do{u=(r=2*RANDOM()-1)*r+(n=2*RANDOM()-1)*n}while(u>=1);do{s=(e=2*RANDOM()-1)*e+(o=2*RANDOM()-1)*o}while(s>=1);var i=Math.sqrt((1-u)/s);return t[0]=a*r,t[1]=a*n,t[2]=a*e*i,t[3]=a*o*i,t}function transformMat4$1(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3];return t[0]=r[0]*n+r[4]*e+r[8]*o+r[12]*u,t[1]=r[1]*n+r[5]*e+r[9]*o+r[13]*u,t[2]=r[2]*n+r[6]*e+r[10]*o+r[14]*u,t[3]=r[3]*n+r[7]*e+r[11]*o+r[15]*u,t}function transformQuat(t,a,r){var n=a[0],e=a[1],o=a[2],u=r[0],s=r[1],i=r[2],c=r[3],l=c*n+s*o-i*e,$=c*e+i*n-u*o,h=c*o+u*e-s*n,f=-u*n-s*e-i*o;return t[0]=l*c+f*-u+$*-i-h*-s,t[1]=$*c+f*-s+h*-u-l*-i,t[2]=h*c+f*-i+l*-s-$*-u,t[3]=a[3],t}function zero$1(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t}function str$3(t){return"vec4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}function exactEquals$3(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]}function equals$3(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=a[0],s=a[1],i=a[2],c=a[3];return Math.abs(r-u)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(u))&&Math.abs(n-s)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(s))&&Math.abs(e-i)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(i))&&Math.abs(o-c)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(c))}var sub$1=subtract$1,mul$3=multiply$3,div$1=divide$1,dist$1=distance$1,sqrDist$1=squaredDistance$1,len$3=length$3,sqrLen$3=squaredLength$3,forEach$1=function(){var t=create$3();return function(a,r,n,e,o,u){var s,i;for(r||(r=4),n||(n=0),i=e?Math.min(e*r+n,a.length):a.length,s=n;s<i;s+=r)t[0]=a[s],t[1]=a[s+1],t[2]=a[s+2],t[3]=a[s+3],o(t,t,u),a[s]=t[0],a[s+1]=t[1],a[s+2]=t[2],a[s+3]=t[3];return a}}(),vec4=Object.freeze({__proto__:null,create:create$3,clone:clone$3,fromValues:fromValues$3,copy:copy$3,set:set$3,add:add$3,subtract:subtract$1,multiply:multiply$3,divide:divide$1,ceil:ceil$1,floor:floor$1,min:min$1,max:max$1,round:round$1,scale:scale$3,scaleAndAdd:scaleAndAdd$1,distance:distance$1,squaredDistance:squaredDistance$1,length:length$3,squaredLength:squaredLength$3,negate:negate$1,inverse:inverse$1,normalize:normalize$3,dot:dot$3,cross:cross$1,lerp:lerp$3,random:random$2,transformMat4:transformMat4$1,transformQuat:transformQuat,zero:zero$1,str:str$3,exactEquals:exactEquals$3,equals:equals$3,sub:sub$1,mul:mul$3,div:div$1,dist:dist$1,sqrDist:sqrDist$1,len:len$3,sqrLen:sqrLen$3,forEach:forEach$1});function create$2(){var t=new ARRAY_TYPE(4);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function identity$1(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t}function setAxisAngle(t,a,r){r*=.5;var n=Math.sin(r);return t[0]=n*a[0],t[1]=n*a[1],t[2]=n*a[2],t[3]=Math.cos(r),t}function getAxisAngle(t,a){var r=2*Math.acos(a[3]),n=Math.sin(r/2);return n>EPSILON?(t[0]=a[0]/n,t[1]=a[1]/n,t[2]=a[2]/n):(t[0]=1,t[1]=0,t[2]=0),r}function getAngle(t,a){var r=dot$2(t,a);return Math.acos(2*r*r-1)}function multiply$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[0],i=r[1],c=r[2],l=r[3];return t[0]=n*l+u*s+e*c-o*i,t[1]=e*l+u*i+o*s-n*c,t[2]=o*l+u*c+n*i-e*s,t[3]=u*l-n*s-e*i-o*c,t}function rotateX$1(t,a,r){r*=.5;var n=a[0],e=a[1],o=a[2],u=a[3],s=Math.sin(r),i=Math.cos(r);return t[0]=n*i+u*s,t[1]=e*i+o*s,t[2]=o*i-e*s,t[3]=u*i-n*s,t}function rotateY$1(t,a,r){r*=.5;var n=a[0],e=a[1],o=a[2],u=a[3],s=Math.sin(r),i=Math.cos(r);return t[0]=n*i-o*s,t[1]=e*i+u*s,t[2]=o*i+n*s,t[3]=u*i-e*s,t}function rotateZ$1(t,a,r){r*=.5;var n=a[0],e=a[1],o=a[2],u=a[3],s=Math.sin(r),i=Math.cos(r);return t[0]=n*i+e*s,t[1]=e*i-n*s,t[2]=o*i+u*s,t[3]=u*i-o*s,t}function calculateW(t,a){var r=a[0],n=a[1],e=a[2];return t[0]=r,t[1]=n,t[2]=e,t[3]=Math.sqrt(Math.abs(1-r*r-n*n-e*e)),t}function exp(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=Math.sqrt(r*r+n*n+e*e),s=Math.exp(o),i=u>0?s*Math.sin(u)/u:0;return t[0]=r*i,t[1]=n*i,t[2]=e*i,t[3]=s*Math.cos(u),t}function ln(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=Math.sqrt(r*r+n*n+e*e),s=u>0?Math.atan2(u,o)/u:0;return t[0]=r*s,t[1]=n*s,t[2]=e*s,t[3]=.5*Math.log(r*r+n*n+e*e+o*o),t}function pow(t,a,r){return ln(t,a),scale$2(t,t,r),exp(t,t),t}function slerp(t,a,r,n){var e,o,u,s,i,c=a[0],l=a[1],$=a[2],h=a[3],f=r[0],M=r[1],m=r[2],d=r[3];return(o=c*f+l*M+$*m+h*d)<0&&(o=-o,f=-f,M=-M,m=-m,d=-d),1-o>EPSILON?(e=Math.acos(o),u=Math.sin(e),s=Math.sin((1-n)*e)/u,i=Math.sin(n*e)/u):(s=1-n,i=n),t[0]=s*c+i*f,t[1]=s*l+i*M,t[2]=s*$+i*m,t[3]=s*h+i*d,t}function random$1(t){var a=RANDOM(),r=RANDOM(),n=RANDOM(),e=Math.sqrt(1-a),o=Math.sqrt(a);return t[0]=e*Math.sin(2*Math.PI*r),t[1]=e*Math.cos(2*Math.PI*r),t[2]=o*Math.sin(2*Math.PI*n),t[3]=o*Math.cos(2*Math.PI*n),t}function invert$1(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r*r+n*n+e*e+o*o,s=u?1/u:0;return t[0]=-r*s,t[1]=-n*s,t[2]=-e*s,t[3]=o*s,t}function conjugate$1(t,a){return t[0]=-a[0],t[1]=-a[1],t[2]=-a[2],t[3]=a[3],t}function fromMat3(t,a){var r,n=a[0]+a[4]+a[8];if(n>0)r=Math.sqrt(n+1),t[3]=.5*r,r=.5/r,t[0]=(a[5]-a[7])*r,t[1]=(a[6]-a[2])*r,t[2]=(a[1]-a[3])*r;else{var e=0;a[4]>a[0]&&(e=1),a[8]>a[3*e+e]&&(e=2);var o=(e+1)%3,u=(e+2)%3;r=Math.sqrt(a[3*e+e]-a[3*o+o]-a[3*u+u]+1),t[e]=.5*r,r=.5/r,t[3]=(a[3*o+u]-a[3*u+o])*r,t[o]=(a[3*o+e]+a[3*e+o])*r,t[u]=(a[3*u+e]+a[3*e+u])*r}return t}function fromEuler(t,a,r,n){var e=arguments.length>4&&void 0!==arguments[4]?arguments[4]:ANGLE_ORDER,o=Math.PI/360;a*=o,n*=o,r*=o;var u=Math.sin(a),s=Math.cos(a),i=Math.sin(r),c=Math.cos(r),l=Math.sin(n),$=Math.cos(n);switch(e){case"xyz":t[0]=u*c*$+s*i*l,t[1]=s*i*$-u*c*l,t[2]=s*c*l+u*i*$,t[3]=s*c*$-u*i*l;break;case"xzy":t[0]=u*c*$-s*i*l,t[1]=s*i*$-u*c*l,t[2]=s*c*l+u*i*$,t[3]=s*c*$+u*i*l;break;case"yxz":t[0]=u*c*$+s*i*l,t[1]=s*i*$-u*c*l,t[2]=s*c*l-u*i*$,t[3]=s*c*$+u*i*l;break;case"yzx":t[0]=u*c*$+s*i*l,t[1]=s*i*$+u*c*l,t[2]=s*c*l-u*i*$,t[3]=s*c*$-u*i*l;break;case"zxy":t[0]=u*c*$-s*i*l,t[1]=s*i*$+u*c*l,t[2]=s*c*l+u*i*$,t[3]=s*c*$-u*i*l;break;case"zyx":t[0]=u*c*$-s*i*l,t[1]=s*i*$+u*c*l,t[2]=s*c*l-u*i*$,t[3]=s*c*$+u*i*l;break;default:throw new Error("Unknown angle order "+e)}return t}function str$2(t){return"quat("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}var clone$2=clone$3,fromValues$2=fromValues$3,copy$2=copy$3,set$2=set$3,add$2=add$3,mul$2=multiply$2,scale$2=scale$3,dot$2=dot$3,lerp$2=lerp$3,length$2=length$3,len$2=length$2,squaredLength$2=squaredLength$3,sqrLen$2=squaredLength$2,normalize$2=normalize$3,exactEquals$2=exactEquals$3;function equals$2(t,a){return Math.abs(dot$3(t,a))>=1-EPSILON}var rotationTo=function(){var t=create$4(),a=fromValues$4(1,0,0),r=fromValues$4(0,1,0);return function(n,e,o){var u=dot$4(e,o);return u<-.999999?(cross$2(t,a,e),len$4(t)<1e-6&&cross$2(t,r,e),normalize$4(t,t),setAxisAngle(n,t,Math.PI),n):u>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(cross$2(t,e,o),n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=1+u,normalize$2(n,n))}}(),sqlerp=function(){var t=create$2(),a=create$2();return function(r,n,e,o,u,s){return slerp(t,n,u,s),slerp(a,e,o,s),slerp(r,t,a,2*s*(1-s)),r}}(),setAxes=function(){var t=create$6();return function(a,r,n,e){return t[0]=n[0],t[3]=n[1],t[6]=n[2],t[1]=e[0],t[4]=e[1],t[7]=e[2],t[2]=-r[0],t[5]=-r[1],t[8]=-r[2],normalize$2(a,fromMat3(a,t))}}(),quat=Object.freeze({__proto__:null,create:create$2,identity:identity$1,setAxisAngle:setAxisAngle,getAxisAngle:getAxisAngle,getAngle:getAngle,multiply:multiply$2,rotateX:rotateX$1,rotateY:rotateY$1,rotateZ:rotateZ$1,calculateW:calculateW,exp:exp,ln:ln,pow:pow,slerp:slerp,random:random$1,invert:invert$1,conjugate:conjugate$1,fromMat3:fromMat3,fromEuler:fromEuler,str:str$2,clone:clone$2,fromValues:fromValues$2,copy:copy$2,set:set$2,add:add$2,mul:mul$2,scale:scale$2,dot:dot$2,lerp:lerp$2,length:length$2,len:len$2,squaredLength:squaredLength$2,sqrLen:sqrLen$2,normalize:normalize$2,exactEquals:exactEquals$2,equals:equals$2,rotationTo:rotationTo,sqlerp:sqlerp,setAxes:setAxes});function create$1(){var t=new ARRAY_TYPE(8);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0),t[3]=1,t}function clone$1(t){var a=new ARRAY_TYPE(8);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a[4]=t[4],a[5]=t[5],a[6]=t[6],a[7]=t[7],a}function fromValues$1(t,a,r,n,e,o,u,s){var i=new ARRAY_TYPE(8);return i[0]=t,i[1]=a,i[2]=r,i[3]=n,i[4]=e,i[5]=o,i[6]=u,i[7]=s,i}function fromRotationTranslationValues(t,a,r,n,e,o,u){var s=new ARRAY_TYPE(8);s[0]=t,s[1]=a,s[2]=r,s[3]=n;var i=.5*e,c=.5*o,l=.5*u;return s[4]=i*n+c*r-l*a,s[5]=c*n+l*t-i*r,s[6]=l*n+i*a-c*t,s[7]=-i*t-c*a-l*r,s}function fromRotationTranslation(t,a,r){var n=.5*r[0],e=.5*r[1],o=.5*r[2],u=a[0],s=a[1],i=a[2],c=a[3];return t[0]=u,t[1]=s,t[2]=i,t[3]=c,t[4]=n*c+e*i-o*s,t[5]=e*c+o*u-n*i,t[6]=o*c+n*s-e*u,t[7]=-n*u-e*s-o*i,t}function fromTranslation(t,a){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=.5*a[0],t[5]=.5*a[1],t[6]=.5*a[2],t[7]=0,t}function fromRotation(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=0,t[5]=0,t[6]=0,t[7]=0,t}function fromMat4(t,a){var r=create$2();getRotation(r,a);var n=new ARRAY_TYPE(3);return getTranslation$1(n,a),fromRotationTranslation(t,r,n),t}function copy$1(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=a[4],t[5]=a[5],t[6]=a[6],t[7]=a[7],t}function identity(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t}function set$1(t,a,r,n,e,o,u,s,i){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t[4]=o,t[5]=u,t[6]=s,t[7]=i,t}var getReal=copy$2;function getDual(t,a){return t[0]=a[4],t[1]=a[5],t[2]=a[6],t[3]=a[7],t}var setReal=copy$2;function setDual(t,a){return t[4]=a[0],t[5]=a[1],t[6]=a[2],t[7]=a[3],t}function getTranslation(t,a){var r=a[4],n=a[5],e=a[6],o=a[7],u=-a[0],s=-a[1],i=-a[2],c=a[3];return t[0]=2*(r*c+o*u+n*i-e*s),t[1]=2*(n*c+o*s+e*u-r*i),t[2]=2*(e*c+o*i+r*s-n*u),t}function translate(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=.5*r[0],i=.5*r[1],c=.5*r[2],l=a[4],$=a[5],h=a[6],f=a[7];return t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=u*s+e*c-o*i+l,t[5]=u*i+o*s-n*c+$,t[6]=u*c+n*i-e*s+h,t[7]=-n*s-e*i-o*c+f,t}function rotateX(t,a,r){var n=-a[0],e=-a[1],o=-a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=s*u+l*n+i*o-c*e,h=i*u+l*e+c*n-s*o,f=c*u+l*o+s*e-i*n,M=l*u-s*n-i*e-c*o;return rotateX$1(t,a,r),n=t[0],e=t[1],o=t[2],u=t[3],t[4]=$*u+M*n+h*o-f*e,t[5]=h*u+M*e+f*n-$*o,t[6]=f*u+M*o+$*e-h*n,t[7]=M*u-$*n-h*e-f*o,t}function rotateY(t,a,r){var n=-a[0],e=-a[1],o=-a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=s*u+l*n+i*o-c*e,h=i*u+l*e+c*n-s*o,f=c*u+l*o+s*e-i*n,M=l*u-s*n-i*e-c*o;return rotateY$1(t,a,r),n=t[0],e=t[1],o=t[2],u=t[3],t[4]=$*u+M*n+h*o-f*e,t[5]=h*u+M*e+f*n-$*o,t[6]=f*u+M*o+$*e-h*n,t[7]=M*u-$*n-h*e-f*o,t}function rotateZ(t,a,r){var n=-a[0],e=-a[1],o=-a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=s*u+l*n+i*o-c*e,h=i*u+l*e+c*n-s*o,f=c*u+l*o+s*e-i*n,M=l*u-s*n-i*e-c*o;return rotateZ$1(t,a,r),n=t[0],e=t[1],o=t[2],u=t[3],t[4]=$*u+M*n+h*o-f*e,t[5]=h*u+M*e+f*n-$*o,t[6]=f*u+M*o+$*e-h*n,t[7]=M*u-$*n-h*e-f*o,t}function rotateByQuatAppend(t,a,r){var n=r[0],e=r[1],o=r[2],u=r[3],s=a[0],i=a[1],c=a[2],l=a[3];return t[0]=s*u+l*n+i*o-c*e,t[1]=i*u+l*e+c*n-s*o,t[2]=c*u+l*o+s*e-i*n,t[3]=l*u-s*n-i*e-c*o,s=a[4],i=a[5],c=a[6],l=a[7],t[4]=s*u+l*n+i*o-c*e,t[5]=i*u+l*e+c*n-s*o,t[6]=c*u+l*o+s*e-i*n,t[7]=l*u-s*n-i*e-c*o,t}function rotateByQuatPrepend(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[0],i=r[1],c=r[2],l=r[3];return t[0]=n*l+u*s+e*c-o*i,t[1]=e*l+u*i+o*s-n*c,t[2]=o*l+u*c+n*i-e*s,t[3]=u*l-n*s-e*i-o*c,s=r[4],i=r[5],c=r[6],l=r[7],t[4]=n*l+u*s+e*c-o*i,t[5]=e*l+u*i+o*s-n*c,t[6]=o*l+u*c+n*i-e*s,t[7]=u*l-n*s-e*i-o*c,t}function rotateAroundAxis(t,a,r,n){if(Math.abs(n)<EPSILON)return copy$1(t,a);var e=Math.hypot(r[0],r[1],r[2]);n*=.5;var o=Math.sin(n),u=o*r[0]/e,s=o*r[1]/e,i=o*r[2]/e,c=Math.cos(n),l=a[0],$=a[1],h=a[2],f=a[3];t[0]=l*c+f*u+$*i-h*s,t[1]=$*c+f*s+h*u-l*i,t[2]=h*c+f*i+l*s-$*u,t[3]=f*c-l*u-$*s-h*i;var M=a[4],m=a[5],d=a[6],v=a[7];return t[4]=M*c+v*u+m*i-d*s,t[5]=m*c+v*s+d*u-M*i,t[6]=d*c+v*i+M*s-m*u,t[7]=v*c-M*u-m*s-d*i,t}function add$1(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t[4]=a[4]+r[4],t[5]=a[5]+r[5],t[6]=a[6]+r[6],t[7]=a[7]+r[7],t}function multiply$1(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[4],i=r[5],c=r[6],l=r[7],$=a[4],h=a[5],f=a[6],M=a[7],m=r[0],d=r[1],v=r[2],b=r[3];return t[0]=n*b+u*m+e*v-o*d,t[1]=e*b+u*d+o*m-n*v,t[2]=o*b+u*v+n*d-e*m,t[3]=u*b-n*m-e*d-o*v,t[4]=n*l+u*s+e*c-o*i+$*b+M*m+h*v-f*d,t[5]=e*l+u*i+o*s-n*c+h*b+M*d+f*m-$*v,t[6]=o*l+u*c+n*i-e*s+f*b+M*v+$*d-h*m,t[7]=u*l-n*s-e*i-o*c+M*b-$*m-h*d-f*v,t}var mul$1=multiply$1;function scale$1(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t[4]=a[4]*r,t[5]=a[5]*r,t[6]=a[6]*r,t[7]=a[7]*r,t}var dot$1=dot$2;function lerp$1(t,a,r,n){var e=1-n;return dot$1(a,r)<0&&(n=-n),t[0]=a[0]*e+r[0]*n,t[1]=a[1]*e+r[1]*n,t[2]=a[2]*e+r[2]*n,t[3]=a[3]*e+r[3]*n,t[4]=a[4]*e+r[4]*n,t[5]=a[5]*e+r[5]*n,t[6]=a[6]*e+r[6]*n,t[7]=a[7]*e+r[7]*n,t}function invert(t,a){var r=squaredLength$1(a);return t[0]=-a[0]/r,t[1]=-a[1]/r,t[2]=-a[2]/r,t[3]=a[3]/r,t[4]=-a[4]/r,t[5]=-a[5]/r,t[6]=-a[6]/r,t[7]=a[7]/r,t}function conjugate(t,a){return t[0]=-a[0],t[1]=-a[1],t[2]=-a[2],t[3]=a[3],t[4]=-a[4],t[5]=-a[5],t[6]=-a[6],t[7]=a[7],t}var length$1=length$2,len$1=length$1,squaredLength$1=squaredLength$2,sqrLen$1=squaredLength$1;function normalize$1(t,a){var r=squaredLength$1(a);if(r>0){r=Math.sqrt(r);var n=a[0]/r,e=a[1]/r,o=a[2]/r,u=a[3]/r,s=a[4],i=a[5],c=a[6],l=a[7],$=n*s+e*i+o*c+u*l;t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=(s-n*$)/r,t[5]=(i-e*$)/r,t[6]=(c-o*$)/r,t[7]=(l-u*$)/r}return t}function str$1(t){return"quat2("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+")"}function exactEquals$1(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]&&t[4]===a[4]&&t[5]===a[5]&&t[6]===a[6]&&t[7]===a[7]}function equals$1(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=t[4],s=t[5],i=t[6],c=t[7],l=a[0],$=a[1],h=a[2],f=a[3],M=a[4],m=a[5],d=a[6],v=a[7];return Math.abs(r-l)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(l))&&Math.abs(n-$)<=EPSILON*Math.max(1,Math.abs(n),Math.abs($))&&Math.abs(e-h)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(h))&&Math.abs(o-f)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(f))&&Math.abs(u-M)<=EPSILON*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(s-m)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(m))&&Math.abs(i-d)<=EPSILON*Math.max(1,Math.abs(i),Math.abs(d))&&Math.abs(c-v)<=EPSILON*Math.max(1,Math.abs(c),Math.abs(v))}var quat2=Object.freeze({__proto__:null,create:create$1,clone:clone$1,fromValues:fromValues$1,fromRotationTranslationValues:fromRotationTranslationValues,fromRotationTranslation:fromRotationTranslation,fromTranslation:fromTranslation,fromRotation:fromRotation,fromMat4:fromMat4,copy:copy$1,identity:identity,set:set$1,getReal:getReal,getDual:getDual,setReal:setReal,setDual:setDual,getTranslation:getTranslation,translate:translate,rotateX:rotateX,rotateY:rotateY,rotateZ:rotateZ,rotateByQuatAppend:rotateByQuatAppend,rotateByQuatPrepend:rotateByQuatPrepend,rotateAroundAxis:rotateAroundAxis,add:add$1,multiply:multiply$1,mul:mul$1,scale:scale$1,dot:dot$1,lerp:lerp$1,invert:invert,conjugate:conjugate,length:length$1,len:len$1,squaredLength:squaredLength$1,sqrLen:sqrLen$1,normalize:normalize$1,str:str$1,exactEquals:exactEquals$1,equals:equals$1});function create(){var t=new ARRAY_TYPE(2);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0),t}function clone(t){var a=new ARRAY_TYPE(2);return a[0]=t[0],a[1]=t[1],a}function fromValues(t,a){var r=new ARRAY_TYPE(2);return r[0]=t,r[1]=a,r}function copy(t,a){return t[0]=a[0],t[1]=a[1],t}function set(t,a,r){return t[0]=a,t[1]=r,t}function add(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t}function subtract(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t}function multiply(t,a,r){return t[0]=a[0]*r[0],t[1]=a[1]*r[1],t}function divide(t,a,r){return t[0]=a[0]/r[0],t[1]=a[1]/r[1],t}function ceil(t,a){return t[0]=Math.ceil(a[0]),t[1]=Math.ceil(a[1]),t}function floor(t,a){return t[0]=Math.floor(a[0]),t[1]=Math.floor(a[1]),t}function min(t,a,r){return t[0]=Math.min(a[0],r[0]),t[1]=Math.min(a[1],r[1]),t}function max(t,a,r){return t[0]=Math.max(a[0],r[0]),t[1]=Math.max(a[1],r[1]),t}function round(t,a){return t[0]=Math.round(a[0]),t[1]=Math.round(a[1]),t}function scale(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t}function scaleAndAdd(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t}function distance(t,a){var r=a[0]-t[0],n=a[1]-t[1];return Math.hypot(r,n)}function squaredDistance(t,a){var r=a[0]-t[0],n=a[1]-t[1];return r*r+n*n}function length(t){var a=t[0],r=t[1];return Math.hypot(a,r)}function squaredLength(t){var a=t[0],r=t[1];return a*a+r*r}function negate(t,a){return t[0]=-a[0],t[1]=-a[1],t}function inverse(t,a){return t[0]=1/a[0],t[1]=1/a[1],t}function normalize(t,a){var r=a[0],n=a[1],e=r*r+n*n;return e>0&&(e=1/Math.sqrt(e)),t[0]=a[0]*e,t[1]=a[1]*e,t}function dot(t,a){return t[0]*a[0]+t[1]*a[1]}function cross(t,a,r){var n=a[0]*r[1]-a[1]*r[0];return t[0]=t[1]=0,t[2]=n,t}function lerp(t,a,r,n){var e=a[0],o=a[1];return t[0]=e+n*(r[0]-e),t[1]=o+n*(r[1]-o),t}function random(t,a){a=a||1;var r=2*RANDOM()*Math.PI;return t[0]=Math.cos(r)*a,t[1]=Math.sin(r)*a,t}function transformMat2(t,a,r){var n=a[0],e=a[1];return t[0]=r[0]*n+r[2]*e,t[1]=r[1]*n+r[3]*e,t}function transformMat2d(t,a,r){var n=a[0],e=a[1];return t[0]=r[0]*n+r[2]*e+r[4],t[1]=r[1]*n+r[3]*e+r[5],t}function transformMat3(t,a,r){var n=a[0],e=a[1];return t[0]=r[0]*n+r[3]*e+r[6],t[1]=r[1]*n+r[4]*e+r[7],t}function transformMat4(t,a,r){var n=a[0],e=a[1];return t[0]=r[0]*n+r[4]*e+r[12],t[1]=r[1]*n+r[5]*e+r[13],t}function rotate(t,a,r,n){var e=a[0]-r[0],o=a[1]-r[1],u=Math.sin(n),s=Math.cos(n);return t[0]=e*s-o*u+r[0],t[1]=e*u+o*s+r[1],t}function angle(t,a){var r=t[0],n=t[1],e=a[0],o=a[1],u=Math.sqrt((r*r+n*n)*(e*e+o*o)),s=u&&(r*e+n*o)/u;return Math.acos(Math.min(Math.max(s,-1),1))}function zero(t){return t[0]=0,t[1]=0,t}function str(t){return"vec2("+t[0]+", "+t[1]+")"}function exactEquals(t,a){return t[0]===a[0]&&t[1]===a[1]}function equals(t,a){var r=t[0],n=t[1],e=a[0],o=a[1];return Math.abs(r-e)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(e))&&Math.abs(n-o)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(o))}var len=length,sub=subtract,mul=multiply,div=divide,dist=distance,sqrDist=squaredDistance,sqrLen=squaredLength,forEach=function(){var t=create();return function(a,r,n,e,o,u){var s,i;for(r||(r=2),n||(n=0),i=e?Math.min(e*r+n,a.length):a.length,s=n;s<i;s+=r)t[0]=a[s],t[1]=a[s+1],o(t,t,u),a[s]=t[0],a[s+1]=t[1];return a}}(),vec2=Object.freeze({__proto__:null,create:create,clone:clone,fromValues:fromValues,copy:copy,set:set,add:add,subtract:subtract,multiply:multiply,divide:divide,ceil:ceil,floor:floor,min:min,max:max,round:round,scale:scale,scaleAndAdd:scaleAndAdd,distance:distance,squaredDistance:squaredDistance,length:length,squaredLength:squaredLength,negate:negate,inverse:inverse,normalize:normalize,dot:dot,cross:cross,lerp:lerp,random:random,transformMat2:transformMat2,transformMat2d:transformMat2d,transformMat3:transformMat3,transformMat4:transformMat4,rotate:rotate,angle:angle,zero:zero,str:str,exactEquals:exactEquals,equals:equals,len:len,sub:sub,mul:mul,div:div,dist:dist,sqrDist:sqrDist,sqrLen:sqrLen,forEach:forEach});globalThis.glMatrix=common,globalThis.glMatrix.mat2=mat2,globalThis.glMatrix.mat2d=mat2d,globalThis.glMatrix.mat3=mat3,globalThis.glMatrix.mat4=mat4,globalThis.glMatrix.quat=quat,globalThis.glMatrix.quat2=quat2,globalThis.glMatrix.vec2=vec2,globalThis.glMatrix.vec3=vec3,globalThis.glMatrix.vec4=vec4;
}

// 3rdparty/poly-decomp.js
{
function lineInt(o,n,t){t=t||0;var e,l,p,g,r,i,y,u=[0,0];return e=o[1][1]-o[0][1],l=o[0][0]-o[1][0],p=e*o[0][0]+l*o[0][1],g=n[1][1]-n[0][1],r=n[0][0]-n[1][0],i=g*n[0][0]+r*n[0][1],scalar_eq(y=e*r-g*l,0,t)||(u[0]=(r*p-l*i)/y,u[1]=(e*i-g*p)/y),u}function lineSegmentsIntersect(o,n,t,e){var l=n[0]-o[0],p=n[1]-o[1],g=e[0]-t[0],r=e[1]-t[1];if(g*p-r*l==0)return!1;var i=(l*(t[1]-o[1])+p*(o[0]-t[0]))/(g*p-r*l),y=(g*(o[1]-t[1])+r*(t[0]-o[0]))/(r*l-g*p);return i>=0&&i<=1&&y>=0&&y<=1}function triangleArea(o,n,t){return(n[0]-o[0])*(t[1]-o[1])-(t[0]-o[0])*(n[1]-o[1])}function isLeft(o,n,t){return triangleArea(o,n,t)>0}function isLeftOn(o,n,t){return triangleArea(o,n,t)>=0}function isRight(o,n,t){return triangleArea(o,n,t)<0}function isRightOn(o,n,t){return triangleArea(o,n,t)<=0}var tmpPoint1=[],tmpPoint2=[];function collinear(o,n,t,e){if(e){var l=tmpPoint1,p=tmpPoint2;l[0]=n[0]-o[0],l[1]=n[1]-o[1],p[0]=t[0]-n[0],p[1]=t[1]-n[1];var g=l[0]*p[0]+l[1]*p[1],r=Math.sqrt(l[0]*l[0]+l[1]*l[1]),i=Math.sqrt(p[0]*p[0]+p[1]*p[1]);return Math.acos(g/(r*i))<e}return 0===triangleArea(o,n,t)}function sqdist(o,n){var t=n[0]-o[0],e=n[1]-o[1];return t*t+e*e}function polygonAt(o,n){var t=o.length;return o[n<0?n%t+t:n%t]}function polygonClear(o){o.length=0}function polygonAppend(o,n,t,e){for(var l=t;l<e;l++)o.push(n[l])}function polygonMakeCCW(o){for(var n=0,t=o,e=1;e<o.length;++e)(t[e][1]<t[n][1]||t[e][1]===t[n][1]&&t[e][0]>t[n][0])&&(n=e);return!isLeft(polygonAt(o,n-1),polygonAt(o,n),polygonAt(o,n+1))&&(polygonReverse(o),!0)}function polygonReverse(o){for(var n=[],t=o.length,e=0;e!==t;e++)n.push(o.pop());for(e=0;e!==t;e++)o[e]=n[e]}function polygonIsReflex(o,n){return isRight(polygonAt(o,n-1),polygonAt(o,n),polygonAt(o,n+1))}var tmpLine1=[],tmpLine2=[];function polygonCanSee(o,n,t){var e,l,p=tmpLine1,g=tmpLine2;if(isLeftOn(polygonAt(o,n+1),polygonAt(o,n),polygonAt(o,t))&&isRightOn(polygonAt(o,n-1),polygonAt(o,n),polygonAt(o,t)))return!1;l=sqdist(polygonAt(o,n),polygonAt(o,t));for(var r=0;r!==o.length;++r)if((r+1)%o.length!==n&&r!==n&&isLeftOn(polygonAt(o,n),polygonAt(o,t),polygonAt(o,r+1))&&isRightOn(polygonAt(o,n),polygonAt(o,t),polygonAt(o,r))&&(p[0]=polygonAt(o,n),p[1]=polygonAt(o,t),g[0]=polygonAt(o,r),g[1]=polygonAt(o,r+1),e=lineInt(p,g),sqdist(polygonAt(o,n),e)<l))return!1;return!0}function polygonCanSee2(o,n,t){for(var e=0;e!==o.length;++e)if(e!==n&&e!==t&&(e+1)%o.length!==n&&(e+1)%o.length!==t&&lineSegmentsIntersect(polygonAt(o,n),polygonAt(o,t),polygonAt(o,e),polygonAt(o,e+1)))return!1;return!0}function polygonCopy(o,n,t,e){var l=e||[];if(polygonClear(l),n<t)for(var p=n;p<=t;p++)l.push(o[p]);else{for(p=0;p<=t;p++)l.push(o[p]);for(p=n;p<o.length;p++)l.push(o[p])}return l}function polygonGetCutEdges(o){for(var n=[],t=[],e=[],l=[],p=Number.MAX_VALUE,g=0;g<o.length;++g)if(polygonIsReflex(o,g))for(var r=0;r<o.length;++r)if(polygonCanSee(o,g,r)){t=polygonGetCutEdges(polygonCopy(o,g,r,l)),e=polygonGetCutEdges(polygonCopy(o,r,g,l));for(var i=0;i<e.length;i++)t.push(e[i]);t.length<p&&(n=t,p=t.length,n.push([polygonAt(o,g),polygonAt(o,r)]))}return n}function polygonDecomp(o){var n=polygonGetCutEdges(o);return n.length>0?polygonSlice(o,n):[o]}function polygonSlice(o,n){if(0===n.length)return[o];if(n instanceof Array&&n.length&&n[0]instanceof Array&&2===n[0].length&&n[0][0]instanceof Array){for(var t=[o],e=0;e<n.length;e++)for(var l=n[e],p=0;p<t.length;p++){var g=polygonSlice(t[p],l);if(g){t.splice(p,1),t.push(g[0],g[1]);break}}return t}l=n,e=o.indexOf(l[0]),p=o.indexOf(l[1]);return-1!==e&&-1!==p&&[polygonCopy(o,e,p),polygonCopy(o,p,e)]}function polygonIsSimple(o){var n,t=o;for(n=0;n<t.length-1;n++)for(var e=0;e<n-1;e++)if(lineSegmentsIntersect(t[n],t[n+1],t[e],t[e+1]))return!1;for(n=1;n<t.length-2;n++)if(lineSegmentsIntersect(t[0],t[t.length-1],t[n],t[n+1]))return!1;return!0}function getIntersectionPoint(o,n,t,e,l){l=l||0;var p=n[1]-o[1],g=o[0]-n[0],r=p*o[0]+g*o[1],i=e[1]-t[1],y=t[0]-e[0],u=i*t[0]+y*t[1],s=p*y-i*g;return scalar_eq(s,0,l)?[0,0]:[(y*r-g*u)/s,(p*u-i*r)/s]}function polygonQuickDecomp(o,n,t,e,l,p,g){p=p||100,g=g||0,l=l||25,n=void 0!==n?n:[],t=t||[],e=e||[];var r=[0,0],i=[0,0],y=[0,0],u=0,s=0,A=0,a=0,f=0,c=0,h=0,v=[],m=[],d=o,C=o;if(C.length<3)return n;if(++g>p)return console.warn("quickDecomp: max level ("+p+") reached."),n;for(var R=0;R<o.length;++R)if(polygonIsReflex(d,R)){t.push(d[R]),u=s=Number.MAX_VALUE;for(var q=0;q<o.length;++q)isLeft(polygonAt(d,R-1),polygonAt(d,R),polygonAt(d,q))&&isRightOn(polygonAt(d,R-1),polygonAt(d,R),polygonAt(d,q-1))&&(y=getIntersectionPoint(polygonAt(d,R-1),polygonAt(d,R),polygonAt(d,q),polygonAt(d,q-1)),isRight(polygonAt(d,R+1),polygonAt(d,R),y)&&(A=sqdist(d[R],y))<s&&(s=A,i=y,c=q)),isLeft(polygonAt(d,R+1),polygonAt(d,R),polygonAt(d,q+1))&&isRightOn(polygonAt(d,R+1),polygonAt(d,R),polygonAt(d,q))&&(y=getIntersectionPoint(polygonAt(d,R+1),polygonAt(d,R),polygonAt(d,q),polygonAt(d,q+1)),isLeft(polygonAt(d,R-1),polygonAt(d,R),y)&&(A=sqdist(d[R],y))<u&&(u=A,r=y,f=q));if(c===(f+1)%o.length)y[0]=(i[0]+r[0])/2,y[1]=(i[1]+r[1])/2,e.push(y),R<f?(polygonAppend(v,d,R,f+1),v.push(y),m.push(y),0!==c&&polygonAppend(m,d,c,d.length),polygonAppend(m,d,0,R+1)):(0!==R&&polygonAppend(v,d,R,d.length),polygonAppend(v,d,0,f+1),v.push(y),m.push(y),polygonAppend(m,d,c,R+1));else{if(c>f&&(f+=o.length),a=Number.MAX_VALUE,f<c)return n;for(q=c;q<=f;++q)isLeftOn(polygonAt(d,R-1),polygonAt(d,R),polygonAt(d,q))&&isRightOn(polygonAt(d,R+1),polygonAt(d,R),polygonAt(d,q))&&(A=sqdist(polygonAt(d,R),polygonAt(d,q)))<a&&polygonCanSee2(d,R,q)&&(a=A,h=q%o.length);R<h?(polygonAppend(v,d,R,h+1),0!==h&&polygonAppend(m,d,h,C.length),polygonAppend(m,d,0,R+1)):(0!==R&&polygonAppend(v,d,R,C.length),polygonAppend(v,d,0,h+1),polygonAppend(m,d,h,R+1))}return v.length<m.length?(polygonQuickDecomp(v,n,t,e,l,p,g),polygonQuickDecomp(m,n,t,e,l,p,g)):(polygonQuickDecomp(m,n,t,e,l,p,g),polygonQuickDecomp(v,n,t,e,l,p,g)),n}return n.push(o),n}function polygonRemoveCollinearPoints(o,n){for(var t=0,e=o.length-1;o.length>3&&e>=0;--e)collinear(polygonAt(o,e-1),polygonAt(o,e),polygonAt(o,e+1),n)&&(o.splice(e%o.length,1),t++);return t}function polygonRemoveDuplicatePoints(o,n){for(var t=o.length-1;t>=1;--t)for(var e=o[t],l=t-1;l>=0;--l)points_eq(e,o[l],n)&&o.splice(t,1)}function scalar_eq(o,n,t){return t=t||0,Math.abs(o-n)<=t}function points_eq(o,n,t){return scalar_eq(o[0],n[0],t)&&scalar_eq(o[1],n[1],t)}self.polyDecomp={decomp:polygonDecomp,quickDecomp:polygonQuickDecomp,isSimple:polygonIsSimple,removeCollinearPoints:polygonRemoveCollinearPoints,removeDuplicatePoints:polygonRemoveDuplicatePoints,makeCCW:polygonMakeCCW};
}

// lib/c3.js
{
let isReady=!1,hasAppStarted=!1,buildMode="dev";const internalApiToken=Symbol("Construct internal API token");let internalApiTokenAccessesRemaining=16;const C3=self.C3=class{constructor(){throw TypeError("static class can't be instantiated")}static _GetInternalAPIToken(){if(internalApiTokenAccessesRemaining<=0)throw new Error("cannot obtain internal API token");return--internalApiTokenAccessesRemaining,internalApiToken}static SetReady(){isReady=!0}static IsReady(){return isReady}static SetAppStarted(){hasAppStarted=!0}static HasAppStarted(){return hasAppStarted}static SetBuildMode(e){buildMode=e}static GetBuildMode(){return buildMode}static IsReleaseBuild(){return"final"===buildMode}};C3.isDebug=!1,C3.isDebugDefend=!1,C3.hardwareConcurrency=navigator.hardwareConcurrency||2,self.C3X={};
}

// ../lib/queryParser.js
{
const C3=self.C3;C3.QueryParser=class{constructor(e){this._queryString=e,this._parameters=new Map,this._Parse()}_Parse(){let e=this._queryString;(e.startsWith("?")||e.startsWith("#"))&&(e=e.substr(1));const r=e.split("&");for(const e of r)this._ParseParameter(e)}_ParseParameter(e){if(!e)return;if(!e.includes("="))return void this._parameters.set(e,null);const r=e.indexOf("="),t=decodeURIComponent(e.substring(0,r)),s=decodeURIComponent(e.substring(r+1));this._parameters.set(t,s)}LogAll(){for(const e of this._parameters)console.log("[QueryParser] Parameter '"+e[0]+"' = "+(null===e[1]?"null":"'"+e[1]+"'"))}Has(e){return this._parameters.has(e)}Get(e){const r=this._parameters.get(e);return void 0===r?null:r}ClearHash(){history.replaceState("",document.title,location.pathname+location.search)}Reparse(e){this._queryString=e,this._parameters.clear(),this._Parse()}},C3.QueryString=new C3.QueryParser(location.search),C3.LocationHashString=new C3.QueryParser(location.hash),C3.QueryString.Has("perf")&&(C3.isPerformanceProfiling=!0),"dev"!==C3.QueryString.Get("mode")&&C3.SetBuildMode("final");
}

// ../lib/detect/detect.js
{
const C3=self.C3,UNKNOWN="(unknown)";C3.Platform={OS:UNKNOWN,OSVersion:UNKNOWN,Browser:UNKNOWN,BrowserVersion:UNKNOWN,BrowserVersionNumber:NaN,BrowserEngine:UNKNOWN,Context:"browser",IsDesktop:!0,IsMobile:!1,IsAppleOS:!1,IsIpadOS:!1,GetDetailedInfo:async()=>{}};const windowsNTVerMap=new Map([[5,"2000"],[5.1,"XP"],[5.2,"XP"],[6,"Vista"],[6.1,"7"],[6.2,"8"],[6.3,"8.1"],[10,"10"]]);function GetWindowsNTVersionName(r){const o=parseFloat(r),e=windowsNTVerMap.get(o);return e||(o>=13?"11":"NT "+r)}const uaStr=navigator.userAgent,uaData=navigator["userAgentData"];if(uaData&&uaData["brands"].length>0){C3.Platform.OS=uaData["platform"],C3.Platform.IsMobile=uaData["mobile"],C3.Platform.IsDesktop=!C3.Platform.IsMobile;const r=new Map([["Google Chrome","Chrome"],["Microsoft Edge","Edge"],["Opera","Opera"],["Opera GX","Opera GX"],["Mozilla Firefox","Firefox"],["Apple Safari","Safari"],["NW.js","NW.js"]]),o=new Map([["Chromium","Chromium"],["Gecko","Gecko"],["WebKit","WebKit"]]);function ReadBrandList(e){let t="",a="",s="",n="";for(const i of e){const e=r.get(i["brand"]);!t&&e&&(t=e,a=i["version"]);const m=o.get(i["brand"]);!s&&m&&(s=m,n=i["version"])}t||"Chromium"!==s||(C3.Platform.Browser="Chromium",C3.Platform.BrowserVersion=n),C3.Platform.Browser=t||UNKNOWN,C3.Platform.BrowserVersion=a||UNKNOWN,C3.Platform.BrowserEngine=s||UNKNOWN}ReadBrandList(uaData["brands"]);let e=!1;C3.Platform.GetDetailedInfo=async()=>{if(!e)try{const r=await navigator["userAgentData"]["getHighEntropyValues"](["platformVersion","fullVersionList"]);ReadBrandList(r["fullVersionList"]),"Windows"===C3.Platform.OS?C3.Platform.OSVersion=GetWindowsNTVersionName(r["platformVersion"]):C3.Platform.OSVersion=r["platformVersion"],e=!0}catch(r){console.warn("Failed to get detailed user agent information: ",r)}}}else{function RunTest(r,o){const e=Array.isArray(r)?r:[r];for(const r of e){const e=r.exec(uaStr);if(e){o(e);break}}}RunTest(/windows\s+nt\s+([\d\.]+)/i,(r=>{C3.Platform.OS="Windows";const o=r[1];C3.Platform.OSVersion=GetWindowsNTVersionName(o)})),RunTest(/mac\s+os\s+x\s+([\d\._]+)/i,(r=>{C3.Platform.OS="macOS",C3.Platform.OSVersion=r[1].replace(/_/g,".")})),RunTest(/CrOS/,(()=>{C3.Platform.OS="Chrome OS"})),RunTest(/linux|openbsd|freebsd|netbsd/i,(()=>{C3.Platform.OS="Linux"})),RunTest(/android/i,(()=>{C3.Platform.OS="Android"})),RunTest(/android\s+([\d\.]+)/i,(r=>{C3.Platform.OS="Android",C3.Platform.OSVersion=r[1]})),C3.Platform.OS===UNKNOWN&&(RunTest(/(iphone|ipod|ipad)/i,(r=>{C3.Platform.OS="iOS"})),RunTest([/iphone\s+os\s+([\d\._]+)/i,/ipad[^)]*os\s+([\d\._]+)/i],(r=>{C3.Platform.OS="iOS",C3.Platform.OSVersion=r[1].replace(/_/g,".")})));const t=/chrome\//i.test(uaStr),a=/chromium\//i.test(uaStr),s=/edg\//i.test(uaStr),n=/OPR\//.test(uaStr),i=/nwjs/i.test(uaStr),m=/safari\//i.test(uaStr),l=/webkit/i.test(uaStr);s||n||RunTest(/chrome\/([\d\.]+)/i,(r=>{C3.Platform.Browser="Chrome",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium"})),RunTest(/edg\/([\d\.]+)/i,(r=>{C3.Platform.Browser="Edge",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium"})),RunTest(/OPR\/([\d\.]+)/,(r=>{C3.Platform.Browser="Opera",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium"})),RunTest(/chromium\/([\d\.]+)/i,(r=>{C3.Platform.Browser="Chromium",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium"})),RunTest(/nwjs\/[0-9.]+/i,(r=>{C3.Platform.Browser="NW.js",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium",C3.Platform.Context="nwjs"})),RunTest(/firefox\/([\d\.]+)/i,(r=>{C3.Platform.Browser="Firefox",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Gecko"})),!m||t||a||s||n||i||(C3.Platform.Browser="Safari",C3.Platform.BrowserEngine="WebKit",RunTest(/version\/([\d\.]+)/i,(r=>{C3.Platform.BrowserVersion=r[1]})),RunTest(/crios\/([\d\.]+)/i,(r=>{C3.Platform.Browser="Chrome for iOS",C3.Platform.BrowserVersion=r[1]})),RunTest(/fxios\/([\d\.]+)/i,(r=>{C3.Platform.Browser="Firefox for iOS",C3.Platform.BrowserVersion=r[1]})),RunTest(/edgios\/([\d\.]+)/i,(r=>{C3.Platform.Browser="Edge for iOS",C3.Platform.BrowserVersion=r[1]}))),C3.Platform.BrowserEngine===UNKNOWN&&l&&(C3.Platform.BrowserEngine="WebKit"),"Android"===C3.Platform.OS&&"Safari"===C3.Platform.Browser&&(C3.Platform.Browser="Stock");const f=new Set(["Windows","macOS","Linux","Chrome OS"]).has(C3.Platform.OS)||"nwjs"===C3.Platform.Context;C3.Platform.IsDesktop=f,C3.Platform.IsMobile=!f}"Chrome"===C3.Platform.Browser&&"browser"===C3.Platform.Context&&/wv\)/.test(uaStr)&&(C3.Platform.Context="webview"),"nwjs"!==C3.Platform.Context&&"undefined"!=typeof window&&(window.matchMedia&&window.matchMedia("(display-mode: standalone)").matches||navigator["standalone"])&&(C3.Platform.Context="webapp"),C3.Platform.BrowserVersionNumber=parseFloat(C3.Platform.BrowserVersion);const looksLikeIPadOS="macOS"===C3.Platform.OS&&navigator["maxTouchPoints"]&&navigator["maxTouchPoints"]>2;looksLikeIPadOS&&(C3.Platform.OS="iOS",C3.Platform.OSVersion=C3.Platform.BrowserVersion,C3.Platform.IsDesktop=!1,C3.Platform.IsMobile=!0,C3.Platform.IsIpadOS=!0),C3.Platform.IsAppleOS="macOS"===C3.Platform.OS||"iOS"===C3.Platform.OS;
}

// ../lib/storage/kvStorage.js
{
"use strict";{const e=2,t="keyvaluepairs",r=new Map,n="undefined"!=typeof IDBObjectStore&&"function"==typeof IDBObjectStore.prototype.getAll,o="undefined"!=typeof IDBObjectStore&&"function"==typeof IDBObjectStore.prototype.getAllKeys;function s(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}function a(e){return new Promise(((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error),e.onabort=()=>r(e.error)}))}function c(e,t){return u(e,t)}function i(e,t){return u(e,t,!0)}async function u(e,n,o=!1,s=!0){const a=await l(e);try{return n(a.transaction([t],o?"readwrite":"readonly"))}catch(t){if(s&&"InvalidStateError"===t["name"])return r.delete(e),u(e,n,o,!1);throw t}}function l(e){f(e);let t=r.get(e);return t instanceof Promise||(t=y(e),r.set(e,t),t.catch((t=>r.delete(e)))),t}async function y(r){f(r);const n=indexedDB.open(r,e);return n.addEventListener("upgradeneeded",(e=>{try{e.target.result.createObjectStore(t)}catch(e){console.error(`Failed to create objectstore for database ${r}`,e)}})),s(n)}function f(e){if("string"!=typeof e)throw new TypeError("expected string")}function d(e,r){const n=e.objectStore(t).openCursor();return new Promise((e=>{const t=[];n.onsuccess=n=>{const o=n.target.result;if(o){switch(r){case"entries":t.push([o.key,o.value]);break;case"keys":t.push(o.key);break;case"values":t.push(o.value)}o.continue()}else e(t)}}))}class m{constructor(e){f(e),this.name=e}async ready(){await l(this.name)}set(e,r){return f(e),i(this.name,(async n=>{const o=s(n.objectStore(t).put(r,e)),c=a(n);await Promise.all([c,o])}))}get(e){return f(e),c(this.name,(async r=>{const n=s(r.objectStore(t).get(e)),o=a(r),[c,i]=await Promise.all([o,n]);return i}))}delete(e){return f(e),i(this.name,(async r=>{const n=s(r.objectStore(t).delete(e)),o=a(r);await Promise.all([o,n])}))}clear(){return i(this.name,(async e=>{const r=s(e.objectStore(t).clear()),n=a(e);await Promise.all([n,r])}))}keys(){return c(this.name,(async e=>{let r;if(o){r=s(e.objectStore(t).getAllKeys())}else r=d(e,"keys");const n=a(e),[c,i]=await Promise.all([n,r]);return i}))}values(){return c(this.name,(async e=>{let r;if(n){r=s(e.objectStore(t).getAll())}else r=d(e,"values");const o=a(e),[c,i]=await Promise.all([o,r]);return i}))}entries(){return c(this.name,(async e=>{const t=d(e,"entries"),r=a(e),[n,o]=await Promise.all([r,t]);return o}))}}self.KVStorageContainer=m}
}

// ../lib/storage/localForageAdaptor.js
{
"use strict";{const e=self.KVStorageContainer,t=[/no available storage method found/i,/an attempt was made to break through the security policy of the user agent/i,/the user denied permission to access the database/i,/a mutation operation was attempted on a database that did not allow mutations/i,/idbfactory\.open\(\) called in an invalid security context/i];new WeakMap;function r(e){throw new Error(`"${e}" is not implemented`)}function a(e){if("function"==typeof e)throw new Error("localforage callback API is not implemented; please use the promise API instead")}function o(e){return"object"==typeof e?new Promise((t=>{const{port1:r,port2:a}=new MessageChannel;a.onmessage=e=>t(e.data),r.postMessage(e)})):Promise.resolve(e)}class s{constructor(e){this._inst=e,this._isInMemory=!this._inst,this._isInMemory||"undefined"!=typeof indexedDB||(this._isInMemory=!0,console.warn("Unable to use local storage because IndexedDB API is not available")),this._memoryStorage=new Map}_MaybeSwitchToMemoryFallback(e){if(!this._isInMemory)for(const r of t)if(e&&r.test(e.message)){console.error("Unable to use local storage, reverting to in-memory store: ",e,e.message),this._isInMemory=!0;break}}async _getItemFallback(e){const t=this._memoryStorage.get(e),r=await o(t);return void 0===r?null:r}async _setItemFallback(e,t){t=await o(t),this._memoryStorage.set(e,t)}_removeItemFallback(e){this._memoryStorage.delete(e)}_clearFallback(){this._memoryStorage.clear()}_keysFallback(){return Array.from(this._memoryStorage.keys())}IsInMemory(){return this._isInMemory}GetMemoryStorage(){return this._memoryStorage}SetMemoryStorage(e){this._memoryStorage=e}async getItem(e,t){if(a(t),this._isInMemory)return await this._getItemFallback(e);let r;try{r=await this._inst.get(e)}catch(t){return this._MaybeSwitchToMemoryFallback(t),this._isInMemory?await this._getItemFallback(e):(console.error(`Error reading '${e}' from storage, returning null: `,t),null)}return void 0===r?null:r}async setItem(e,t,r){if(a(r),void 0===t&&(t=null),this._isInMemory)await this._setItemFallback(e,t);else try{await this._inst.set(e,t)}catch(r){if(this._MaybeSwitchToMemoryFallback(r),!this._isInMemory)throw r;await this._setItemFallback(e,t)}}async removeItem(e,t){if(a(t),this._isInMemory)this._removeItemFallback(e);else try{await this._inst.delete(e)}catch(t){this._MaybeSwitchToMemoryFallback(t),this._isInMemory?this._removeItemFallback(e):console.error(`Error removing '${e}' from storage: `,t)}}async clear(e){if(a(e),this._isInMemory)this._clearFallback();else try{await this._inst.clear()}catch(e){this._MaybeSwitchToMemoryFallback(e),this._isInMemory?this._clearFallback():console.error("Error clearing storage: ",e)}}async keys(e){if(a(e),this._isInMemory)return this._keysFallback();let t=[];try{t=await this._inst.keys()}catch(e){if(this._MaybeSwitchToMemoryFallback(e),this._isInMemory)return this._keysFallback();console.error("Error getting storage keys: ",e)}return t}ready(e){return a(e),this._isInMemory?Promise.resolve(!0):this._inst.ready()}createInstance(t){if(t.forceInMemoryFallback)return new s(null);{const r=t.name;if("string"!=typeof r)throw new TypeError("invalid store name");const a=new e(r);return new s(a)}}length(e){r("localforage.length()")}key(e,t){r("localforage.key()")}iterate(e,t){r("localforage.iterate()")}setDriver(e){r("localforage.setDriver()")}config(e){r("localforage.config()")}defineDriver(e){r("localforage.defineDriver()")}driver(){r("localforage.driver()")}supports(e){r("localforage.supports()")}dropInstance(){r("localforage.dropInstance()")}}self["localforage"]=new s(new e("localforage"))}
}

// ../lib/misc/supports.js
{
const C3=self.C3;if(C3.Supports={},C3.Supports.WebAnimations=(()=>{try{if("undefined"==typeof document)return!1;const e=document.createElement("div");if(void 0===e.animate)return!1;return void 0!==e.animate([{opacity:"0"},{opacity:"1"}],1e3).reverse}catch(e){return!1}})(),C3.Supports.DialogElement="undefined"!=typeof HTMLDialogElement,C3.Supports.RequestIdleCallback=!!self.requestIdleCallback,C3.Supports.ImageBitmap=!!self.createImageBitmap,C3.Supports.ImageBitmapOptions=!1,C3.Supports.ImageBitmapOptionsResize=!1,C3.Supports.ImageBitmap){try{self.createImageBitmap(new ImageData(32,32),{"premultiplyAlpha":"none"}).then((()=>{C3.Supports.ImageBitmapOptions=!0})).catch((()=>{C3.Supports.ImageBitmapOptions=!1}))}catch(e){C3.Supports.ImageBitmapOptions=!1}try{self.createImageBitmap(new ImageData(32,32),{"resizeWidth":10,"resizeHeight":10}).then((e=>{C3.Supports.ImageBitmapOptionsResize=10===e.width&&10===e.height})).catch((()=>{C3.Supports.ImageBitmapOptionsResize=!1}))}catch(e){C3.Supports.ImageBitmapOptionsResize=!1}}if(C3.Supports.ClipboardReadText=!(!navigator["clipboard"]||!navigator["clipboard"]["readText"]),C3.Supports.PermissionsQuery=!(!navigator["permissions"]||!navigator["permissions"]["query"]),C3.Supports.ClipboardPermissionsQuery=!1,C3.Supports.PermissionsQuery){const e={"name":"clipboard-read"};navigator["permissions"]["query"](e).then((()=>{C3.Supports.ClipboardPermissionsQuery=!0})).catch((()=>{C3.Supports.ClipboardPermissionsQuery=!1}))}C3.Supports.AsyncClipboardApi=!!(navigator["permissions"]&&navigator["clipboard"]&&self["ClipboardItem"]),C3.Supports.Proxies="undefined"!=typeof Proxy,C3.Supports.DownloadAttribute=(()=>{if("undefined"==typeof document)return!1;return void 0!==document.createElement("a").download})(),C3.Supports.Fetch="function"==typeof fetch,C3.Supports.PersistentStorage=!!(self.isSecureContext&&"Opera"!==C3.Platform.Browser&&navigator["storage"]&&navigator["storage"]["persist"]),C3.Supports.StorageQuotaEstimate=!!(self.isSecureContext&&navigator["storage"]&&navigator["storage"]["estimate"]),C3.Supports.Fullscreen=(()=>{if("undefined"==typeof document)return!1;if("iOS"===C3.Platform.OS)return!1;const e=document.documentElement;return!!(e.requestFullscreen||e.msRequestFullscreen||e.mozRequestFullScreen||e.webkitRequestFullscreen)})(),C3.Supports.ImageDecoder=void 0!==self["ImageDecoder"],C3.Supports.WebCodecs=!!self["VideoEncoder"],C3.Supports.NativeFileSystemAPI=!!self["showOpenFilePicker"],C3.Supports.QueryLocalFonts=!!self["queryLocalFonts"],C3.Supports.UserActivation=!!navigator["userActivation"],C3.Supports.CanvasToBlobWebP=!1,(async()=>{let e;"undefined"==typeof document?e=new OffscreenCanvas(32,32):(e=document.createElement("canvas"),e.width=32,e.height=32);const t=e.getContext("2d");t.fillStyle="blue",t.fillRect(0,0,32,32);let o=null;try{e["convertToBlob"]?o=await e["convertToBlob"]({"type":"image/webp","quality":1}):e.toBlob&&(o=await new Promise((t=>e.toBlob(t,"image/webp",1)))),C3.Supports.CanvasToBlobWebP=o&&"image/webp"===o.type}catch(e){C3.Supports.CanvasToBlobWebP=!1}})();
}

// ../lib/misc/polyfills.js
{
const C3=self.C3;if(!String.prototype.trimStart){const t=/^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*/;String.prototype.trimStart=function(){return this.replace(t,"")}}if(!String.prototype.trimEnd){const r=/[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*$/;String.prototype.trimEnd=function(){return this.replace(r,"")}}if(String.prototype.replaceAll||(String.prototype.replaceAll=function(t,r){return this.replace(new RegExp(C3.EscapeRegex(t),"g"),r)}),Array.prototype.values||(Array.prototype.values=function*(){for(const t of this)yield t}),!Array.prototype.flat){function arrayFlat(t,r){return t.reduce(((t,e)=>r>0&&Array.isArray(e)?(Array.prototype.push.apply(t,arrayFlat(e,r-1)),t):(t.push(e),t)),[])}Array.prototype.flat=function(t=1){return arrayFlat(this,t)}}Array.prototype.at||(Array.prototype.at=function(t){if((t=Math.trunc(t)||0)<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]}),String.prototype.at||(String.prototype.at=function(t){if((t=Math.trunc(t)||0)<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]}),RegExp.escape||(RegExp.escape=function(t){return String(t).replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}),Set.prototype.isSubsetOf||(Set.prototype.isSubsetOf=function(t){if(!(t instanceof Set))throw new TypeError("argument must be a Set");for(const r of this)if(!t.has(r))return!1;return!0}),navigator["storage"]&&!navigator["storage"]["estimate"]&&navigator["webkitTemporaryStorage"]&&navigator["webkitTemporaryStorage"]["queryUsageAndQuota"]&&(navigator["storage"]["estimate"]=function(){return new Promise(((t,r)=>navigator["webkitTemporaryStorage"]["queryUsageAndQuota"](((r,e)=>t({"usage":r,"quota":e})),r)))}),void 0===self.isSecureContext&&(self.isSecureContext="https:"===location.protocol),void 0===self["globalThis"]&&(self["globalThis"]=self);
}

// lib/misc/assert.js
{
const C3=self.C3;function assertFail(e){let s="Assertion failure: "+e+"\n\nStack trace:\n"+C3.GetCallStack();console.error(s)}self.assert=function(e,s){e||assertFail(s)};
}

// ../lib/misc/typeChecks.js
{
const C3=self.C3,C3X=self.C3X;C3.IsNumber=function(e){return"number"==typeof e},C3.IsFiniteNumber=function(e){return C3.IsNumber(e)&&isFinite(e)},C3.RequireNumber=function(e){if(!C3.IsNumber(e))throw new TypeError("expected number")},C3.RequireOptionalNumber=function(e){C3.IsNullOrUndefined(e)},C3.RequireNumberInRange=function(e,n,r){if(!C3.IsNumber(e)||isNaN(e)||n>e||r<e)throw new RangeError("number outside of range")},C3.RequireAllNumber=function(...e){for(let n of e);},C3.RequireFiniteNumber=function(e){if(!C3.IsFiniteNumber(e))throw new TypeError("expected finite number")},C3.RequireOptionalFiniteNumber=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllFiniteNumber=function(...e){for(let n of e);},C3.IsString=function(e){return"string"==typeof e},C3.RequireString=function(e){if(!C3.IsString(e))throw new TypeError("expected string")},C3.RequireOptionalString=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllString=function(...e){for(let n of e);},C3.IsSimpleObject=function(e){if("object"!=typeof e||null===e)return!1;let n=Object.getPrototypeOf(e);return n?n.constructor===Object:null===n},C3.RequireSimpleObject=function(e){if(!C3.IsSimpleObject(e))throw new TypeError("expected simple object")},C3.RequireOptionalSimpleObject=function(e){if(!C3.IsNullOrUndefined(e)&&!C3.IsSimpleObject(e))throw new TypeError("expected simple object")},C3.IsObject=function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)},C3.RequireObject=function(e){if(!C3.IsObject(e))throw new TypeError("expected object")},C3.RequireOptionalObject=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllObject=function(...e){for(let n of e);},C3.IsFileLike=function(e){return C3.WeakIsInstanceOf(e,Blob)&&"string"==typeof e["name"]},C3.RequireFileLike=function(e){if(!C3.IsFileLike(e))throw new TypeError("expected file")},C3.RequireOptionalFileLike=function(e){C3.IsNullOrUndefined(e)},C3.IsArray=function(e){return Array.isArray(e)},C3.RequireArray=function(e){if(!C3.IsArray(e))throw new TypeError("expected array")},C3.RequireOptionalArray=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllArray=function(...e){for(let n of e);},C3.Is2DArray=function(e){return!!C3.IsArray(e)&&(!e.length||!!C3.IsArray(e[0]))},C3.Require2DArray=function(e){if(!C3.Is2DArray(e))throw new TypeError("expected 2d array");for(let n of e)if(!C3.IsArray(n))throw new TypeError("expected 2d array")},C3.RequireOptional2DArray=function(e){C3.IsNullOrUndefined(e)},C3.IsFunction=function(e){return"function"==typeof e},C3.RequireFunction=function(e,n){if(!C3.IsFunction(e))throw new TypeError("expected function");if(!C3.IsNullOrUndefined(n)&&e!==n)throw new TypeError("expected same function reference")},C3.RequireOptionalFunction=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllFunction=function(...e){for(let n of e);},C3.RequireAnyFunction=function(e,...n){if(!C3.IsFunction(e))throw new TypeError("expected function");if(!n.length)throw new Error("missing comparison functions");for(let r of n)if(!C3.IsNullOrUndefined(r)&&e===r)return;throw new TypeError("expected same function reference")},C3.RequireOptionalAllFunction=function(...e){if(!C3.IsNullOrUndefined(e))for(let n of e);},C3.IsInstanceOf=function(e,n){return e instanceof n},C3.IsInstanceOfAny=function(e,...n){for(let r of n)if(C3.IsInstanceOf(e,r))return!0;return!1},C3.RequireInstanceOf=function(e,n){if(!C3.IsInstanceOf(e,n))throw new TypeError("unexpected type")},C3.RequireOptionalInstanceOf=function(e,n){C3.IsNullOrUndefined(e)},C3.RequireAllInstanceOf=function(e,...n){for(let e of n);},C3.RequireAnyInstanceOf=function(e,...n){if(!C3.IsInstanceOfAny(e,...n))throw new TypeError("unexpected type")},C3.RequireAnyOptionalInstanceOf=function(e,...n){if(!C3.IsNullOrUndefined(e)&&!C3.IsInstanceOfAny(e,...n))throw new TypeError("unexpected type")},C3.IsArrayOf=function(e,n){for(let r of e)if(!C3.IsInstanceOf(r,n))return!1;return!0},C3.IsArrayOfFiniteNumbers=function(e){for(let n of e)if(!C3.IsFiniteNumber(n))return!1;return!0},C3.RequireArrayOf=function(e,n){for(let n of e);},C3.RequireOptionalArrayOf=function(e,n){if(!C3.IsNullOrUndefined(e))for(let n of e);},C3.RequireOptionalArrayOfFunctions=function(e,n){if(!C3.IsNullOrUndefined(e))for(let n of e);},C3.RequireArrayOfAny=function(e,...n){for(let n of e);},C3.RequireOptionalArrayOfAny=function(e,...n){if(!C3.IsNullOrUndefined(e))for(let n of e);},C3.IsDOMNode=function(e,n){return!(C3.IsNullOrUndefined(e)||!C3.IsString(e.nodeName))&&(!n||C3.equalsNoCase(e.nodeName,n))},C3.RequireDOMNode=function(e,n){if(C3.IsNullOrUndefined(e)||!C3.IsString(e.nodeName))throw new TypeError("expected DOM node");if(n&&!C3.equalsNoCase(e.nodeName,n))throw new TypeError(`expected DOM '${n}' node`)},C3.RequireOptionalDOMNode=function(e,n){C3.IsNullOrUndefined(e)},C3.IsHTMLElement=function(e,n){return!(C3.IsNullOrUndefined(e)||!C3.IsString(e.tagName))&&(!n||C3.equalsNoCase(e.tagName,n))},C3.RequireHTMLElement=function(e,n){if(C3.IsNullOrUndefined(e)||!C3.IsString(e.tagName))throw new TypeError("expected HTML element");if(n&&!C3.equalsNoCase(e.tagName,n))throw new TypeError(`expected HTML '${n}' element`)},C3.RequireOptionalHTMLElement=function(e,n){C3.IsNullOrUndefined(e)},C3.IsDrawable=function(e){return C3.IsHTMLElement(e,"img")||C3.IsHTMLElement(e,"canvas")||C3.IsHTMLElement(e,"video")||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap},C3.RequireDrawable=function(e){if(!C3.IsDrawable(e))throw new TypeError("expected drawable")},C3.RequireOptionalDrawable=function(e){C3.IsNullOrUndefined(e)},C3.IsDrawableOrImageData=function(e){return e instanceof ImageData||C3.IsDrawable(e)},C3.RequireDrawableOrImageData=function(e){if(!C3.IsDrawableOrImageData(e))throw new TypeError("expected drawable or image data")},C3.RequireOptionalDrawableOrImageData=function(e){if(!C3.IsNullOrUndefined(e)&&!C3.IsDrawableOrImageData(e))throw new TypeError("expected drawable or image data")},C3.IsStringLike=function(e){return"string"==typeof e||C3.HtmlString&&e instanceof C3.HtmlString||e instanceof C3.BBString},C3.RequireStringLike=function(e){if(!C3.IsStringLike(e))throw new TypeError("expected string-like")},C3.RequireOptionalStringLike=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllStringLike=function(...e){for(let n of e);},C3.RequireOverride=function(){throw new Error("must be overridden")},C3.NotYetImplemented=function(){throw new Error("not yet implemented")},C3.IsGeneratorFunction=function(e){return e.constructor===function*(){}.constructor},C3.RequireGeneratorFunction=function(e){if(!C3.IsGeneratorFunction(e))throw new Error("expected generator function")},C3.IsIterable=function(e){return"function"===e[Symbol.iterator]},C3.RequireIterable=function(e){if(!C3.IsIterable(e))throw new Error("expected iterable")},C3.IsDefined=function(e){return!C3.IsNullOrUndefined(e)},C3.IsNullOrUndefined=function(e){return null==e},C3.AreArrayElementsOfSameType=function(e){let n=e[0].constructor;for(let r of e)if(r.constructor!==n)return!1;return n},C3.AreArrayElementsOfType=function(e,n){for(let r of e)if(!(r instanceof n))return!1;return!0};const TypedArray=Object.getPrototypeOf(Uint8Array);C3.IsTypedArray=function(e){return C3.IsInstanceOf(e,TypedArray)},C3.RequireTypedArray=function(e){},C3.WeakRequireTypedArray=function(e){C3.WeakRequireInstanceOf(e,TypedArray)},C3.WeakRequireAnyInstanceOf=function(e,...n){if(!C3.WeakIsAnyInstanceOf(e,...n))throw new TypeError("unexpected type")},C3.WeakIsAnyInstanceOf=function(e,...n){for(const r of n)if(C3.WeakIsInstanceOf(e,r))return!0;return!1},C3.WeakRequireInstanceOf=function(e,n){if(!C3.WeakIsInstanceOf(e,n))throw new TypeError("unexpected type")},C3.WeakIsInstanceOf=function(e,n){for(;e=Object.getPrototypeOf(e);)if(e.constructor.name===n.name)return!0;return!1},C3X.RequireNumber=C3.RequireNumber,C3X.RequireOptionalNumber=C3.RequireOptionalNumber,C3X.RequireFiniteNumber=C3.RequireFiniteNumber,C3X.RequireOptionalFiniteNumber=C3.RequireOptionalFiniteNumber,C3X.RequireString=C3.RequireString,C3X.RequireOptionalString=C3.RequireOptionalString,C3X.RequireObject=C3.RequireObject,C3X.RequireOptionalObject=C3.RequireOptionalObject,C3X.RequireArray=C3.RequireArray,C3X.RequireOptionalArray=C3.RequireOptionalArray,C3X.RequireFunction=C3.RequireFunction,C3X.RequireOptionalFunction=C3.RequireOptionalFunction,C3X.RequireInstanceOf=C3.RequireInstanceOf,C3X.RequireOptionalInstanceOf=C3.RequireOptionalInstanceOf,C3X.IsNullOrUndefined=C3.IsNullOrUndefined;
}

// ../lib/misc/jsutil.js
{
const C3=self.C3,logRafIds=new Map;let measures;function isValidTypeChange(e,t){let r=C3.getType(e),n=C3.getType(t);return"null"===r||"null"===n||"undefined"!==r&&"undefined"!==n&&r===n}C3.ColorLog=function(e,t){console.log(`%c${e}`,`font-weight: bold; color:${t}`)},C3.RafLog=function(e,...t){logRafIds.has(e)||logRafIds.set(e,-1),-1===logRafIds.get(e)&&logRafIds.set(e,requestAnimationFrame((()=>{console.log(`%c${e}`,"font-weight: bold",...t),logRafIds.set(e,-1)})))},C3.StartMeasure=function(e){performance.mark(e),measures||(measures=new Map),measures.has(e)||measures.set(e,{current:0,total:0,average:0,calls:1,toString:function(){return`${e} :: current => ${this.current.toPrecision(3)} :: average => ${this.average.toPrecision(3)} :: calls => ${this.calls}`}})},C3.EndMeasure=function(e){performance.measure(`measure-${e}`,e);const t=performance.getEntriesByName(`measure-${e}`)[0],r=measures.get(e);r.current=t.duration,r.total+=r.current,r.average=r.total/r.calls,console.log(r.toString()),r.calls++,performance.clearMarks(e),performance.clearMeasures(`measure-${e}`)},C3.GetCallStack=function(){return(new Error).stack},C3.Debugger=function(){},C3.cast=function(e,t){return e&&e instanceof t?e:null},C3.getName=function(e){return void 0===e?"undefined":null===e?"null":"boolean"==typeof e?"<boolean>":C3.IsNumber(e)?"<number>":C3.IsString(e)?"<string>":C3.IsArray(e)?"<array>":"symbol"==typeof e?"<"+e.toString()+">":C3.IsFunction(e)?e.name&&"Function"!==e.name?e.name:"<anonymous function>":"object"==typeof e?e.constructor&&e.constructor.name&&"Object"!==e.constructor.name?e.constructor.name:"<anonymous object>":"<unknown>"},C3.getType=function(e){return null===e?"null":Array.isArray(e)?"array":typeof e},C3.range=function*(e,t){if(!isFinite(Math.abs(e-t)))throw new Error("Invalid parameters");if(e>t)for(let r=e-1;r>=t;r--)yield r;else for(let r=e;r<t;r++)yield r};let ctorObjectToProxy=new Map,ctorProxyToObject=new Map,proxyToObject=new WeakMap,releasedObjects=new WeakMap;C3.DefendHandler={};const VALID_GET_MISSING_KEYS=new Set(["then","splice"]);function logDefendedObjectWarning(e){console.warn("[Defence] "+e+" @",C3.GetCallStack())}C3.DefendHandler.get=function(e,t){return t in e||"symbol"==typeof t||VALID_GET_MISSING_KEYS.has(t)||logDefendedObjectWarning(`Accessed missing property '${t}' from defended object '${C3.getName(e)}', returning undefined`),releasedObjects.has(e)&&"symbol"!=typeof t&&!VALID_GET_MISSING_KEYS.has(t)&&logDefendedObjectWarning(`Accessed property '${t}' on a released object '${C3.getName(e)}'\nObject was originally released at: ${releasedObjects.get(e)})\nCall stack at access: `),e[t]},C3.DefendHandler.set=function(e,t,r){return t in e||ctorObjectToProxy.has(e)||logDefendedObjectWarning(`Set non-existent property '${t}' to '${r}' on defended object '${C3.getName(e)}'`),isValidTypeChange(e[t],r)||ctorObjectToProxy.has(e)||logDefendedObjectWarning(`Set '${C3.getType(e[t])}' property '${t}' to type '${C3.getType(r)}' on defended object '${C3.getName(e)}'`),releasedObjects.has(e)&&logDefendedObjectWarning(`Set property '${t}' on a released object '${C3.getName(e)}'\nObject was originally released at: ${releasedObjects.get(e)})\nCall stack at access: `),e[t]=r,!0},C3.DefendHandler.deleteProperty=function(e,t){throw new ReferenceError(`Cannot delete property '${t}' from defended object '${C3.getName(e)}'`)},C3.DefendHandler.defineProperty=function(e,t,r){throw new ReferenceError(`Cannot define property '${t}' on defended object '${C3.getName(e)}'`)},C3.DefendHandler.enumerate=function(e){throw new ReferenceError(`Cannot enumerate defended object '${C3.getName(e)}'`)};let checkRafId=-1;function CheckDefendedObjectsUsedCorrectly(){if(checkRafId=-1,ctorObjectToProxy.size>0||ctorProxyToObject.size>0){let e=[...new Set([...ctorObjectToProxy.keys()].map((e=>C3.getName(e))))].join(",");console.warn(`An object derived from DefendedBase was not protected with debugDefend(). This will disable some checks. See the coding guidelines! Possible affected class names: ${e}`),ctorObjectToProxy.clear(),ctorProxyToObject.clear()}}C3.DefendedBase=class{constructor(){if(!C3.isDebugDefend||!C3.Supports.Proxies)return;let e=new.target,t=Object.create(e.prototype),r=new Proxy(t,C3.DefendHandler);return ctorObjectToProxy.set(t,r),ctorProxyToObject.set(r,t),proxyToObject.set(r,t),-1===checkRafId&&(checkRafId=requestAnimationFrame(CheckDefendedObjectsUsedCorrectly)),r}},C3.debugDefend=function(e){if(C3.isDebugDefend&&C3.Supports.Proxies&&e instanceof C3.DefendedBase){if(!ctorProxyToObject.has(e))return e;let t=ctorProxyToObject.get(e);return ctorProxyToObject.delete(e),ctorObjectToProxy.delete(t),e}return C3.isDebug?Object.seal(e):e},C3.New=function(e,...t){let r;try{r=new e(...t)}catch(e){throw ctorProxyToObject.clear(),ctorObjectToProxy.clear(),e}return C3.isDebugDefend&&VerifyObjectPropertiesConsistent(e,r),C3.debugDefend(r)},C3.Release=function(e){let t=proxyToObject.get(e);t&&releasedObjects.set(t,C3.GetCallStack())},C3.WasReleased=function(e){let t=proxyToObject.get(e);return!!t&&!!releasedObjects.get(t)};let typeProperties=new Map;function getObjectPropertySet(e){let t=new Set;for(let r in e)t.add(r);return t}function VerifyObjectPropertiesConsistent(e,t){let r=getObjectPropertySet(t),n=typeProperties.get(e);if(n){let t=[];for(let e of n.values())r.has(e)?r.delete(e):t.push(e);C3.appendArray(t,[...r]),t.length&&console.warn(`[Defence] '${C3.getName(e)}' constructor creates inconsistent properties: ${t.join(", ")}`)}else typeProperties.set(e,r)}C3.PerfMark=class{constructor(e){this._name="",e&&this.start(e)}start(e){C3.isPerformanceProfiling&&(this._name=e,performance.mark(this._name+"-Start"))}end(){C3.isPerformanceProfiling&&(performance.mark(this._name+"-End"),performance.measure(this._name,this._name+"-Start",this._name+"-End"))}next(e){C3.isPerformanceProfiling&&(this.end(),this._name=e,performance.mark(this._name+"-Start"))}};
}

// ../lib/misc/mathutil.js
{
const C3=self.C3,TWO_PI=2*Math.PI,D_TO_R=Math.PI/180,R_TO_D=180/Math.PI;C3.wrap=function(t,n,e){t=Math.floor(t),n=Math.floor(n);const r=(e=Math.floor(e))-n;if(0===r)return e;if(t<n){const a=e-(n-t)%r;return a===e?0:a}return n+(t-n)%r},C3.mapToRange=function(t,n,e,r,a){const o=e-n;if(0===o&&0===r)return t;return(t-n)*(a-r)/o+r},C3.normalize=function(t,n,e){return n-e==0?1:(t-n)/(e-n)},C3.clamp=function(t,n,e){return t<n?n:t>e?e:t},C3.clampAngle=function(t){return(t%=TWO_PI)<0&&(t+=TWO_PI),t},C3.toRadians=function(t){return t*D_TO_R},C3.toDegrees=function(t){return t*R_TO_D},C3.hypot2DFast=function(t,n){return Math.sqrt(t*t+n*n)},C3.hypot3DFast=function(t,n,e){return Math.sqrt(t*t+n*n+e*e)},C3.distanceTo=function(t,n,e,r){return C3.hypot2DFast(e-t,r-n)},C3.distanceSquared=function(t,n,e,r){const a=e-t,o=r-n;return a*a+o*o},C3.angleTo=function(t,n,e,r){return Math.atan2(r-n,e-t)},C3.angleDiff=function(t,n){if(t===n)return 0;let e=Math.sin(t),r=Math.cos(t),a=e*Math.sin(n)+r*Math.cos(n);return a>=1?0:a<=-1?Math.PI:Math.acos(a)},C3.angleRotate=function(t,n,e){let r=Math.sin(t),a=Math.cos(t),o=Math.sin(n),c=Math.cos(n);return Math.acos(r*o+a*c)>e?a*o-r*c>0?C3.clampAngle(t+e):C3.clampAngle(t-e):C3.clampAngle(n)},C3.angleClockwise=function(t,n){let e=Math.sin(t);return Math.cos(t)*Math.sin(n)-e*Math.cos(n)<=0},C3.angleLerp=function(t,n,e,r=0){let a=C3.angleDiff(t,n);const o=TWO_PI*r;return C3.angleClockwise(n,t)?C3.clampAngle(t+(a+o)*e):C3.clampAngle(t-(a+o)*e)},C3.angleLerpClockwise=function(t,n,e,r=0){const a=C3.angleDiff(t,n),o=TWO_PI*r;return C3.angleClockwise(n,t)?C3.clampAngle(t+(a+o)*e):C3.clampAngle(t+(TWO_PI-a+o)*e)},C3.angleLerpAntiClockwise=function(t,n,e,r=0){const a=C3.angleDiff(t,n),o=TWO_PI*r;return C3.angleClockwise(n,t)?C3.clampAngle(t-(-TWO_PI+a-o)*e):C3.clampAngle(t-(a+o)*e)},C3.angleReflect=function(t,n){const e=C3.angleDiff(t,n);return C3.angleClockwise(t,n)?C3.clampAngle(n-e):C3.clampAngle(n+e)},C3.lerp=function(t,n,e){return t+e*(n-t)},C3.unlerp=function(t,n,e){return t===n?0:(e-t)/(n-t)},C3.relerp=function(t,n,e,r,a){return C3.lerp(r,a,C3.unlerp(t,n,e))},C3.qarp=function(t,n,e,r){return C3.lerp(C3.lerp(t,n,r),C3.lerp(n,e,r),r)},C3.cubic=function(t,n,e,r,a){return C3.lerp(C3.qarp(t,n,e,a),C3.qarp(n,e,r,a),a)},C3.cosp=function(t,n,e){return(t+n+(t-n)*Math.cos(e*Math.PI))/2},C3.isPOT=function(t){return t>0&&!(t-1&t)},C3.nextHighestPowerOfTwo=function(t){--t;for(let n=1;n<32;n<<=1)t|=t>>n;return t+1},C3.roundToNearestFraction=function(t,n){return Math.round(t*n)/n},C3.floorToNearestFraction=function(t,n){return Math.floor(t*n)/n},C3.roundToDp=function(t,n){n=Math.max(Math.floor(n),0);const e=Math.pow(10,n);return Math.round(t*e)/e},C3.countDecimals=function(t){return Math.floor(t)!==t&&t.toString().split(".")[1].length||0},C3.toFixed=function(t,n){let e=t.toFixed(n),r=e.length-1;for(;r>=0&&"0"===e.charAt(r);--r);return r>=0&&"."===e.charAt(r)&&--r,r<0?e:e.substr(0,r+1)},C3.PackRGB=function(t,n,e){return C3.clamp(t,0,255)|C3.clamp(n,0,255)<<8|C3.clamp(e,0,255)<<16};const ALPHAEX_SHIFT=1024,ALPHAEX_MAX=1023,RGBEX_SHIFT=16384,RGBEX_MAX=8191,RGBEX_MIN=-8192;function isNegativeZero(t){return 0===t&&1/t<0}C3.PackRGBAEx=function(t,n,e,r){return(t=C3.clamp(Math.floor(1024*t),-8192,8191))<0&&(t+=16384),(n=C3.clamp(Math.floor(1024*n),-8192,8191))<0&&(n+=16384),(e=C3.clamp(Math.floor(1024*e),-8192,8191))<0&&(e+=16384),-(16384*t*16384*1024+16384*n*1024+1024*e+(r=C3.clamp(Math.floor(1023*r),0,1023)))},C3.PackRGBEx=function(t,n,e){return C3.PackRGBAEx(t,n,e,1)},C3.GetRValue=function(t){if(t>=0)return(255&t)/255;{let n=Math.floor(-t/274877906944);return n>8191&&(n-=16384),n/1024}},C3.GetGValue=function(t){if(t>=0)return((65280&t)>>8)/255;{let n=Math.floor(-t%274877906944/16777216);return n>8191&&(n-=16384),n/1024}},C3.GetBValue=function(t){if(t>=0)return((16711680&t)>>16)/255;{let n=Math.floor(-t%16777216/1024);return n>8191&&(n-=16384),n/1024}},C3.GetAValue=function(t){if(isNegativeZero(t))return 0;if(t>=0)return 1;return Math.floor(-t%1024)/1023},C3.greatestCommonDivisor=function(t,n){for(t=Math.floor(t),n=Math.floor(n);0!==n;){let e=n;n=t%n,t=e}return t};const COMMON_ASPECT_RATIOS=[[3,2],[4,3],[5,4],[5,3],[6,5],[14,9],[16,9],[16,10],[21,9]];C3.getAspectRatio=function(t,n){if((t=Math.floor(t))===(n=Math.floor(n)))return[1,1];for(let e of COMMON_ASPECT_RATIOS){let r=t/e[0]*e[1];if(Math.abs(n-r)<1)return e.slice(0);if(r=t/e[1]*e[0],Math.abs(n-r)<1)return[e[1],e[0]]}let e=C3.greatestCommonDivisor(t,n);return[t/e,n/e]},C3.segmentsIntersect=function(t,n,e,r,a,o,c,u){const i=Math.min(t,e),l=Math.max(t,e),s=Math.min(a,c),C=Math.max(a,c);if(l<s||i>C)return!1;const f=Math.min(n,r),h=Math.max(n,r),M=Math.min(o,u),g=Math.max(o,u);if(h<M||f>g)return!1;const m=a-t+c-e,p=o-n+u-r,I=e-t,T=r-n,P=c-a,A=u-o,_=Math.abs(T*P-A*I),x=P*p-A*m;if(Math.abs(x)>_)return!1;const O=I*p-T*m;return Math.abs(O)<=_},C3.segmentsIntersectPreCalc=function(t,n,e,r,a,o,c,u,i,l,s,C){const f=Math.min(i,s),h=Math.max(i,s);if(o<f||a>h)return!1;const M=Math.min(l,C),g=Math.max(l,C);if(u<M||c>g)return!1;const m=i-t+s-e,p=l-n+C-r,I=e-t,T=r-n,P=s-i,A=C-l,_=Math.abs(T*P-A*I),x=P*p-A*m;if(Math.abs(x)>_)return!1;const O=I*p-T*m;return Math.abs(O)<=_},C3.segmentIntersectsQuad=function(t,n,e,r,a){const o=Math.min(t,e),c=Math.max(t,e),u=Math.min(n,r),i=Math.max(n,r),l=a.getTlx(),s=a.getTly(),C=a.getTrx(),f=a.getTry(),h=a.getBrx(),M=a.getBry(),g=a.getBlx(),m=a.getBly();return C3.segmentsIntersectPreCalc(t,n,e,r,o,c,u,i,l,s,C,f)||C3.segmentsIntersectPreCalc(t,n,e,r,o,c,u,i,C,f,h,M)||C3.segmentsIntersectPreCalc(t,n,e,r,o,c,u,i,h,M,g,m)||C3.segmentsIntersectPreCalc(t,n,e,r,o,c,u,i,g,m,l,s)},C3.segmentIntersectsAnyN=function(t,n,e,r,a){const o=Math.min(t,e),c=Math.max(t,e),u=Math.min(n,r),i=Math.max(n,r);let l=0;for(let s=a.length-4;l<=s;l+=2)if(C3.segmentsIntersectPreCalc(t,n,e,r,o,c,u,i,a[l],a[l+1],a[l+2],a[l+3]))return!0;return C3.segmentsIntersectPreCalc(t,n,e,r,o,c,u,i,a[l],a[l+1],a[0],a[1])};const NO_HIT=2,PADDING=1e-6;C3.rayIntersect=function(t,n,e,r,a,o,c,u){const i=e-t,l=u-o,s=i*l-(r-n)*(c-a);if(0===s)return 2;const C=((n-r)*(c-t)+i*(u-n))/s;return 0<C&&C<1.000001?(l*(c-t)+(a-c)*(u-n))/s:2},C3.rayIntersectExtended=function(t,n,e,r,a,o,c,u,i){const l=(c-a)*i,s=(u-o)*i;return C3.rayIntersect(t,n,e,r,a-l,o-s,c+l,u+s)},C3.isPointInTriangleInclusive=function(t,n,e,r,a,o,c,u){const i=a-e,l=o-r,s=c-e,C=u-r,f=t-e,h=n-r,M=i*i+l*l,g=i*s+l*C,m=i*f+l*h,p=s*s+C*C,I=s*f+C*h,T=1/(M*p-g*g),P=(p*m-g*I)*T,A=(M*I-g*m)*T;return P>=0&&A>=0&&P+A<=1},C3.triangleCartesianToBarycentric=function(t,n,e,r,a,o,c,u){const i=a-e,l=o-r,s=c-e,C=u-r,f=t-e,h=n-r,M=i*i+l*l,g=i*s+l*C,m=s*s+C*C,p=f*i+h*l,I=f*s+h*C,T=M*m-g*g,P=(m*p-g*I)/T,A=(M*I-g*p)/T;return[1-P-A,P,A]},C3.triangleBarycentricToCartesian3d=function(t,n,e,r,a,o,c,u,i,l,s,C){return[t*r+n*c+e*l,t*a+n*u+e*s,t*o+n*i+e*C]};
}

// ../lib/misc/miscutil.js
{
const C3=self.C3;let mainDocument=null,baseHref="";if("undefined"!=typeof document){mainDocument=document;const e=document.querySelector("base");baseHref=e&&e.hasAttribute("href")?e.getAttribute("href"):"",baseHref&&(baseHref.startsWith("/")&&(baseHref=baseHref.substr(1)),baseHref.endsWith("/")||(baseHref+="/"))}C3.GetBaseHref=function(){return baseHref},C3.GetBaseURL=function(){if(!mainDocument)return"";const e=mainDocument.location;return C3.GetPathFromURL(e.origin+e.pathname)+baseHref},C3.GetPathFromURL=function(e){if(!e.length)return e;if(e.endsWith("/")||e.endsWith("\\"))return e;const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===t?"":e.substr(0,t+1)},C3.GetFilenameFromURL=function(e){if(!e.length)return e;if(e.endsWith("/")||e.endsWith("\\"))return"";const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===t?e:e.substr(t+1)},C3.GetFileExtension=function(e){let t=e.lastIndexOf(".");return t<1?"":e.substr(t)},C3.SetFileExtension=function(e,t){const n=e.lastIndexOf(".");return-1===n?e+"."+t:e.substr(0,n+1)+t},C3.GetFileNamePart=function(e){let t=e.lastIndexOf(".");return t<1?e:e.substr(0,t)},C3.NormalizeFileSeparator=function(e){return e.replace(/\\/g,"/")},C3.IsFileExtension=function(e,t){return t===(e?C3.GetFileExtension(e).slice(1):"")},C3.FileNameEquals=function(e,t){let n,r;return C3.IsFileLike(e)&&(n=C3.GetFileNamePart(e["name"])),C3.IsString(e)&&(n=C3.GetFileNamePart(e)),C3.IsFileLike(t)&&(r=C3.GetFileNamePart(t["name"])),C3.IsString(t)&&(r=C3.GetFileNamePart(t)),n===r},C3.ParseFilePath=function(e){e=C3.NormalizeFileSeparator(e);let t=/^\w\:\//.exec(e);t?(t=t[0],"/"!==(e=e.slice(3))[0]&&(e="/"+e)):t="",(e=e.replace(/\/{2,}/g,"/")).length>1&&"/"===e.slice(-1)&&(e=e.slice(0,-1));const n=e.lastIndexOf("/")+1;let r,a="",o=e,s="";n>0&&(a=e.slice(0,n),o=e.slice(n)),r=o;const i=o.lastIndexOf(".");i>0&&(s=o.slice(i),r=o.slice(0,-s.length));return{dir:a,base:o,name:r,root:t,ext:s,full:t+a+o}},C3.Wait=function(e,t){return new Promise(((n,r)=>{self.setTimeout(n,e,t)}))},C3.swallowException=function(e){try{e()}catch(e){C3.isDebug&&console.warn("Swallowed exception: ",e)}},C3.noop=function(){},C3.equalsNoCase=function(e,t){return"string"==typeof e&&"string"==typeof t&&(e===t||e.normalize().toLowerCase()===t.normalize().toLowerCase())},C3.equalsCase=function(e,t){return"string"==typeof e&&"string"==typeof t&&(e===t||e.normalize()===t.normalize())},C3.typedArraySet16=function(e,t,n){e[n++]=t[0],e[n++]=t[1],e[n++]=t[2],e[n++]=t[3],e[n++]=t[4],e[n++]=t[5],e[n++]=t[6],e[n++]=t[7],e[n++]=t[8],e[n++]=t[9],e[n++]=t[10],e[n++]=t[11],e[n++]=t[12],e[n++]=t[13],e[n++]=t[14],e[n]=t[15]},C3.truncateArray=function(e,t){e.length=t},C3.clearArray=function(e){e&&0!==e.length&&C3.truncateArray(e,0)},C3.clear2DArray=function(e){if(e){for(let t=0;t<e.length;t++){let n=e[t];C3.truncateArray(n,0)}C3.truncateArray(e,0)}},C3.extendArray=function(e,t,n){t|=0;const r=e.length;if(!(t<=r))for(let a=r;a<t;++a)e.push(n)},C3.resizeArray=function(e,t,n){t|=0;const r=e.length;t<r?C3.truncateArray(e,t):t>r&&C3.extendArray(e,t,n)},C3.shallowAssignArray=function(e,t){C3.clearArray(e),C3.appendArray(e,t)},C3.appendArray=function(e,t){if(t.length<1e4)e.push(...t);else for(let n=0,r=t.length;n<r;++n)e.push(t[n])},C3.arrayRemove=function(e,t){if((t=Math.floor(t))<0||t>=e.length)return;let n=e.length-1;for(let r=t;r<n;++r)e[r]=e[r+1];C3.truncateArray(e,n)},C3.arrayFindRemove=function(e,t){let n=e.indexOf(t);n>=0&&e.splice(n,1)},C3.arraysEqual=function(e,t){let n=e.length;if(t.length!==n)return!1;for(let r=0;r<n;++r)if(e[r]!==t[r])return!1;return!0},C3.arrayFilterOut=function(e,t){let n=[],r=0;for(let a=0,o=e.length;a<o;++a){let o=e[a];t(o)?n.push(o):(e[r]=o,++r)}return C3.truncateArray(e,r),n},C3.arrayRemoveAllInSet=function(e,t){const n=e.length;let r=0;for(let n=0,a=e.length;n<a;++n){let a=e[n];t.has(a)||(e[r++]=a)}return C3.truncateArray(e,r),n-r},C3.isArrayIndexInBounds=function(e,t){return e===Math.floor(e)&&(e>=0&&e<t.length)},C3.validateArrayIndex=function(e,t){if(!C3.isArrayIndexInBounds(e,t))throw new RangeError("array index out of bounds")},C3.cloneArray=function(e){return e.slice()},C3.deepCloneArray=function(e,t){let n=[];for(let r of e)if(C3.IsObject(r)){let e=t(r);if(!e)throw new Error("missing clone");if(e.constructor!==r.constructor)throw new Error("object is not a clone");n.push(e)}else C3.IsArray(r)?n.push(C3.deepCloneArray(r,t)):n.push(r);return n},C3.clone2DArray=function(e){let t=[];for(let n of e)t.push(n.slice());return t},C3.splitStringAndNormalize=function(e,t=" "){return e?e.split(t).map((e=>e.trim())).filter((e=>!!e)):[]},C3.filterSet=function(e,t,n){const r=new Set;for(const a of e.values())t(a)&&(n?r.add(n(a)):r.add(a));return r},C3.mergeSets=function(e,t){return e["union"]?e["union"](t):new Set([...e,...t])},C3.mergeSetsInPlace=function(e,t){for(const n of t)e.add(n);return e},C3.first=function(e){for(let t of e)return t;return null},C3.xor=function(e,t){return!e!=!t},C3.compare=function(e,t,n){switch(t){case 0:return e===n;case 1:return e!==n;case 2:return e<n;case 3:return e<=n;case 4:return e>n;case 5:return e>=n;default:return!1}},C3.hasAnyOwnProperty=function(e){for(let t in e)if(e.hasOwnProperty(t))return!0;return!1},C3.PromiseAllWithProgress=function(e,t){return e.length?new Promise(((n,r)=>{const a=[];let o=0,s=!1;for(let i=0,l=e.length;i<l;++i)a.push(void 0),e[i].then((r=>{s||(a[i]=r,++o,o===e.length?n(a):t(o,e.length))})).catch((e=>{s=!0,r(e)}))})):Promise.resolve([])};let memoryCallbacks=[];C3.AddLibraryMemoryCallback=function(e){memoryCallbacks.push(e)},C3.GetEstimatedLibraryMemoryUsage=function(){let e=0;for(let t of memoryCallbacks){e+=t()}return Math.floor(e)};let nextTaskId=1;const activeTaskIds=new Map,taskMessageChannel=new MessageChannel;taskMessageChannel.port2.onmessage=function(e){const t=e.data,n=activeTaskIds.get(t);activeTaskIds.delete(t),n&&n(performance.now())},C3.RequestUnlimitedAnimationFrame=function(e){const t=nextTaskId++;return activeTaskIds.set(t,e),taskMessageChannel.port1.postMessage(t),t},C3.CancelUnlimitedAnimationFrame=function(e){activeTaskIds.delete(e)},C3.PostTask=C3.RequestUnlimitedAnimationFrame,C3.WaitForNextTask=function(){return new Promise((e=>C3.PostTask(e)))};const activeRPAFids=new Set;C3.RequestPostAnimationFrame=function(e){const t=self.requestAnimationFrame((async n=>{await C3.WaitForNextTask(),activeRPAFids.has(t)&&(activeRPAFids.delete(t),e(n))}));return activeRPAFids.add(t),t},C3.CancelPostAnimationFrame=function(e){activeRPAFids.has(e)&&(self.cancelAnimationFrame(e),activeRPAFids.delete(e))};
}

// lib/misc/runtimeutil.js
{
const C3=self.C3;C3.IsAbsoluteURL=function(e){return/^(?:[a-z\-]+:)?\/\//.test(e)||"data:"===e.substr(0,5)||"blob:"===e.substr(0,5)},C3.IsRelativeURL=function(e){return!C3.IsAbsoluteURL(e)},C3.ThrowIfNotOk=function(e){if(!e.ok)throw new Error(`fetch '${e.url}' response returned ${e.status} ${e.statusText}`)},C3.FetchOk=function(e,t){return fetch(e,t).then((e=>(C3.ThrowIfNotOk(e),e)))},C3.FetchText=function(e){return C3.FetchOk(e).then((e=>e.text()))},C3.FetchJson=function(e){return C3.FetchOk(e).then((e=>e.json()))},C3.FetchBlob=function(e){return C3.FetchOk(e).then((e=>e.blob()))},C3.FetchArrayBuffer=function(e){return C3.FetchOk(e).then((e=>e.arrayBuffer()))},C3.FetchImage=function(e){return new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e}))},C3.BlobToArrayBuffer=function(e){return"function"==typeof e["arrayBuffer"]?e["arrayBuffer"]():new Promise(((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsArrayBuffer(e)}))},C3.BlobToString=function(e){return"function"==typeof e["text"]?e["text"]():new Promise(((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)}))},C3.BlobToJson=function(e){return C3.BlobToString(e).then((e=>JSON.parse(e)))},C3.BlobToImage=async function(e,t){let n=URL.createObjectURL(e);try{const e=await C3.FetchImage(n);return URL.revokeObjectURL(n),n="",t&&"function"==typeof e["decode"]&&await e["decode"](),e}finally{n&&URL.revokeObjectURL(n)}},C3.CreateCanvas=function(e,t){if("undefined"!=typeof document&&"function"==typeof document.createElement){const n=document.createElement("canvas");return n.width=e,n.height=t,n}return new OffscreenCanvas(e,t)},C3.CanvasToBlob=function(e,t,n){if("number"!=typeof n&&(n=1),t=t||"image/png",n=C3.clamp(n,0,1),e["convertToBlob"])return e["convertToBlob"]({"type":t,"quality":n});if(e.toBlob)return new Promise((r=>e.toBlob(r,t,n)));throw new Error("could not convert canvas to blob")},C3.DrawableToBlob=function(e,t,n){const r=C3.CreateCanvas(e.width,e.height);return r.getContext("2d").drawImage(e,0,0),C3.CanvasToBlob(r,t,n)},C3.ImageDataToBlob=function(e,t,n){if(C3.Supports.ImageBitmapOptions)return createImageBitmap(e,{"premultiplyAlpha":"none"}).then((e=>C3.DrawableToBlob(e,t,n)));if(C3.Supports.ImageBitmap)return createImageBitmap(e).then((e=>C3.DrawableToBlob(e,t,n)));{const r=C3.CreateCanvas(e.width,e.height);return r.getContext("2d").putImageData(e,0,0),C3.CanvasToBlob(r,t,n)}},C3.CopySet=function(e,t){e.clear();for(const n of t)e.add(n)},C3.MapToObject=function(e){const t=Object.create(null);for(const[n,r]of e.entries())t[n]=r;return t},C3.ObjectToMap=function(e,t){t.clear();for(const[n,r]of Object.entries(e))t.set(n,r)},C3.ToSuperJSON=function e(t){if("object"==typeof t&&null!==t){if(t instanceof Set)return{"_c3type_":"set","data":[...t].map((t=>e(t)))};if(t instanceof Map)return{"_c3type_":"map","data":[...t].map((t=>[t[0],e(t[1])]))};{const n=Object.create(null);for(const[r,o]of Object.entries(t))n[r]=e(o);return n}}return t},C3.FromSuperJSON=function e(t){if("object"==typeof t&null!==t){if("set"===t["_c3type_"])return new Set(t["data"].map((t=>e(t))));if("map"===t["_c3type_"])return new Map(t["data"].map((t=>[t[0],e(t[1])])));{const n=Object.create(null);for(const[r,o]of Object.entries(t))n[r]=e(o);return n}}return t},C3.CSSToCamelCase=function(e){if(e.startsWith("--"))return e;let t="",n=!1,r=0;for(const o of e)"-"===o?r>0&&(n=!0):n?(t+=o.toUpperCase(),n=!1):t+=o,++r;return t},C3.IsIterator=function(e){return"object"==typeof e&&"function"==typeof e.next},C3.MakeFilledArray=function(e,t){const n=[];if("function"==typeof t)for(let r=0;r<e;++r)n.push(t());else for(let r=0;r<e;++r)n.push(t);return n};
}

// ../lib/misc/color.js
{
const C3=self.C3,HSL_TEST=/([0-9.]+),([0-9.]+)\%?,([0-9.]+)\%?/i,HSLA_TEST=/([0-9.]+),([0-9.]+)\%?,([0-9.]+)\%?,([0-9.])/i;function padTwoDigits(t){return 0===t.length?"00":1===t.length?"0"+t:t}function hueToRGB(t,s,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?t+6*(s-t)*e:e<.5?s:e<2/3?t+(s-t)*(2/3-e)*6:t}C3.Color=class{constructor(t,s,e,r){this._r=NaN,this._g=NaN,this._b=NaN,this._a=NaN,this._r=0,this._g=0,this._b=0,this._a=0,t instanceof C3.Color?this.set(t):this.setRgba(t||0,s||0,e||0,r||0)}setRgb(t,s,e){return this._r=+t,this._g=+s,this._b=+e,this.clamp(),this}setRgba(t,s,e,r){return this._r=+t,this._g=+s,this._b=+e,this._a=+r,this.clamp(),this}set(t){return this._r=t._r,this._g=t._g,this._b=t._b,this._a=t._a,this}copy(t){return this.set(t)}add(t){this._r+=t._r,this._g+=t._g,this._b+=t._b,this._a+=t._a,this.clamp()}addRgb(t,s,e,r=0){this._r+=+t,this._g+=+s,this._b+=+e,this._a+=+r,this.clamp()}diff(t){this.setR(Math.max(this._r,t._r)-Math.min(this._r,t._r)),this.setG(Math.max(this._g,t._g)-Math.min(this._g,t._g)),this.setB(Math.max(this._b,t._b)-Math.min(this._b,t._b)),this.setA(Math.max(this._a,t._a)-Math.min(this._a,t._a)),this.clamp()}copyRgb(t){this._r=t._r,this._g=t._g,this._b=t._b}setR(t){this._r=C3.clamp(+t,0,1)}getR(){return this._r}setG(t){this._g=C3.clamp(+t,0,1)}getG(){return this._g}setB(t){this._b=C3.clamp(+t,0,1)}getB(){return this._b}setA(t){this._a=C3.clamp(+t,0,1)}getA(){return this._a}clone(){return C3.New(C3.Color,this._r,this._g,this._b,this._a)}toArray(){return[this._r,this._g,this._b,this._a]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(t,s){t[s++]=this._r,t[s++]=this._g,t[s++]=this._b,t[s]=this._a}writeRGBToTypedArray(t,s){t[s++]=this._r,t[s++]=this._g,t[s]=this._b}equals(t){return this._r===t._r&&this._g===t._g&&this._b===t._b&&this._a===t._a}equalsIgnoringAlpha(t){return this._r===t._r&&this._g===t._g&&this._b===t._b}equalsRgb(t,s,e){return this._r===t&&this._g===s&&this._b===e}equalsRgba(t,s,e,r){return this._r===t&&this._g===s&&this._b===e&&this._a===r}equalsF32Array(t,s){return t[s]===Math.fround(this._r)&&t[s+1]===Math.fround(this._g)&&t[s+2]===Math.fround(this._b)&&t[s+3]===Math.fround(this._a)}equalsRGBF32Array(t,s){return t[s]===Math.fround(this._r)&&t[s+1]===Math.fround(this._g)&&t[s+2]===Math.fround(this._b)}multiply(t){this._r*=t._r,this._g*=t._g,this._b*=t._b,this._a*=t._a}multiplyAlpha(t){this._r*=t,this._g*=t,this._b*=t,this._a*=t}premultiply(){return this._r*=this._a,this._g*=this._a,this._b*=this._a,this}unpremultiply(){return this._r/=this._a,this._g/=this._a,this._b/=this._a,this}clamp(){return this._r=C3.clamp(this._r,0,1),this._g=C3.clamp(this._g,0,1),this._b=C3.clamp(this._b,0,1),this._a=C3.clamp(this._a,0,1),this}setFromRgbValue(t){this._r=C3.GetRValue(t),this._g=C3.GetGValue(t),this._b=C3.GetBValue(t),this._a=C3.GetAValue(t)}getCssRgb(t,s,e){return`rgb(${100*(C3.IsFiniteNumber(t)?t:this.getR())}%, ${100*(C3.IsFiniteNumber(s)?s:this.getG())}%, ${100*(C3.IsFiniteNumber(e)?e:this.getB())}%)`}getCssRgba(t,s,e,r){return`rgba(${100*(C3.IsFiniteNumber(t)?t:this.getR())}%, ${100*(C3.IsFiniteNumber(s)?s:this.getG())}%, ${100*(C3.IsFiniteNumber(e)?e:this.getB())}%, ${C3.IsFiniteNumber(r)?r:this.getA()})`}toHexString(){const t=Math.round(255*this.getR()),s=Math.round(255*this.getG()),e=Math.round(255*this.getB());return"#"+padTwoDigits(t.toString(16))+padTwoDigits(s.toString(16))+padTwoDigits(e.toString(16))}parseHexString(t){if("string"!=typeof t)return!1;let s,e,r;if("#"===(t=t.trim()).charAt(0)&&(t=t.substr(1)),3===t.length)s=parseInt(t[0],16)/15,e=parseInt(t[1],16)/15,r=parseInt(t[2],16)/15;else{if(6!==t.length)return!1;s=parseInt(t.substr(0,2),16)/255,e=parseInt(t.substr(2,2),16)/255,r=parseInt(t.substr(4,2),16)/255}return isFinite(s)&&this.setR(s),isFinite(e)&&this.setG(e),isFinite(r)&&this.setB(r),this.setA(1),!0}toCommaSeparatedRgb(){return`${Math.round(255*this.getR())}, ${Math.round(255*this.getG())}, ${Math.round(255*this.getB())}`}toRgbArray(){return[Math.round(255*this.getR()),Math.round(255*this.getG()),Math.round(255*this.getB())]}parseCommaSeparatedRgb(t){if("string"!=typeof t)return!1;const s=(t=t.replace(/^rgb\(|\)|%/,"")).split(",");if(s.length<3)return!1;const e=parseInt(s[0].trim(),10)/255,r=parseInt(s[1].trim(),10)/255,i=parseInt(s[2].trim(),10)/255;return isFinite(e)&&this.setR(e),isFinite(r)&&this.setG(r),isFinite(i)&&this.setB(i),this.setA(1),!0}parseCommaSeparatedPercentageRgb(t){if("string"!=typeof t)return!1;const s=(t=t.replace(/^rgb\(|\)|%/,"")).split(",");if(s.length<3)return!1;const e=parseInt(s[0].trim(),10)/100,r=parseInt(s[1].trim(),10)/100,i=parseInt(s[2].trim(),10)/100;return isFinite(e)&&this.setR(e),isFinite(r)&&this.setG(r),isFinite(i)&&this.setB(i),this.setA(1),!0}parseCommaSeparatedRgba(t){if("string"!=typeof t)return!1;const s=(t=t.replace(/^rgba\(|\)|%/,"")).split(",");if(s.length<4)return!1;const e=parseInt(s[0].trim(),10)/255,r=parseInt(s[1].trim(),10)/255,i=parseInt(s[2].trim(),10)/255,a=parseFloat(s[3].trim());return isFinite(e)&&this.setR(e),isFinite(r)&&this.setG(r),isFinite(i)&&this.setB(i),isFinite(a)&&this.setA(a),!0}parseCommaSeparatedPercentageRgba(t){if("string"!=typeof t)return!1;const s=(t=t.replace(/^rgba\(|\)|%/,"")).split(",");if(s.length<4)return!1;const e=parseInt(s[0].trim(),10)/100,r=parseInt(s[1].trim(),10)/100,i=parseInt(s[2].trim(),10)/100,a=parseFloat(s[3].trim());return isFinite(e)&&this.setR(e),isFinite(r)&&this.setG(r),isFinite(i)&&this.setB(i),isFinite(a)&&this.setA(a),!0}parseString(t){if("string"!=typeof t)return!1;if((t=t.replace(/\s+/,"")).includes(",")){if(t.startsWith("rgb("))return t.includes("%")?this.parseCommaSeparatedPercentageRgb(t):this.parseCommaSeparatedRgb(t);if(t.startsWith("rgba("))return t.includes("%")?this.parseCommaSeparatedPercentageRgba(t):this.parseCommaSeparatedRgba(t);if(t.startsWith("hsl(")||t.startsWith("hsla("))return this.parseHSLString(t);{const s=t.split(",");return t.includes("%")?3===s.length?this.parseCommaSeparatedPercentageRgb(t):4===s.length&&this.parseCommaSeparatedPercentageRgba(t):3===s.length?this.parseCommaSeparatedRgb(t):4===s.length&&this.parseCommaSeparatedRgba(t)}}return this.parseHexString(t)}toJSON(){return[this._r,this._g,this._b,this._a]}setFromHSLA(t,s,e,r){let i,a,h;if(t%=360,s=C3.clamp(s,0,100),e=C3.clamp(e,0,100),r=C3.clamp(r,0,1),t/=360,e/=100,0===(s/=100))i=a=h=e;else{const r=e<.5?e*(1+s):e+s-e*s,n=2*e-r;i=hueToRGB(n,r,t+1/3),a=hueToRGB(n,r,t),h=hueToRGB(n,r,t-1/3)}return this.setR(i),this.setG(a),this.setB(h),this.setA(r),this}parseHSLString(t){const s=t.replace(/ |hsl|hsla|\(|\)|;/gi,""),e=HSL_TEST.exec(s),r=HSLA_TEST.exec(s);return e&&4===e.length?(this.setFromHSLA(+e[1],+e[2],+e[3],1),!0):!(!r||5!==r.length)&&(this.setFromHSLA(+e[1],+e[2],+e[3],+e[4]),!0)}toHSLAString(){const t=this._r,s=this._g,e=this._b,r=this._a;return`hsla(${C3.Color.GetHue(t,s,e)}, ${C3.Color.GetSaturation(t,s,e)}%, ${C3.Color.GetLuminosity(t,s,e)}%, ${r})`}toHSLAArray(){const t=this._r,s=this._g,e=this._b;return[C3.Color.GetHue(t,s,e),C3.Color.GetSaturation(t,s,e),C3.Color.GetLuminosity(t,s,e),this._a]}setFromJSON(t){Array.isArray(t)&&(t.length<3||(this._r=t[0],this._g=t[1],this._b=t[2],t.length>=4?this._a=t[3]:this._a=1))}set r(t){this.setR(t)}get r(){return this.getR()}set g(t){this.setG(t)}get g(){return this.getG()}set b(t){this.setB(t)}get b(){return this.getB()}set a(t){this.setA(t)}get a(){return this.getA()}setAtIndex(t,s){switch(t){case 0:this.setR(s);break;case 1:this.setG(s);break;case 2:this.setB(s);break;case 3:this.setA(s);break;default:throw new RangeError("invalid color index")}}getAtIndex(t){switch(t){case 0:return this.getR();case 1:return this.getG();case 2:return this.getB();case 3:return this.getA();default:throw new RangeError("invalid color index")}}static Equals(t,s){let e,r;if(Array.isArray(t))e=new C3.Color,e.setFromJSON(t);else{if(!(t instanceof C3.Color))throw new Error("unexpected type");e=t}if(Array.isArray(s))r=new C3.Color,r.setFromJSON(s);else{if(!(s instanceof C3.Color))throw new Error("unexpected type");r=s}return e.equals(r)}static DiffChannel(t,s){return C3.clamp(Math.max(t,s)-Math.min(t,s),0,1)}static Diff(t,s){const e=new C3.Color;return e.setR(Math.max(t._r,s._r)-Math.min(t._r,s._r)),e.setG(Math.max(t._g,s._g)-Math.min(t._g,s._g)),e.setB(Math.max(t._b,s._b)-Math.min(t._b,s._b)),e.setA(Math.max(t._a,s._a)-Math.min(t._a,s._a)),e}static DiffNoAlpha(t,s){const e=new C3.Color(0,0,0,1);return e.setR(Math.max(t._r,s._r)-Math.min(t._r,s._r)),e.setG(Math.max(t._g,s._g)-Math.min(t._g,s._g)),e.setB(Math.max(t._b,s._b)-Math.min(t._b,s._b)),e}static GetHue(t,s,e){const r=Math.max(t,s,e),i=Math.min(t,s,e);if(r===i)return 0;let a=0;switch(r){case t:a=(s-e)/(r-i)+(s<e?6:0);break;case s:a=(e-t)/(r-i)+2;break;case e:a=(t-s)/(r-i)+4}return Math.round(a/6*360)}static GetSaturation(t,s,e){const r=Math.max(t,s,e),i=Math.min(t,s,e);if(r===i)return 0;const a=r-i,h=(r+i)/2>.5?a/(2-r-i):a/(r+i);return Math.round(100*h)}static GetLuminosity(t,s,e){const r=Math.max(t,s,e),i=(r+Math.min(t,s,e))/2;return r?Math.round(100*i):0}},C3.Color.White=Object.freeze(C3.New(C3.Color,1,1,1,1)),C3.Color.Black=Object.freeze(C3.New(C3.Color,0,0,0,1)),C3.Color.TransparentBlack=Object.freeze(C3.New(C3.Color,0,0,0,0));
}

// ../lib/misc/vector2.js
{
const C3=self.C3;C3.Vector2=class{constructor(t,s){this._x=0,this._y=0,t instanceof C3.Vector2?this.copy(t):this.set(t||0,s||0)}set(t,s){this._x=+t,this._y=+s}copy(t){this._x=t._x,this._y=t._y}equals(t){return this._x===t._x&&this._y===t._y}equalsValues(t,s){return this._x===t&&this._y===s}equalsF32Array(t,s){return t[s]===Math.fround(this._x)&&t[s+1]===Math.fround(this._y)}setX(t){this._x=+t}getX(){return this._x}setY(t){this._y=+t}getY(){return this._y}toArray(){return[this._x,this._y]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(t,s){t[s++]=this._x,t[s]=this._y}offset(t,s){this._x+=+t,this._y+=+s}scale(t,s){this._x*=t,this._y*=s}divide(t,s){this._x/=t,this._y/=s}round(){this._x=Math.round(this._x),this._y=Math.round(this._y)}floor(){this._x=Math.floor(this._x),this._y=Math.floor(this._y)}ceil(){this._x=Math.ceil(this._x),this._y=Math.ceil(this._y)}angle(){return C3.angleTo(0,0,this._x,this._y)}lengthSquared(){return this._x*this._x+this._y*this._y}length(){return C3.hypot2DFast(this._x,this._y)}rotatePrecalc(t,s){const h=this._x*s-this._y*t;this._y=this._y*s+this._x*t,this._x=h}rotate(t){0!==t&&this.rotatePrecalc(Math.sin(t),Math.cos(t))}rotateAbout(t,s,h){0===t||s===this._x&&h===this._y||(this._x-=s,this._y-=h,this.rotatePrecalc(Math.sin(t),Math.cos(t)),this._x+=+s,this._y+=+h)}move(t,s){0!==s&&(this._x+=Math.cos(t)*s,this._y+=Math.sin(t)*s)}normalize(){const t=this.length();0!==t&&1!==t&&(this._x/=t,this._y/=t)}clamp(t,s){this._x=C3.clamp(this._x,t,s),this._y=C3.clamp(this._y,t,s)}dot(t){return this._x*t._x+this._y*t._y}reverse(){this._x=-this._x,this._y=-this._y}perp(){let t=this._x;return this._x=this._y,this._y=-t,this}};
}

// ../lib/misc/rect.js
{
const C3=self.C3;C3.Rect=class{constructor(t,h,i,o){this._left=NaN,this._top=NaN,this._right=NaN,this._bottom=NaN,this._left=0,this._top=0,this._right=0,this._bottom=0,t instanceof C3.Rect?this.copy(t):this.set(t||0,h||0,i||0,o||0)}set(t,h,i,o){this._left=+t,this._top=+h,this._right=+i,this._bottom=+o}setWH(t,h,i,o){t=+t,h=+h,this._left=t,this._top=h,this._right=t+ +i,this._bottom=h+ +o}copy(t){this._left=+t._left,this._top=+t._top,this._right=+t._right,this._bottom=+t._bottom}clone(){return new C3.Rect(this._left,this._top,this._right,this._bottom)}static Merge(t,h){const i=new C3.Rect;return i.setLeft(Math.min(t._left,h._left)),i.setTop(Math.min(t._top,h._top)),i.setRight(Math.max(t._right,h._right)),i.setBottom(Math.max(t._bottom,h._bottom)),i}static FromObject(t){return new C3.Rect(t.left,t.top,t.right,t.bottom)}equals(t){return this._left===t._left&&this._top===t._top&&this._right===t._right&&this._bottom===t._bottom}equalsWH(t,h,i,o){return this._left===t&&this._top===h&&this.width()===i&&this.height()===o}equalsF32Array(t,h){return t[h]===Math.fround(this._left)&&t[h+1]===Math.fround(this._top)&&t[h+2]===Math.fround(this._right)&&t[h+3]===Math.fround(this._bottom)}setLeft(t){this._left=+t}getLeft(){return this._left}setTop(t){this._top=+t}getTop(){return this._top}setRight(t){this._right=+t}getRight(){return this._right}setBottom(t){this._bottom=+t}getBottom(){return this._bottom}toArray(){return[this._left,this._top,this._right,this._bottom]}toTypedArray(){return new Float64Array(this.toArray())}toDOMRect(){return new DOMRect(this._left,this._top,this.width(),this.height())}static fromDOMRect(t){return C3.New(C3.Rect,t.left,t.top,t.right,t.bottom)}writeToTypedArray(t,h){t[h++]=this._left,t[h++]=this._top,t[h++]=this._right,t[h]=this._bottom}writeAsQuadToTypedArray(t,h){t[h++]=this._left,t[h++]=this._top,t[h++]=this._right,t[h++]=this._top,t[h++]=this._right,t[h++]=this._bottom,t[h++]=this._left,t[h]=this._bottom}writeAsQuadToTypedArray3D(t,h,i){t[h++]=this._left,t[h++]=this._top,t[h++]=i,t[h++]=this._right,t[h++]=this._top,t[h++]=i,t[h++]=this._right,t[h++]=this._bottom,t[h++]=i,t[h++]=this._left,t[h++]=this._bottom,t[h]=i}width(){return this._right-this._left}height(){return this._bottom-this._top}midX(){return(this._left+this._right)/2}midY(){return(this._top+this._bottom)/2}offset(t,h){t=+t,h=+h,this._left+=t,this._top+=h,this._right+=t,this._bottom+=h}offsetLeft(t){this._left+=+t}offsetTop(t){this._top+=+t}offsetRight(t){this._right+=+t}offsetBottom(t){this._bottom+=+t}toSquare(t){if("x"!==t)throw new Error("invalid axis, only 'x' supported");this._top<this._bottom?this._left<this._right?this._bottom=this._top+this.width():this._bottom=this._top-this.width():this._left<this._right?this._bottom=this._top-this.width():this._bottom=this._top+this.width()}inflate(t,h){t=+t,h=+h,this._left-=t,this._top-=h,this._right+=t,this._bottom+=h}deflate(t,h){t=+t,h=+h,this._left+=t,this._top+=h,this._right-=t,this._bottom-=h}multiply(t,h){this._left*=t,this._top*=h,this._right*=t,this._bottom*=h}divide(t,h){this._left/=t,this._top/=h,this._right/=t,this._bottom/=h}mirrorAround(t){this._left=+t-this._left,this._right=+t-this._right}flipAround(t){this._top=+t-this._top,this._bottom=+t-this._bottom}rotate90DegreesAround(t,h){const i=this.width(),o=this.height(),s=this.getLeft()+i*t,_=this.getTop()+o*h;this.setWH(s-o*h,_-i*t,o,i)}swapLeftRight(){const t=this._left;this._left=this._right,this._right=t}swapTopBottom(){const t=this._top;this._top=this._bottom,this._bottom=t}shuntY(t){const h=this._top;this._top=+t-this._bottom,this._bottom=+t-h}round(){this._left=Math.round(this._left),this._top=Math.round(this._top),this._right=Math.round(this._right),this._bottom=Math.round(this._bottom)}roundInner(){this._left=Math.ceil(this._left),this._top=Math.ceil(this._top),this._right=Math.floor(this._right),this._bottom=Math.floor(this._bottom)}roundOuter(){this._left=Math.floor(this._left),this._top=Math.floor(this._top),this._right=Math.ceil(this._right),this._bottom=Math.ceil(this._bottom)}floor(){this._left=Math.floor(this._left),this._top=Math.floor(this._top),this._right=Math.floor(this._right),this._bottom=Math.floor(this._bottom)}ceil(){this._left=Math.ceil(this._left),this._top=Math.ceil(this._top),this._right=Math.ceil(this._right),this._bottom=Math.ceil(this._bottom)}clamp(t,h,i,o){this._left=Math.max(this._left,+t),this._top=Math.max(this._top,+h),this._right=Math.min(this._right,+i),this._bottom=Math.min(this._bottom,+o)}clampBoth(t,h,i,o){t=+t,h=+h,i=+i,o=+o,this._left=C3.clamp(this._left,t,i),this._top=C3.clamp(this._top,h,o),this._right=C3.clamp(this._right,t,i),this._bottom=C3.clamp(this._bottom,h,o)}normalize(){this._left>this._right&&this.swapLeftRight(),this._top>this._bottom&&this.swapTopBottom()}intersectsRect(t){return!(t._right<this._left||t._bottom<this._top||t._left>this._right||t._top>this._bottom)}intersectsRectOffset(t,h,i){return!(t._right+h<this._left||t._bottom+i<this._top||t._left+h>this._right||t._top+i>this._bottom)}containsPoint(t,h){return t>=this._left&&t<=this._right&&h>=this._top&&h<=this._bottom}containsRect(t){return t._left>=this._left&&t._top>=this._top&&t._right<=this._right&&t._bottom<=this._bottom}expandToContain(t){t._left<this._left&&(this._left=+t._left),t._top<this._top&&(this._top=+t._top),t._right>this._right&&(this._right=+t._right),t._bottom>this._bottom&&(this._bottom=+t._bottom)}lerpInto(t){this._left=C3.lerp(t._left,t._right,this._left),this._top=C3.lerp(t._top,t._bottom,this._top),this._right=C3.lerp(t._left,t._right,this._right),this._bottom=C3.lerp(t._top,t._bottom,this._bottom)}};
}

// ../lib/misc/quad.js
{
const C3=self.C3;C3.Quad=class{constructor(t,s,i,h,_,r,l,e){this._tlx=NaN,this._tly=NaN,this._trx=NaN,this._try=NaN,this._brx=NaN,this._bry=NaN,this._blx=NaN,this._bly=NaN,this._tlx=0,this._tly=0,this._trx=0,this._try=0,this._brx=0,this._bry=0,this._blx=0,this._bly=0,t instanceof C3.Quad?this.copy(t):this.set(t||0,s||0,i||0,h||0,_||0,r||0,l||0,e||0)}set(t,s,i,h,_,r,l,e){this._tlx=+t,this._tly=+s,this._trx=+i,this._try=+h,this._brx=+_,this._bry=+r,this._blx=+l,this._bly=+e}setRect(t,s,i,h){this.set(t,s,i,s,i,h,t,h)}copy(t){this._tlx=t._tlx,this._tly=t._tly,this._trx=t._trx,this._try=t._try,this._brx=t._brx,this._bry=t._bry,this._blx=t._blx,this._bly=t._bly}equals(t){return this._tlx===t._tlx&&this._tly===t._tly&&this._trx===t._trx&&this._try===t._try&&this._brx===t._brx&&this._bry===t._bry&&this._blx===t._blx&&this._bly===t._bly}setTlx(t){this._tlx=+t}getTlx(){return this._tlx}setTly(t){this._tly=+t}getTly(){return this._tly}setTrx(t){this._trx=+t}getTrx(){return this._trx}setTry(t){this._try=+t}getTry(){return this._try}setBrx(t){this._brx=+t}getBrx(){return this._brx}setBry(t){this._bry=+t}getBry(){return this._bry}setBlx(t){this._blx=+t}getBlx(){return this._blx}setBly(t){this._bly=+t}getBly(){return this._bly}toDOMQuad(){return new DOMQuad(new DOMPoint(this._tlx,this._tly),new DOMPoint(this._trx,this._try),new DOMPoint(this._brx,this._bry),new DOMPoint(this._blx,this._bly))}static fromDOMQuad(t){return C3.New(C3.Quad,t.p1.x,t.p1.y,t.p2.x,t.p2.y,t.p3.x,t.p3.y,t.p4.x,t.p4.y)}toArray(){return[this._tlx,this._tly,this._trx,this._try,this._brx,this._bry,this._blx,this._bly]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(t,s){t[s++]=this._tlx,t[s++]=this._tly,t[s++]=this._trx,t[s++]=this._try,t[s++]=this._brx,t[s++]=this._bry,t[s++]=this._blx,t[s]=this._bly}writeToTypedArray3D(t,s,i){t[s++]=this._tlx,t[s++]=this._tly,t[s++]=i,t[s++]=this._trx,t[s++]=this._try,t[s++]=i,t[s++]=this._brx,t[s++]=this._bry,t[s++]=i,t[s++]=this._blx,t[s++]=this._bly,t[s]=i}offset(t,s){t=+t,s=+s,this._tlx+=t,this._tly+=s,this._trx+=t,this._try+=s,this._brx+=t,this._bry+=s,this._blx+=t,this._bly+=s}round(){this._tlx=Math.round(this._tlx),this._tly=Math.round(this._tly),this._trx=Math.round(this._trx),this._try=Math.round(this._try),this._brx=Math.round(this._brx),this._bry=Math.round(this._bry),this._blx=Math.round(this._blx),this._bly=Math.round(this._bly)}floor(){this._tlx=Math.floor(this._tlx),this._tly=Math.floor(this._tly),this._trx=Math.floor(this._trx),this._try=Math.floor(this._try),this._brx=Math.floor(this._brx),this._bry=Math.floor(this._bry),this._blx=Math.floor(this._blx),this._bly=Math.floor(this._bly)}ceil(){this._tlx=Math.ceil(this._tlx),this._tly=Math.ceil(this._tly),this._trx=Math.ceil(this._trx),this._try=Math.ceil(this._try),this._brx=Math.ceil(this._brx),this._bry=Math.ceil(this._bry),this._blx=Math.ceil(this._blx),this._bly=Math.ceil(this._bly)}setFromRect(t){this._tlx=t._left,this._tly=t._top,this._trx=t._right,this._try=t._top,this._brx=t._right,this._bry=t._bottom,this._blx=t._left,this._bly=t._bottom}setFromRotatedRect(t,s){0===s?this.setFromRect(t):this.setFromRotatedRectPrecalc(t,Math.sin(s),Math.cos(s))}setFromRotatedRectPrecalc(t,s,i){const h=t._left*s,_=t._top*s,r=t._right*s,l=t._bottom*s,e=t._left*i,x=t._top*i,y=t._right*i,b=t._bottom*i;this._tlx=e-_,this._tly=x+h,this._trx=y-_,this._try=x+r,this._brx=y-l,this._bry=b+r,this._blx=e-l,this._bly=b+h}getBoundingBox(t){t.set(Math.min(this._tlx,this._trx,this._brx,this._blx),Math.min(this._tly,this._try,this._bry,this._bly),Math.max(this._tlx,this._trx,this._brx,this._blx),Math.max(this._tly,this._try,this._bry,this._bly))}containsPoint(t,s){let i=this._trx-this._tlx,h=this._try-this._tly;const _=this._brx-this._tlx,r=this._bry-this._tly,l=t-this._tlx,e=s-this._tly;let x=i*i+h*h,y=i*_+h*r,b=i*l+h*e;const a=_*_+r*r,n=_*l+r*e;let o=1/(x*a-y*y),c=(a*b-y*n)*o,u=(x*n-y*b)*o;return c>=0&&u>0&&c+u<1||(i=this._blx-this._tlx,h=this._bly-this._tly,x=i*i+h*h,y=i*_+h*r,b=i*l+h*e,o=1/(x*a-y*y),c=(a*b-y*n)*o,u=(x*n-y*b)*o,c>=0&&u>0&&c+u<1)}midX(){return(this._tlx+this._trx+this._brx+this._blx)/4}midY(){return(this._tly+this._try+this._bry+this._bly)/4}intersectsSegment(t,s,i,h){return!(!this.containsPoint(t,s)&&!this.containsPoint(i,h))||C3.segmentIntersectsQuad(t,s,i,h,this)}intersectsQuad(t){let s=t.midX(),i=t.midY();if(this.containsPoint(s,i))return!0;if(s=this.midX(),i=this.midY(),t.containsPoint(s,i))return!0;const h=this._tlx,_=this._tly,r=this._trx,l=this._try,e=this._brx,x=this._bry,y=this._blx,b=this._bly;return C3.segmentIntersectsQuad(h,_,r,l,t)||C3.segmentIntersectsQuad(r,l,e,x,t)||C3.segmentIntersectsQuad(e,x,y,b,t)||C3.segmentIntersectsQuad(y,b,h,_,t)}rotatePointsAnticlockwise(){const t=this._tlx,s=this._tly;this._tlx=this._trx,this._tly=this._try,this._trx=this._brx,this._try=this._bry,this._brx=this._blx,this._bry=this._bly,this._blx=t,this._bly=s}mirror(){this._swap(0,2),this._swap(1,3),this._swap(6,4),this._swap(7,5)}flip(){this._swap(0,6),this._swap(1,7),this._swap(2,4),this._swap(3,5)}diag(){this._swap(2,6),this._swap(3,7)}_swap(t,s){const i=this._getAtIndex(t);this._setAtIndex(t,this._getAtIndex(s)),this._setAtIndex(s,i)}_getAtIndex(t){switch(t){case 0:return this._tlx;case 1:return this._tly;case 2:return this._trx;case 3:return this._try;case 4:return this._brx;case 5:return this._bry;case 6:return this._blx;case 7:return this._bly;default:throw new RangeError("invalid quad point index")}}_setAtIndex(t,s){switch(s=+s,t){case 0:this._tlx=s;break;case 1:this._tly=s;break;case 2:this._trx=s;break;case 3:this._try=s;break;case 4:this._brx=s;break;case 5:this._bry=s;break;case 6:this._blx=s;break;case 7:this._bly=s;break;default:throw new RangeError("invalid quad point index")}}};
}

// lib/misc/collisionPoly.js
{
const C3=self.C3,assert=self.assert,DEFAULT_POLY_POINTS=[0,0,1,0,1,1,0,1],tempQuad=C3.New(C3.Quad);C3.CollisionPoly=class extends C3.DefendedBase{constructor(t,s=!0){super(),t||(t=DEFAULT_POLY_POINTS),this._ptsArr=Float64Array.from(t),this._bbox=new C3.Rect,this._isBboxChanged=!0,this._enabled=s}Release(){}pointsArr(){return this._ptsArr}pointCount(){return this._ptsArr.length/2}setPoints(t){this._ptsArr.length===t.length?this._ptsArr.set(t):this._ptsArr=Float64Array.from(t),this._isBboxChanged=!0}setDefaultPoints(){this.setPoints(DEFAULT_POLY_POINTS)}copy(t){this.setPoints(t._ptsArr)}setBboxChanged(){this._isBboxChanged=!0}_updateBbox(){if(!this._isBboxChanged)return;const t=this._ptsArr;let s=t[0],e=t[1],r=s,n=e;for(let o=0,i=t.length;o<i;o+=2){const i=t[o],h=t[o+1];i<s&&(s=i),i>r&&(r=i),h<e&&(e=h),h>n&&(n=h)}this._bbox.set(s,e,r,n),this._isBboxChanged=!1}setFromRect(t,s,e){let r=this._ptsArr;8!==r.length&&(r=new Float64Array(8),this._ptsArr=r),r[0]=t.getLeft()-s,r[1]=t.getTop()-e,r[2]=t.getRight()-s,r[3]=t.getTop()-e,r[4]=t.getRight()-s,r[5]=t.getBottom()-e,r[6]=t.getLeft()-s,r[7]=t.getBottom()-e,this._bbox.copy(t),0===s&&0===e||this._bbox.offset(-s,-e),this._isBboxChanged=!1}setFromQuad(t,s,e){tempQuad.copy(t),tempQuad.offset(s,e),this.setPoints(tempQuad.toArray()),this._isBboxChanged=!0}transform(t,s,e){let r=0,n=1;0!==e&&(r=Math.sin(e),n=Math.cos(e)),this.transformPrecalc(t,s,r,n)}transformPrecalc(t,s,e,r){const n=this._ptsArr;for(let o=0,i=n.length;o<i;o+=2){const i=o+1,h=n[o]*t,l=n[i]*s;n[o]=h*r-l*e,n[i]=l*r+h*e}this._isBboxChanged=!0}offset(t,s){const e=this._ptsArr;for(let r=0,n=e.length;r<n;r+=2)e[r]+=t,e[r+1]+=s}containsPoint(t,s){const e=this._ptsArr;if(t===e[0]&&s===e[1])return!0;this._updateBbox();const r=this._bbox,n=r.getLeft()-110,o=r.getTop()-101,i=r.getRight()+131,h=r.getBottom()+120;let l=0,a=0,c=0,g=0,_=0,p=0,f=0,u=0;n<t?(l=n,c=t):(l=t,c=n),o<s?(a=o,g=s):(a=s,g=o),i<t?(_=i,f=t):(_=t,f=i),h<s?(p=h,u=s):(p=s,u=h);let C=0,A=0;for(let r=0,d=e.length;r<d;r+=2){const b=(r+2)%d,P=e[r],m=e[r+1],x=e[b],B=e[b+1];C3.segmentsIntersectPreCalc(n,o,t,s,l,c,a,g,P,m,x,B)&&++C,C3.segmentsIntersectPreCalc(i,h,t,s,_,f,p,u,P,m,x,B)&&++A}return C%2==1||A%2==1}intersectsPoly(t,s,e){const r=t._ptsArr,n=this._ptsArr;if(this.containsPoint(r[0]+s,r[1]+e))return!0;if(t.containsPoint(n[0]-s,n[1]-e))return!0;for(let t=0,o=n.length;t<o;t+=2){const i=(t+2)%o,h=n[t],l=n[t+1],a=n[i],c=n[i+1];let g=0,_=0,p=0,f=0;h<a?(g=h,p=a):(g=a,p=h),l<c?(_=l,f=c):(_=c,f=l);for(let t=0,n=r.length;t<n;t+=2){const o=(t+2)%n,i=r[t]+s,u=r[t+1]+e,C=r[o]+s,A=r[o+1]+e;if(C3.segmentsIntersectPreCalc(h,l,a,c,g,p,_,f,i,u,C,A))return!0}}return!1}intersectsSegment(t,s,e,r,n,o){if(this.containsPoint(e-t,r-s))return!0;if(this.containsPoint(n-t,o-s))return!0;let i=0,h=0,l=0,a=0;e<n?(i=e,l=n):(i=n,l=e),r<o?(h=r,a=o):(h=o,a=r);const c=this._ptsArr;for(let g=0,_=c.length;g<_;g+=2){const p=(g+2)%_,f=c[g]+t,u=c[g+1]+s,C=c[p]+t,A=c[p+1]+s;if(C3.segmentsIntersectPreCalc(e,r,n,o,i,l,h,a,f,u,C,A))return!0}return!1}mirror(t){const s=this._ptsArr;for(let e=0,r=s.length;e<r;e+=2)s[e]=2*t-s[e];this._isBboxChanged=!0}flip(t){const s=this._ptsArr;for(let e=0,r=s.length;e<r;e+=2){const r=e+1;s[r]=2*t-s[r]}this._isBboxChanged=!0}diag(){const t=this._ptsArr;for(let s=0,e=t.length;s<e;s+=2){const e=s+1,r=t[s];t[s]=t[e],t[e]=r}this._isBboxChanged=!0}GetMidX(){const t=this._ptsArr;let s=0;for(let e=0,r=t.length;e<r;e+=2)s+=t[e];return s/this.pointCount()}GetMidY(){const t=this._ptsArr;let s=0;for(let e=0,r=t.length;e<r;e+=2)s+=t[e+1];return s/this.pointCount()}GetPointsArray(){return this._ptsArr}GetPointCount(){return this.pointCount()}IsEnabled(){return this._enabled}};
}

// lib/misc/pairMap.js
{
const C3=self.C3;C3.PairMap=class extends C3.DefendedBase{constructor(e){if(super(),this._firstMap=new Map,e)for(const[t,s,r]of e)this.Set(t,s,r)}Release(){this.Clear(),this._firstMap=null}IsEmpty(){return 0===this._firstMap.size}Clear(){const e=this._firstMap;for(const t of e.values())t.clear();e.clear()}Set(e,t,s){const r=this._firstMap;let i=r.get(e);i||(i=new Map,r.set(e,i)),i.set(t,s)}Get(e,t){const s=this._firstMap.get(e);return s?s.get(t):s}Has(e,t){const s=this._firstMap.get(e);return!!s&&s.has(t)}Delete(e,t){const s=this._firstMap,r=s.get(e);if(!r)return!1;const i=r.delete(t);return i&&0===r.size&&s.delete(e),i}DeleteEither(e){const t=this._firstMap,s=t.get(e);s&&(s.clear(),t.delete(e));for(const[s,r]of t.entries())r.delete(e)&&0===r.size&&t.delete(s)}GetSize(){let e=0;for(const t of this._firstMap.values())e+=t.size;return e}*values(){for(const e of this._firstMap.values())yield*e.values()}*keyPairs(){for(const[e,t]of this._firstMap.entries())for(const s of t.keys())yield[e,s]}*entries(){for(const[e,t]of this._firstMap.entries())for(const[s,r]of t.entries())yield[e,s,r]}};
}

// lib/misc/arraySet.js
{
const C3=self.C3;C3.ArraySet=class extends C3.DefendedBase{constructor(){super(),this._set=new Set,this._arr=[],this._needToRebuildArray=!1}Release(){this.Clear()}Clear(){this._set.clear(),C3.clearArray(this._arr),this._needToRebuildArray=!1}Add(e){this._set.has(e)||(this._set.add(e),this._needToRebuildArray||this._arr.push(e))}Has(e){return this._set.has(e)}Delete(e){this._set.delete(e)&&(this._needToRebuildArray=!0)}GetSize(){return this._set.size}IsEmpty(){return 0===this._set.size}GetArray(){return this._needToRebuildArray&&(this._RebuildArray(),this._needToRebuildArray=!1),this._arr}_RebuildArray(){const e=this._arr;C3.clearArray(e);for(const r of this._set)e.push(r)}};
}

// ../lib/misc/ease.js
{
const C3=self.C3,EASE_MAP=new Map,PREDEFINED_EASE_MAP=new Map,CUSTOM_EASE_EDITOR_MAP=new Map,CUSTOM_EASE_DATA_EDITOR_MAP=new Map,CUSTOM_EASE_RUNTIME_MAP=new Map,CUSTOM_EASE_DATA_RUNTIME_MAP=new Map,PRIVATE_EASE_MAP=new Map,BUILT_IN_TRANSITION_MAP=new Map,ALIAS_MAP=new Map;ALIAS_MAP.set("linear","noease"),ALIAS_MAP.set("default","noease");const EASE_TRANSLATION_KEYS=["default","noease","easeinquad","easeoutquad","easeinoutquad","easeincubic","easeoutcubic","easeinoutcubic","easeinquart","easeoutquart","easeinoutquart","easeinquint","easeoutquint","easeinoutquint","easeinsine","easeoutsine","easeinoutsine","easeinexpo","easeoutexpo","easeinoutexpo","easeincirc","easeoutcirc","easeinoutcirc","easeinelastic","easeoutelastic","easeinoutelastic","easeinback","easeoutback","easeinoutback","easeinbounce","easeoutbounce","easeinoutbounce"],SHORT_EASE_TRANSLATION_KEYS=["default","noease","quad","cubic","quart","quint","sine","expo","circ","elastic","back","bounce"],EASE_API2INTERNAL_NAMES=new Map([["linear","noease"],["in-sine","easeinsine"],["out-sine","easeoutsine"],["in-out-sine","easeinoutsine"],["in-elastic","easeinelastic"],["out-elastic","easeoutelastic"],["in-out-elastic","easeinoutelastic"],["in-back","easeinback"],["out-back","easeoutback"],["in-out-back","easeinoutback"],["in-bounce","easeinbounce"],["out-bounce","easeoutbounce"],["in-out-bounce","easeinoutbounce"],["in-cubic","easeincubic"],["out-cubic","easeoutcubic"],["in-out-cubic","easeinoutcubic"],["in-quadratic","easeinquad"],["out-quadratic","easeoutquad"],["in-out-quadratic","easeinoutquad"],["in-quartic","easeinquart"],["out-quartic","easeoutquart"],["in-out-quartic","easeinoutquart"],["in-quintic","easeinquint"],["out-quintic","easeoutquint"],["in-out-quintic","easeinoutquint"],["in-circular","easeincirc"],["out-circular","easeoutcirc"],["in-out-circular","easeinoutcirc"],["in-exponential","easeinexpo"],["out-exponential","easeoutexpo"],["in-out-exponential","easeinoutexpo"]]);self.Ease=class e{constructor(){}static InheritEase(){return"default"}static DefaultEase(){return"noease"}static ToInternal(e){return EASE_API2INTERNAL_NAMES.get(e)}static GetEditorEaseNames(a,...s){let t,i;this._CreateEaseMap(),a?(CUSTOM_EASE_EDITOR_MAP.has(a)||CUSTOM_EASE_EDITOR_MAP.set(a,new Map),t=CUSTOM_EASE_EDITOR_MAP.get(a),i=[...t.keys()].filter((s=>!e.GetEditorEaseData(s,a)||e.GetEditorEaseData(s,a).transition.IsForAnyPurpose()))):(t=CUSTOM_EASE_RUNTIME_MAP,i=[...t.keys()]);const x=i.sort();return[...PREDEFINED_EASE_MAP.keys()].concat(x).filter((e=>!s.includes(e)))}static GetRuntimeEaseNames(){this._CreateEaseMap();const e=[...CUSTOM_EASE_RUNTIME_MAP.keys()];return e.sort(),[...PREDEFINED_EASE_MAP.keys()].concat(e)}static GetCustomRuntimeEaseNames(){this._CreateEaseMap();const e=[...CUSTOM_EASE_RUNTIME_MAP.keys()];return e.sort(),e}static IsPredefinedTranslatedName(e){for(const a of EASE_TRANSLATION_KEYS){if(self.lang(`ui.bars.timeline.eases.${a}`)===e)return!0}for(const a of SHORT_EASE_TRANSLATION_KEYS){if(self.lang(`ui.bars.timeline.short-eases.${a}`)===e)return!0}}static IsNamePredefined(e){return this._CreateEaseMap(),[...PREDEFINED_EASE_MAP.keys()].includes(e)}static _GetEase(a){const s=ALIAS_MAP.get(a);return s?EASE_MAP.get(s):e.IsNamePredefined(a)?EASE_MAP.get(a):PRIVATE_EASE_MAP.has(a)?PRIVATE_EASE_MAP.get(a):void 0}static GetBuiltInTransition(e){return this._CreateEaseMap(),BUILT_IN_TRANSITION_MAP.get(e)}static GetEditorEase(a,s){this._CreateEaseMap();const t=e._GetEase(a);if(t)return t;if(!s)throw new Error("missing ease function");return CUSTOM_EASE_EDITOR_MAP.get(s).get(a)}static GetEditorEaseData(e,a){this._CreateEaseMap();const s=CUSTOM_EASE_DATA_EDITOR_MAP.get(a);if(s)return s.get(e)}static HasEditorEase(a,s){this._CreateEaseMap();return!!e._GetEase(a)||!!CUSTOM_EASE_EDITOR_MAP.get(s).get(a)}static GetRuntimeEase(a){this._CreateEaseMap();const s=e._GetEase(a);return s||CUSTOM_EASE_RUNTIME_MAP.get(a)}static GetRuntimeEaseData(e){return this._CreateEaseMap(),CUSTOM_EASE_DATA_RUNTIME_MAP.get(e)}static GetEaseFromIndex(e){this._CreateEaseMap();return this.GetRuntimeEaseNames()[e]}static GetIndexForEase(e,a){this._CreateEaseMap();return this.GetEditorEaseNames(a).indexOf(e)}static GetIndexForEaseAtRuntime(e){return this.GetIndexForEase(e)}static _CreateEaseMap(){0===EASE_MAP.size&&(this._AddPredifinedEase("default",(()=>{})),this._AddPredifinedEase("noease",[{"x":0,"y":0,"sax":.336,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.336,"eay":0,"se":!1,"ee":!0}],!0),this._AddPredifinedEase("easeinsine",[{"x":0,"y":0,"sax":.485,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.038,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutsine",[{"x":0,"y":0,"sax":.038,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.485,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutsine",[{"x":0,"y":0,"sax":.336,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.336,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinelastic",[{"x":0,"y":0,"sax":.018,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.116,"y":.002,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.266,"y":-.005,"sax":.024,"say":0,"eax":-.021,"eay":0,"se":!0,"ee":!0},{"x":.416,"y":.016,"sax":.024,"say":0,"eax":-.026,"eay":0,"se":!0,"ee":!0},{"x":.566,"y":-.045,"sax":.061,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.716,"y":.132,"sax":.072,"say":-.004,"eax":-.045,"eay":0,"se":!0,"ee":!0},{"x":.866,"y":-.373,"sax":.06,"say":0,"eax":-.049,"eay":-.002,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.038,"eay":-.263,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutelastic",[{"x":0,"y":0,"sax":.038,"say":.263,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.136,"y":1.373,"sax":.049,"say":.002,"eax":-.06,"eay":0,"se":!0,"ee":!0},{"x":.286,"y":.868,"sax":.045,"say":0,"eax":-.072,"eay":.004,"se":!0,"ee":!0},{"x":.436,"y":1.045,"sax":.025,"say":0,"eax":-.061,"eay":0,"se":!0,"ee":!0},{"x":.586,"y":.984,"sax":.026,"say":0,"eax":-.024,"eay":0,"se":!0,"ee":!0},{"x":.736,"y":1.005,"sax":.021,"say":0,"eax":-.024,"eay":0,"se":!0,"ee":!0},{"x":.886,"y":.998,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.018,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutelastic",[{"x":0,"y":0,"sax":.025,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.067,"y":.001,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.18,"y":-.005,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.292,"y":.025,"sax":.053,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.405,"y":-.118,"sax":.069,"say":0,"eax":-.027,"eay":0,"se":!0,"ee":!0},{"x":.597,"y":1.118,"sax":.027,"say":0,"eax":-.069,"eay":0,"se":!0,"ee":!0},{"x":.71,"y":.975,"sax":.025,"say":0,"eax":-.053,"eay":0,"se":!0,"ee":!0},{"x":.822,"y":1.005,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.935,"y":.999,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.025,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinback",[{"x":0,"y":0,"sax":.35,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.34,"eay":-1.579,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutback",[{"x":0,"y":0,"sax":.34,"say":1.579,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.35,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutback",[{"x":0,"y":0,"sax":.035,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.242,"y":-.1,"sax":.258,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.76,"y":1.1,"sax":.025,"say":0,"eax":-.26,"eay":0,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.035,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinbounce",[{"x":0,"y":0,"sax":.033,"say":.025,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.092,"y":0,"sax":.026,"say":.078,"eax":-.033,"eay":.025,"se":!0,"ee":!0},{"x":.274,"y":0,"sax":.097,"say":.319,"eax":-.026,"eay":.078,"se":!0,"ee":!0},{"x":.637,"y":0,"sax":.105,"say":.625,"eax":-.097,"eay":.319,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.125,"eay":-.004,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutbounce",[{"x":0,"y":0,"sax":.125,"say":.004,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.365,"y":1,"sax":.097,"say":-.319,"eax":-.105,"eay":-.625,"se":!0,"ee":!0},{"x":.728,"y":1,"sax":.026,"say":-.078,"eax":-.097,"eay":-.319,"se":!0,"ee":!0},{"x":.91,"y":1,"sax":.033,"say":-.025,"eax":-.026,"eay":-.078,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.033,"eay":-.025,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutbounce",[{"x":0,"y":0,"sax":.01,"say":.006,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.046,"y":0,"sax":.021,"say":.038,"eax":-.01,"eay":.006,"se":!0,"ee":!0},{"x":.137,"y":0,"sax":.059,"say":.158,"eax":-.021,"eay":.038,"se":!0,"ee":!0},{"x":.319,"y":0,"sax":.117,"say":.744,"eax":-.059,"eay":.158,"se":!0,"ee":!0},{"x":.683,"y":1,"sax":.059,"say":-.158,"eax":-.117,"eay":-.744,"se":!0,"ee":!0},{"x":.865,"y":1,"sax":.021,"say":-.038,"eax":-.059,"eay":-.158,"se":!0,"ee":!0},{"x":.956,"y":1,"sax":.01,"say":-.006,"eax":-.021,"eay":-.038,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.01,"eay":-.006,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeincubic",[{"x":0,"y":0,"sax":.75,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.138,"eay":-.321,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutcubic",[{"x":0,"y":0,"sax":.138,"say":.321,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.75,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutcubic",[{"x":0,"y":0,"sax":.285,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.5,"y":.5,"sax":.081,"say":.272,"eax":-.081,"eay":-.272,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.285,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinquad",[{"x":0,"y":0,"sax":.4,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.178,"eay":-.392,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutquad",[{"x":0,"y":0,"sax":.178,"say":.392,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.4,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutquad",[{"x":0,"y":0,"sax":.25,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.5,"y":.5,"sax":.03,"say":.065,"eax":-.03,"eay":-.065,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinquart",[{"x":0,"y":0,"sax":.25,"say":1,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.5,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutquart",[{"x":0,"y":0,"sax":.5,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":-1,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutquart",[{"x":0,"y":0,"sax":.765,"say":.03,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.765,"eay":-.03,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinquint",[{"x":0,"y":0,"sax":.6,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.2,"eay":-1,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutquint",[{"x":0,"y":0,"sax":.2,"say":1,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.6,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutquint",[{"eax":0,"eay":0,"ee":!1,"sax":.84,"say":0,"se":!0,"x":0,"y":0},{"eax":-.84,"eay":0,"ee":!0,"sax":0,"say":0,"se":!1,"x":1,"y":1}]),this._AddPredifinedEase("easeincirc",[{"x":0,"y":0,"sax":.25,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.024,"eay":-.808,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutcirc",[{"x":0,"y":0,"sax":.024,"say":.808,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutcirc",[{"x":0,"y":0,"sax":.125,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.5,"y":.5,"sax":.02,"say":.428,"eax":-.02,"eay":-.428,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.125,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinexpo",[{"x":0,"y":0,"sax":.66,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.14,"eay":-1,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutexpo",[{"x":0,"y":0,"sax":.14,"say":1,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.66,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutexpo",[{"eax":0,"eay":0,"ee":!1,"sax":.345,"say":0,"se":!0,"x":0,"y":0},{"eax":-.06,"eay":-.5,"ee":!0,"sax":.06,"say":.5,"se":!0,"x":.5,"y":.5},{"eax":-.335,"eay":0,"ee":!0,"sax":0,"say":0,"se":!1,"x":1,"y":1}]),this._AddPrivateCustomEase("cubicbezier",this.EaseCubicBezier),this._AddPrivateCustomEase("spline",this.EaseSpline))}static _AddPredifinedEase(a,s,t=!1){if("function"==typeof s)e._AddEase(a,s,"predefined");else{if(!C3.IsArray(s))throw new Error("unexpected arguments");if(self.BuiltInTransition){const i=C3.New(self.BuiltInTransition,a,t);i.SetFromJson(s),e._AddEase(a,((e,a,s,t)=>i.Interpolate(e,a,s,t)),"predefined"),BUILT_IN_TRANSITION_MAP.set(a,i)}else{const i=C3.New(C3.Transition,[a,s.map((e=>[e["x"],e["y"],e["sax"],e["say"],e["eax"],e["eay"],e["se"],e["ee"]]))],!1);i.MakeLinear(t),e._AddEase(a,((e,a,s,t)=>i.Interpolate(e,a,s,t)),"predefined")}}}static _AddPrivateCustomEase(a,s){e._AddEase(a,s,"private")}static AddCustomEase(a,s,t,i){this._CreateEaseMap(),e._AddEase(a,s,"custom",t,i)}static RemoveCustomEase(e,a){if(this.IsNamePredefined(e))return;if([...PRIVATE_EASE_MAP.keys()].includes(e))return;const s=CUSTOM_EASE_EDITOR_MAP.get(a);s&&s.delete(e);const t=CUSTOM_EASE_DATA_EDITOR_MAP.get(a);t&&t.delete(e)}static _AddEase(e,a,s,t,i){switch(s){case"predefined":EASE_MAP.set(e,a),PREDEFINED_EASE_MAP.set(e,a);break;case"custom":if(t){CUSTOM_EASE_EDITOR_MAP.has(t)||CUSTOM_EASE_EDITOR_MAP.set(t,new Map),CUSTOM_EASE_DATA_EDITOR_MAP.has(t)||CUSTOM_EASE_DATA_EDITOR_MAP.set(t,new Map);CUSTOM_EASE_EDITOR_MAP.get(t).set(e,a);CUSTOM_EASE_DATA_EDITOR_MAP.get(t).set(e,i)}else CUSTOM_EASE_RUNTIME_MAP.set(e,a),CUSTOM_EASE_DATA_RUNTIME_MAP.set(e,i);break;case"private":EASE_MAP.set(e,a),PRIVATE_EASE_MAP.set(e,a);break;default:throw new Error("unexpected ease mode")}}static NoEase(e,a,s,t){return 0===t?a:s*e/t+a}static EaseCubicBezier(e,a,s,t,i){return a+3*e*(s-a)+3*e**2*(a+t-2*s)+e**3*(i-a+3*s-3*t)}static EaseSpline(e,s,t,i,x,y,n,E,_,r){if(i===x&&y===n)return e;const u=get_t_for_x(e,s,i,y,E,r),d=a(t,x,n,_),A=b(t,x,n,_),o=c(t,x,n,_);return calc_bezier(u,d,A,o)}static GetBezierSamples(e,s,t,i){const x=[],y=a(e,s,t,i),n=b(e,s,t,i),E=c(e,s,t,i);for(let e=0;e<SAMPLE_COUNT;++e){const a=calc_bezier(e*SAMPLE_STEP,y,n,E);x.push(a)}return x}};const SAMPLE_COUNT=11,SAMPLE_STEP=1/(SAMPLE_COUNT-1),NEWTON_RAPHSON_ITERATIONS=4,NEWTON_RAPHSON_MIN_SLOPE=.01,SUBDIVISION_PRECISION=1e-7,SUBDIVISION_MAX_ITERATIONS=10,a=(e,a,s,t)=>t-3*s+3*a-e,b=(e,a,s,t)=>3*s-6*a+3*e,c=(e,a,s,t)=>3*(a-e),calc_bezier=(e,a,s,t)=>((a*e+s)*e+t)*e,get_slope=(e,a,s,t)=>3*a*e*e+2*s*e+t,get_t_for_x=(e,s,t,i,x,y)=>{if(1==e)return 1;let n=0,E=1,_=y[E],r=SAMPLE_COUNT-1;y[SAMPLE_COUNT-1];for(;E!=r&&_<=e;)E++,_=y[E],n+=SAMPLE_STEP;E--,_=y[E];let u=n+(e-_)/(y[E+1]-_)*SAMPLE_STEP;const d=a(s,t,i,x),A=b(s,t,i,x),o=c(s,t,i,x),M=get_slope(u,d,A,o);if(0===M)return u;if(M>=.01){for(let a=0;a<4;++a){u-=(calc_bezier(u,d,A,o)-e)/get_slope(u,d,A,o)}return u}{let a,s,t=n,i=n+SAMPLE_STEP,x=0;do{u=t+(i-t)/2;let y=calc_bezier(u,d,A,o)-e;y>0?i=u:t=u,a=Math.abs(y)>1e-7,s=++x<10}while(a&&s);return u}};
}

// ../lib/misc/probability.js
{
const C3=self.C3;function RequireStringOrNumber(t){C3.IsString(t)}C3.ProbabilityTable=class{constructor(t){this._items=[],this._name=t||"",this._totalWeight=0}Release(){this.Clear(),this._items=null}GetName(){return this._name}Clear(){C3.clear2DArray(this._items),this._totalWeight=0}GetTotalWeight(){return this._totalWeight}Sample(t=Math.random()*this.GetTotalWeight()){let e=0;for(const[i,s]of this._items)if(e+=i,t<e)return s;return 0}HasItems(){return!!this._items.length}AddItem(t,e){RequireStringOrNumber(e),this._totalWeight+=t,this._items.push([t,e])}RemoveItem(t,e){RequireStringOrNumber(e);const i=0===t;for(let s=0;s<this._items.length;s++){const r=this._items[s],h=i||r[0]===t,n=r[1]===e;if(h&&n){this._items.splice(s,1),this._totalWeight-=r[0];break}}}asJSON(){return JSON.stringify(this._items)}static fromJSON(t,e){const i=new C3.ProbabilityTable(e),s=JSON.parse(t);for(const t of s){const e=t[0],s=t[1];i.AddItem(e,s)}return i}};
}

// lib/misc/screenReaderText.js
{
const C3=self.C3;let nextId=0;C3.ScreenReaderText=class{constructor(t,e){this._runtime=t,this._text=e,this._id=nextId++,this._runtime.PostComponentMessageToDOM("runtime","screen-reader-text",{"type":"create","id":this._id,"text":this._text})}Release(){this._runtime.PostComponentMessageToDOM("runtime","screen-reader-text",{"type":"release","id":this._id}),this._runtime=null,this._text="",this._id=-1}SetText(t){this._text!==t&&(this._text=t,this._runtime.PostComponentMessageToDOM("runtime","screen-reader-text",{"type":"update","id":this._id,"text":this._text}))}};
}

// ../lib/events/event.js
{
const C3=self.C3;C3.Event=class{constructor(t,e){this.type=t,this.cancelable=!!e,this.defaultPrevented=!1,this.propagationStopped=!1,this.isAsync=!1}preventDefault(){if(!this.cancelable)throw new Error(`event '${this.type}' is not cancelable`);this.defaultPrevented=!0}stopPropagation(){if(!this.cancelable)throw new Error(`event '${this.type}' cannot be stopped`);if(this.isAsync)throw new Error(`cannot stop async event '${this.type}' propagation`);this.propagationStopped=!0}};
}

// ../lib/events/handler.js
{
const C3=self.C3,assert=self.assert;C3.Event.Handler=class extends C3.DefendedBase{constructor(e){super(),this._type=e,this._captureListeners=[],this._captureListenersSet=new Set,this._listeners=[],this._listenersSet=new Set,this._fireDepth=0,this._queueModifyListeners=[]}Release(){this._fireDepth>0||(C3.clearArray(this._captureListeners),this._captureListenersSet.clear(),C3.clearArray(this._listeners),this._listenersSet.clear(),C3.clearArray(this._queueModifyListeners),C3.Release(this))}_AddListener(e,t){if(this._IsFiring())this._queueModifyListeners.push({op:"add",func:e,capture:t});else if(t){if(this._captureListenersSet.has(e))return;this._captureListeners.push(e),this._captureListenersSet.add(e)}else{if(this._listenersSet.has(e))return;this._listeners.push(e),this._listenersSet.add(e)}}_RemoveListener(e,t){this._IsFiring()?this._queueModifyListeners.push({op:"remove",func:e,capture:t}):t?this._captureListenersSet.has(e)&&(this._captureListenersSet.delete(e),C3.arrayFindRemove(this._captureListeners,e)):this._listenersSet.has(e)&&(this._listenersSet.delete(e),C3.arrayFindRemove(this._listeners,e))}_IsEmpty(){return!this._captureListeners.length&&!this._listeners.length}_IsFiring(){return this._fireDepth>0}_ProcessQueuedListeners(){const e=new Set,t=new Set;for(const s of this._queueModifyListeners)if("add"===s.op)this._AddListener(s.func,s.capture),s.capture?t.delete(s.func):e.delete(s.func);else{if("remove"!==s.op)throw new Error("invalid op");s.capture?(this._captureListenersSet.delete(s.func),t.add(s.func)):(this._listenersSet.delete(s.func),e.add(s.func))}C3.arrayRemoveAllInSet(this._listeners,e),C3.arrayRemoveAllInSet(this._captureListeners,t),C3.clearArray(this._queueModifyListeners)}_FireCancellable(e){this._IncreaseFireDepth();let t=!1;for(let s=0,r=this._captureListeners.length;s<r;++s)if(this._captureListeners[s](e),e.propagationStopped){t=!0;break}if(!t)for(let t=0,s=this._listeners.length;t<s&&(this._listeners[t](e),!e.propagationStopped);++t);return this._DecreaseFireDepth(),!e.defaultPrevented}_FireNonCancellable(e){this._IncreaseFireDepth();for(let t=0,s=this._captureListeners.length;t<s;++t)this._captureListeners[t](e);for(let t=0,s=this._listeners.length;t<s;++t)this._listeners[t](e);return this._DecreaseFireDepth(),!0}_IncreaseFireDepth(){this._fireDepth++}_DecreaseFireDepth(){this._fireDepth--,0===this._fireDepth&&this._queueModifyListeners.length>0&&this._ProcessQueuedListeners()}SetDelayRemoveEventsEnabled(e){e?this._IncreaseFireDepth():this._DecreaseFireDepth()}_FireAsync(e){let t=[];for(let s=0,r=this._captureListeners.length;s<r;++s){let r=this._captureListeners[s];t.push(C3.Asyncify((()=>r(e))))}for(let s=0,r=this._listeners.length;s<r;++s){let r=this._listeners[s];t.push(C3.Asyncify((()=>r(e))))}return Promise.all(t).then((()=>!e.defaultPrevented))}_FireAndWait_AsyncOptional(e){const t=[];this._IncreaseFireDepth();for(let s=0,r=this._captureListeners.length;s<r;++s){const r=this._captureListeners[s](e);r instanceof Promise&&t.push(r)}for(let s=0,r=this._listeners.length;s<r;++s){const r=this._listeners[s](e);r instanceof Promise&&t.push(r)}return this._DecreaseFireDepth(),t.length?Promise.all(t).then((()=>!e.defaultPrevented)):!e.defaultPrevented}async _FireAndWaitAsync(e){return await this._FireAndWait_AsyncOptional(e)}async _FireAndWaitAsyncSequential(e){this._IncreaseFireDepth();for(let t=0,s=this._captureListeners.length;t<s;++t){const s=this._captureListeners[t](e);s instanceof Promise&&await s}for(let t=0,s=this._listeners.length;t<s;++t){const s=this._listeners[t](e);s instanceof Promise&&await s}return this._DecreaseFireDepth(),!e.defaultPrevented}*_FireAsGenerator(e){this._IncreaseFireDepth();for(let t=0,s=this._captureListeners.length;t<s;++t){const s=this._captureListeners[t](e);C3.IsIterator(s)&&(yield*s)}for(let t=0,s=this._listeners.length;t<s;++t){const s=this._listeners[t](e);C3.IsIterator(s)&&(yield*s)}this._DecreaseFireDepth()}};
}

// ../lib/events/dispatcher.js
{
const C3=self.C3;C3.Event.Dispatcher=class extends C3.DefendedBase{constructor(){super(),this._eventHandlers=new Map,this._dispatcherWasReleased=!1}Release(){if(this._dispatcherWasReleased)throw new Error("already released");this.ClearEvents(),this._dispatcherWasReleased=!0,C3.Release(this)}WasReleased(){return this._dispatcherWasReleased}ClearEvents(){if(this._eventHandlers){for(let e of this._eventHandlers.values())e.Release();this._eventHandlers.clear()}}_GetHandlerByType(e,t){let n=this._eventHandlers.get(e);return n||(t?(n=C3.New(C3.Event.Handler,e),this._eventHandlers.set(e,n),n):null)}HasAnyHandlerFor(e){return this._eventHandlers.has(e)}addEventListener(e,t,n){this._GetHandlerByType(e,!0)._AddListener(t,!!n)}removeEventListener(e,t,n){let s=this._GetHandlerByType(e,!1);s&&(s._RemoveListener(t,!!n),s._IsEmpty()&&this._eventHandlers.delete(e))}dispatchEvent(e){const t=this._GetHandlerByType(e.type,!1);return!t||(e.cancelable?t._FireCancellable(e):t._FireNonCancellable(e))}dispatchEventAsync(e){const t=this._GetHandlerByType(e.type,!1);return t?(e.isAsync=!0,t._FireAsync(e)):Promise.resolve(!0)}async dispatchEventAndClearAsync(e){const t=this._GetHandlerByType(e.type,!1);if(!t)return!0;this._eventHandlers.delete(e.type),e.isAsync=!0;const n=await t._FireAsync(e);return t.Release(),n}async dispatchEventAndWaitAsync(e){const t=this._GetHandlerByType(e.type,!1);return!t||await t._FireAndWaitAsync(e)}dispatchEventAndWait_AsyncOptional(e){const t=this._GetHandlerByType(e.type,!1);return!t||t._FireAndWait_AsyncOptional(e)}async dispatchEventAndWaitAsyncSequential(e){const t=this._GetHandlerByType(e.type,!1);return!t||await t._FireAndWaitAsyncSequential(e)}dispatchGeneratorEvent(e){const t=this._GetHandlerByType(e.type,!1);if(!t)return null;if(e.cancelable)throw new Error("not supported");return t._FireAsGenerator(e)}SetDelayRemoveEventsEnabled(e){for(const t of this._eventHandlers.values())t.SetDelayRemoveEventsEnabled(e)}};
}

// ../lib/util/asyncify.js
{
const C3=self.C3,SETTIMEOUT_WORK_DURATION=12,SETTIMEOUT_INTERVAL=16,IDLECALLBACK_TIMEOUT=35,SUPPORTS_RIC="undefined"!=typeof requestIdleCallback;let workQueue=[],callbackId=-1,highThroughputMode=0;function SetNewCallback(e){callbackId=SUPPORTS_RIC&&0===highThroughputMode?requestIdleCallback(DoAsyncifiedWork,{timeout:35}):setTimeout(DoAsyncifiedWork,highThroughputMode>0?1:e)}function DoAsyncifiedWork(e){if(callbackId=-1,!workQueue.length)return;let o=performance.now(),i=o,t=0,n=0;do{DoNextAsyncifiedJob(workQueue.shift()),i=performance.now(),++t,n=(i-o)/t*1.1}while(workQueue.length&&(SUPPORTS_RIC&&0===highThroughputMode&&void 0!==e?n<e["timeRemaining"]():i-o+n<12));if(-1===callbackId&&workQueue.length){let e=i-o;SetNewCallback(Math.max(16-e,4))}}function DoNextAsyncifiedJob(e){let o;try{o=e.func()}catch(o){return void e.reject(o)}e.resolve(o)}let asyncifyDisabled=C3.QueryString.Has("disable-asyncify");asyncifyDisabled&&console.warn("[Asyncify] Asyncify has been disabled due to disable-asyncify in the query string. Some work will now be done synchronously."),C3.Asyncify=function(e){let o=null;return C3.isDebug&&(o=C3.GetCallStack()),new Promise(((i,t)=>{workQueue.push({func:e,resolve:i,reject:t,stack:o}),asyncifyDisabled?DoNextAsyncifiedJob(workQueue.pop()):-1===callbackId&&SetNewCallback(16)}))},C3.Asyncify.SetHighThroughputMode=function(e){if(e)++highThroughputMode;else if(--highThroughputMode,highThroughputMode<0)throw new Error("already turned off high throughput mode")};
}

// ../lib/util/idleTimeout.js
{
const C3=self.C3,IDLE_CHECK_MIN_INTERVAL=1e3,IDLE_CHECK_TIMER_OVERSHOOT=100;let cachedNowTime=-1;function ClearTimeCache(){cachedNowTime=-1}C3.FastGetDateNow=function(){return-1===cachedNowTime&&(cachedNowTime=Date.now(),self.setTimeout(ClearTimeCache,16)),cachedNowTime};let timerId=-1,nextDeadline=-1,activeIdleTimeouts=new Set;function CheckActiveIdleTimeouts(){timerId=-1,nextDeadline=-1;let e=Date.now();for(let t of activeIdleTimeouts)if(t._CheckTimeout(e)){let e=t._GetDeadline();(-1===nextDeadline||e<nextDeadline)&&(nextDeadline=e)}else activeIdleTimeouts.delete(t);if(-1!==nextDeadline){let t=Math.max(nextDeadline-e+100,1e3);timerId=self.setTimeout(CheckActiveIdleTimeouts,t)}}C3.IdleTimeout=class{constructor(e,t){this._callback=e,this._timeout=1e3*t,this._deadline=0,this._isActive=!1}Reset(){let e=C3.FastGetDateNow();this._deadline=e+this._timeout,this._isActive||(activeIdleTimeouts.add(this),this._isActive=!0),-1===timerId?(nextDeadline=this._deadline,timerId=self.setTimeout(CheckActiveIdleTimeouts,this._timeout+100)):this._deadline<nextDeadline&&nextDeadline>e+1e3&&(self.clearTimeout(timerId),nextDeadline=this._deadline,timerId=self.setTimeout(CheckActiveIdleTimeouts,this._timeout+100))}_CheckTimeout(e){return!(e>=this._deadline)||(this._callback()?(this._deadline=e+this._timeout,!0):(this._isActive=!1,!1))}_GetDeadline(){return this._deadline}Cancel(){this._isActive&&(activeIdleTimeouts.delete(this),this._isActive=!1,0===activeIdleTimeouts.size&&-1!==timerId&&(self.clearTimeout(timerId),timerId=-1,nextDeadline=-1))}Release(){this.Cancel(),this._callback=null}};
}

// ../lib/util/disposable.js
{
const C3=self.C3;C3.Disposable=class s{constructor(s){this._disposed=!1,this._disposeAction=s}Dispose(){this._disposed||(this._disposed=!0,this._disposeAction&&(this._disposeAction(),this._disposeAction=null))}IsDisposed(){return this._disposed}Release(){this.Dispose()}static Release(e){return new s((()=>e.Release()))}static From(s,e,i,o,t){if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("expected string or array");if(null==o)o=!1;else if("boolean"!=typeof o&&"object"!=typeof o)throw new TypeError("invalid event listener options");if(t&&(i=i.bind(t)),Array.isArray(e)||e.includes(" ")){"string"==typeof e&&(e=e.split(" "));const t=new C3.CompositeDisposable;for(const r of e)s.addEventListener(r,i,o),t.Add(C3.New(C3.Disposable,(()=>s.removeEventListener(r,i,o))));return t}return s.addEventListener(e,i,o),C3.New(C3.Disposable,(()=>s.removeEventListener(e,i,o)))}},C3.StubDisposable=class extends C3.Disposable{SetAction(s){this._disposeAction=s}},C3.CompositeDisposable=class extends C3.Disposable{constructor(...s){super(),this._disposables=new Set;for(let e of s)this.Add(e)}Add(...s){if(this._disposed)throw new Error("already disposed");for(let e of s)this._disposables.add(e)}Remove(s){if(this._disposed)throw new Error("already disposed");this._disposables.delete(s)}RemoveAll(){if(this._disposed)throw new Error("already disposed");if(this._disposables){for(let s of this._disposables)s.Dispose();this._disposables.clear()}}IsDisposed(){return this._disposed}Dispose(){if(this._disposed)throw new Error("already disposed");this._disposed=!0;for(let s of this._disposables)s.Dispose();this._disposables.clear(),this._disposables=null}Release(){this.Dispose()}};
}

// lib/util/kahanSum.js
{
const C3=self.C3;C3.KahanSum=class extends C3.DefendedBase{constructor(){super(),this._c=0,this._y=0,this._t=0,this._sum=0}Add(s){s=+s,this._y=s-this._c,this._t=this._sum+this._y,this._c=this._t-this._sum-this._y,this._sum=this._t}Subtract(s){this._sum-=+s}Get(){return this._sum}Reset(){this._c=0,this._y=0,this._t=0,this._sum=0}Set(s){this._c=0,this._y=0,this._t=0,this._sum=+s}Copy(s){this._c=s._c,this._y=s._y,this._t=s._t,this._sum=s._sum}Release(){}};
}

// lib/util/redblackset.js
{
const C3=self.C3,js_cols={},RED=!0,BLACK=!1;js_cols.RBnode=function(t){this.tree=t,this.right=this.tree.sentinel,this.left=this.tree.sentinel,this.parent=null,this.color=!1,this.key=null},js_cols.RedBlackSet=function(t){this.size=0,this.sentinel=new js_cols.RBnode(this),this.sentinel.color=false,this.root=this.sentinel,this.root.parent=this.sentinel,this.compare=t||this.default_compare},js_cols.RedBlackSet.prototype.default_compare=function(t,e){return t<e?-1:e<t?1:0},js_cols.RedBlackSet.prototype.clone=function(){var t=new js_cols.RedBlackSet(this.compare);return t.insertAll(this),t},js_cols.RedBlackSet.prototype.clear=function(){this.size=0,this.sentinel=new js_cols.RBnode(this),this.sentinel.color=false,this.root=this.sentinel,this.root.parent=this.sentinel},js_cols.RedBlackSet.prototype.leftRotate=function(t){var e=t.right;t.right=e.left,e.left!=this.sentinel&&(e.left.parent=t),e.parent=t.parent,t.parent==this.sentinel?this.root=e:t==t.parent.left?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e},js_cols.RedBlackSet.prototype.rightRotate=function(t){var e=t.left;t.left=e.right,e.right!=this.sentinel&&(e.right.parent=t),e.parent=t.parent,t.parent==this.sentinel?this.root=e:t==t.parent.right?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e},js_cols.RedBlackSet.prototype.insert=function(t){if(this.contains(t)){this.get_(t).key=t}else{var e=new js_cols.RBnode(this);e.key=t;for(var s=this.sentinel,r=this.root;r!=this.sentinel;)s=r,r=this.compare(e.key,r.key)<0?r.left:r.right;e.parent=s,s==this.sentinel?this.root=e:this.compare(e.key,s.key)<0?s.left=e:s.right=e,e.left=this.sentinel,e.right=this.sentinel,e.color=RED,this.insertFixup(e),this.size++}},js_cols.RedBlackSet.prototype.insertFixup=function(t){for(;t!=this.sentinel&&t!=this.root&&t.parent.color==RED;){var e;if(t.parent==t.parent.parent.left)(e=t.parent.parent.right).color==RED?(t.parent.color=false,e.color=false,t.parent.parent.color=RED,t=t.parent.parent):(t==t.parent.right&&(t=t.parent,this.leftRotate(t)),t.parent.color=false,t.parent.parent.color=RED,t.parent.parent!=this.sentinel&&this.rightRotate(t.parent.parent));else(e=t.parent.parent.left).color==RED?(t.parent.color=false,e.color=false,t.parent.parent.color=RED,t=t.parent.parent):(t==t.parent.left&&(t=t.parent,this.rightRotate(t)),t.parent.color=false,t.parent.parent.color=RED,t.parent.parent!=this.sentinel&&this.leftRotate(t.parent.parent))}this.root.color=false},js_cols.RedBlackSet.prototype.delete_=function(t){var e,s;(s=(e=t.left==this.sentinel||t.right==this.sentinel?t:this.successor_(t)).left!=this.sentinel?e.left:e.right).parent=e.parent,e.parent==this.sentinel?this.root=s:e==e.parent.left?e.parent.left=s:e.parent.right=s,e!=t&&(t.key=e.key),false==e.color&&this.deleteFixup(s),this.size--},js_cols.RedBlackSet.prototype.deleteFixup=function(t){for(;t!=this.root&&false==t.color;){var e;if(t==t.parent.left)(e=t.parent.right).color==RED&&(e.color=false,t.parent.color=RED,this.leftRotate(t.parent),e=t.parent.right),false==e.left.color&&false==e.right.color?(e.color=RED,t=t.parent):(false==e.right.color&&(e.left.color=false,e.color=RED,this.rightRotate(e),e=t.parent.right),e.color=t.parent.color,t.parent.color=false,e.right.color=false,this.leftRotate(t.parent),t=this.root);else(e=t.parent.left).color==RED&&(e.color=false,t.parent.color=RED,this.rightRotate(t.parent),e=t.parent.left),false==e.right.color&&false==e.left.color?(e.color=RED,t=t.parent):(false==e.left.color&&(e.right.color=false,e.color=RED,this.leftRotate(e),e=t.parent.left),e.color=t.parent.color,t.parent.color=false,e.left.color=false,this.rightRotate(t.parent),t=this.root)}t.color=false},js_cols.RedBlackSet.prototype.remove=function(t){var e=this.get_(t);if(e!=this.sentinel){var s=e.key;return this.delete_(e),s}return null},js_cols.RedBlackSet.prototype.removeSwapped=function(t,e){this.remove(e)},js_cols.RedBlackSet.prototype.min=function(t){for(;t.left!=this.sentinel;)t=t.left;return t},js_cols.RedBlackSet.prototype.max=function(t){for(;t.right!=this.sentinel;)t=t.right;return t},js_cols.RedBlackSet.prototype.successor_=function(t){if(t.right!=this.sentinel)return this.min(t.right);for(var e=t.parent;e!=this.sentinel&&t==e.right;)t=e,e=e.parent;return e},js_cols.RedBlackSet.prototype.predeccessor_=function(t){if(t.left!=this.sentinel)return this.max(t.left);for(var e=t.parent;e!=this.sentinel&&t==e.left;)t=e,e=e.parent;return e},js_cols.RedBlackSet.prototype.successor=function(t){if(this.size>0){var e=this.get_(t);if(e==this.sentinel)return null;if(e.right!=this.sentinel)return this.min(e.right).key;for(var s=e.parent;s!=this.sentinel&&e==s.right;)e=s,s=s.parent;return s!=this.sentinel?s.key:null}return null},js_cols.RedBlackSet.prototype.predecessor=function(t){if(this.size>0){var e=this.get_(t);if(e==this.sentinel)return null;if(e.left!=this.sentinel)return this.max(e.left).key;for(var s=e.parent;s!=this.sentinel&&e==s.left;)e=s,s=s.parent;return s!=this.sentinel?s.key:null}return null},js_cols.RedBlackSet.prototype.getMin=function(){return this.min(this.root).key},js_cols.RedBlackSet.prototype.getMax=function(){return this.max(this.root).key},js_cols.RedBlackSet.prototype.get_=function(t){for(var e=this.root;e!=this.sentinel&&0!=this.compare(e.key,t);)e=this.compare(t,e.key)<0?e.left:e.right;return e},js_cols.RedBlackSet.prototype.contains=function(t){return null!=this.get_(t).key},js_cols.RedBlackSet.prototype.getValues=function(){var t=[];return this.forEach((function(e){t.push(e)})),t},js_cols.RedBlackSet.prototype.insertAll=function(t){if("array"==js_cols.typeOf(t))for(var e=0;e<t.length;e++)this.insert(t[e]);else if("function"==js_cols.typeOf(t.forEach))t.forEach(this.insert,this);else if("function"==js_cols.typeOf(t.getValues)){var s=t.getValues();for(e=0;e<s.length;e++)this.insert(s[e])}else if("object"==js_cols.typeOf(t))for(var r in t)this.insert(t[r])},js_cols.RedBlackSet.prototype.removeAll=function(t){if("array"==js_cols.typeOf(t))for(var e=0;e<t.length;e++)this.remove(t[e]);else if("function"==js_cols.typeOf(t.forEach))t.forEach(this.removeSwapped,this);else if("function"==js_cols.typeOf(t.getValues)){var s=t.getValues();for(e=0;e<s.length;e++)this.remove(s[e])}else if("object"==js_cols.typeOf(t))for(var r in t)this.remove(t[r])},js_cols.RedBlackSet.prototype.containsAll=function(t){if("array"==js_cols.typeOf(t)){for(var e=0;e<t.length;e++)if(!this.contains(t[e]))return!1;return!0}if("function"==js_cols.typeOf(t.forEach))return t.every(this.contains,this);if("function"==js_cols.typeOf(t.getValues)){var s=t.getValues();for(e=0;e<s.length;e++)if(!this.contains(s[e]))return!1;return!0}if("object"==js_cols.typeOf(t)){for(var r in t)if(!this.contains(t[r]))return!1;return!0}},js_cols.RedBlackSet.prototype.range=function(t,e){var s=[];return this.traverseFromTo((function(t){s.push(t)}),t,e),s},js_cols.RedBlackSet.prototype.traverse=function(t,e){if(!this.isEmpty())for(var s=this.min(this.root);s!=this.sentinel;){if(t.call(e,s.key,this))return;s=this.successor_(s)}},js_cols.RedBlackSet.prototype.traverseFrom=function(t,e,s){if(!this.isEmpty())for(var r=this.get_(e);r!=this.sentinel;){if(t.call(s,r.key,this))return;r=this.successor_(r)}},js_cols.RedBlackSet.prototype.traverseTo=function(t,e,s){if(!this.isEmpty())for(var r=this.min(this.root),i=this.get_(e);r!=i;){if(t.call(s,r.key,this))return;r=this.successor_(r)}},js_cols.RedBlackSet.prototype.traverseFromTo=function(t,e,s,r){if(!this.isEmpty())for(var i=this.get_(e),o=this.get_(s);i!=o;){if(t.call(r,i.key,this))return;i=this.successor_(i)}},js_cols.RedBlackSet.prototype.traverseBackwards=function(t,e){if(!this.isEmpty())for(var s=this.max(this.root);s!=this.sentinel;){if(t.call(e,s.key,this))return;s=this.predeccessor_(s)}},js_cols.RedBlackSet.prototype.forEach=function(t,e){if(!this.isEmpty())for(var s=this.min(this.root);s!=this.sentinel;s=this.successor_(s))t.call(e,s.key,s.key,this)},js_cols.RedBlackSet.prototype.some=function(t,e){if(this.isEmpty())return!1;for(var s=this.min(this.root);s!=this.sentinel;s=this.successor_(s))if(t.call(e,s.key,s.key,this))return!0;return!1},js_cols.RedBlackSet.prototype.every=function(t,e){if(this.isEmpty())return!1;for(var s=this.min(this.root);s!=this.sentinel;s=this.successor_(s))if(!t.call(e,s.key,s.key,this))return!1;return!0},js_cols.RedBlackSet.prototype.map=function(t,e){var s=[];if(this.isEmpty())return s;for(var r=this.min(this.root);r!=this.sentinel;r=this.successor_(r))s.push(t.call(e,r.key,r.key,this));return s},js_cols.RedBlackSet.prototype.filter=function(t,e){var s=[];if(this.isEmpty())return s;for(var r=this.min(this.root);r!=this.sentinel;r=this.successor_(r))t.call(e,r.key,r.key,this)&&s.push(r.key);return s},js_cols.RedBlackSet.prototype.getCount=function(){return this.size},js_cols.RedBlackSet.prototype.isEmpty=function(){return 0==this.size},js_cols.RedBlackSet.prototype.isSubsetOf=function(t){var e=js_cols.getCount(t);if(this.getCount()>e)return!1;var s=0;if(this.isEmpty())return!0;for(var r=this.min(this.root);r!=this.sentinel;r=this.successor_(r))js_cols.contains.call(t,t,r.key)&&s++;return s==this.getCount()},js_cols.RedBlackSet.prototype.intersection=function(t){var e=new js_cols.RedBlackSet(this.compare);if(this.isEmpty())return e;for(var s=this.min(this.root);s!=this.sentinel;s=this.successor_(s))t.contains.call(t,s.key,s.key,this)&&e.insert(s.key);return e},C3.RedBlackSet=class extends C3.DefendedBase{constructor(t){super(),this._rbSet=new js_cols.RedBlackSet(t),this._enableQueue=!1,this._queueInsert=new Set,this._queueRemove=new Set}Add(t){this._enableQueue?this._rbSet.contains(t)?this._queueRemove.delete(t):this._queueInsert.add(t):this._rbSet.insert(t)}Remove(t){this._enableQueue?this._rbSet.contains(t)?this._queueRemove.add(t):this._queueInsert.delete(t):this._rbSet.remove(t)}Has(t){return this._enableQueue?!!this._queueInsert.has(t)||!this._queueRemove.has(t)&&this._rbSet.contains(t):this._rbSet.contains(t)}Clear(){this._rbSet.clear(),this._queueInsert.clear(),this._queueRemove.clear()}toArray(){if(this._enableQueue)throw new Error("cannot be used in queueing mode");return this._rbSet.getValues()}GetSize(){return this._rbSet.getCount()+this._queueInsert.size-this._queueRemove.size}IsEmpty(){return 0===this.GetSize()}Front(){if(this.IsEmpty())throw new Error("empty set");if(this._enableQueue)throw new Error("cannot be used in queueing mode");const t=this._rbSet;return t.min(t.root).key}Shift(){if(this.IsEmpty())throw new Error("empty set");if(this._enableQueue)throw new Error("cannot be used in queueing mode");const t=this.Front();return this.Remove(t),t}SetQueueingEnabled(t){if(t=!!t,this._enableQueue!==t&&(this._enableQueue=t,!t)){for(const t of this._queueRemove)this._rbSet.remove(t);this._queueRemove.clear();for(const t of this._queueInsert)this._rbSet.insert(t);this._queueInsert.clear()}}ForEach(t){this._rbSet.forEach(t)}*values(){if(this.IsEmpty())return;const t=this._rbSet;for(let e=t.min(t.root);e!=t.sentinel;e=t.successor_(e))yield e.key}[Symbol.iterator](){return this.values()}};
}

// ../lib/util/promiseThrottle.js
{
const C3=self.C3;C3.PromiseThrottle=class{constructor(e=C3.hardwareConcurrency){this._maxParallel=e,this._queue=[],this._activeCount=0}Add(e){return new Promise(((t,r)=>{this._queue.push({func:e,resolve:t,reject:r}),this._MaybeStartNext()}))}_FindInQueue(e){for(let t=0,r=this._queue.length;t<r;++t)if(this._queue[t].func===e)return t;return-1}RemoveAndResolve(e,t){const r=this._FindInQueue(e);if(-1===r)throw new Error("cannot find promise to resolve");this._queue[r].resolve(t),this._queue.splice(r,1)}RemoveAndReject(e,t){const r=this._FindInQueue(e);if(-1===r)throw new Error("cannot find promise to reject");this._queue[r].reject(t),this._queue.splice(r,1)}async _MaybeStartNext(){if(!this._queue.length)return;if(this._activeCount>=this._maxParallel)return;this._activeCount++;const e=this._queue.shift();try{const t=await e.func();e.resolve(t)}catch(t){e.reject(t)}this._activeCount--,this._MaybeStartNext()}static async Batch(e,t){const r=[];let s=!1;const i=async e=>{let i;for(;i=t.pop();){if(s)return;try{r.push(await i())}catch(e){throw s=!0,e}}},n=[];for(;e--;)n.push(i());return await Promise.all(n),r}};
}

// ../lib/util/rateLimiter.js
{
const C3=self.C3;C3.RateLimiter=class{constructor(t,e,i){this._callback=t,this._interval=e,this._intervalOnBattery=i||2*e,this._timerId=-1,this._lastCallTime=-1/0,this._timerCallFunc=()=>this._OnTimer(),this._ignoreReset=!1,this._canRunImmediate=!1,this._callbackArguments=null}SetCanRunImmediate(t){this._canRunImmediate=!!t}_GetInterval(){return void 0!==C3.Battery&&C3.Battery.IsOnBatteryPower()?this._intervalOnBattery:this._interval}Call(...t){if(-1!==this._timerId)return;this._callbackArguments=t;let e=C3.FastGetDateNow(),i=e-this._lastCallTime,l=this._GetInterval();i>=l&&this._canRunImmediate?(this._lastCallTime=e,this._RunCallback()):this._timerId=self.setTimeout(this._timerCallFunc,Math.max(l-i,4))}_RunCallback(){this._ignoreReset=!0;const t=this._callbackArguments;this._callbackArguments=null,t?this._callback(...t):this._callback(),this._ignoreReset=!1}Reset(){this._ignoreReset||(this._CancelTimer(),this._callbackArguments=null,this._lastCallTime=C3.FastGetDateNow())}_OnTimer(){this._timerId=-1,this._lastCallTime=C3.FastGetDateNow(),this._RunCallback()}_CancelTimer(){-1!==this._timerId&&(self.clearTimeout(this._timerId),this._timerId=-1)}Release(){this._CancelTimer(),this._callback=null,this._callbackArguments=null,this._timerCallFunc=null}};
}

// ../lib/util/svgRaster/svgRasterManager.js
{
const C3=self.C3;C3.SVGRasterManager=class{constructor(){this._images=new Map,this._allowNpotSurfaces=!1,this._getBaseSizeCallback=null,this._rasterAtSizeCallback=null,this._releaseResultCallback=null,this._redrawCallback=null}SetNpotSurfaceAllowed(e){this._allowNpotSurfaces=!!e}IsNpotSurfaceAllowed(){return this._allowNpotSurfaces}SetGetBaseSizeCallback(e){this._getBaseSizeCallback=e}GetBaseSize(e){if(!this._getBaseSizeCallback)throw new Error("no get base size callback set");return this._getBaseSizeCallback(e)}SetRasterAtSizeCallback(e){this._rasterAtSizeCallback=e}RasterAtSize(e,a,t,l,s,r){if(!this._rasterAtSizeCallback)throw new Error("no raster at size callback set");return this._rasterAtSizeCallback(e,a,t,l,s,r)}SetReleaseResultCallback(e){this._releaseResultCallback=e}ReleaseResult(e){if(!this._releaseResultCallback)throw new Error("no release result callback set");this._releaseResultCallback(e)}SetRedrawCallback(e){this._redrawCallback=e}Redraw(){if(!this._redrawCallback)throw new Error("no redraw callback set");this._redrawCallback()}AddImage(e){let a=this._images.get(e);return a||(a=C3.New(C3.SVGRasterImage,this,e),this._images.set(e,a)),a.IncReference(),a}_RemoveImage(e){this._images.delete(e.GetDataSource())}OnTexturesChanged(){for(const e of this._images.values())e.ReleaseRasterizedResult(),e.ForceRasterAgain()}};
}

// ../lib/util/svgRaster/svgRasterImage.js
{
const C3=self.C3,MAX_SURFACE_SIZE=4096;C3.SVGRasterImage=class{constructor(e,t){this._manager=e,this._dataSource=t,this._refCount=0,this._baseWidth=0,this._baseHeight=0,this._getBaseSizePromise=this._manager.GetBaseSize(t).then((e=>{this._manager&&(this._baseWidth=e[0],this._baseHeight=e[1],this._manager.Redraw())})).catch((e=>{console.error("[SVG] Error loading SVG: ",e),this._hadError=!0,this._manager&&this._manager.Redraw()})),this._rasterSurfaceWidth=0,this._rasterSurfaceHeight=0,this._rasterImageWidth=0,this._rasterImageHeight=0,this._isRasterizing=!1,this._rasterizedResult=null,this._forceRaster=!1,this._hadError=!1}Release(){if(this._refCount<=0)throw new Error("already released");this._refCount--,0===this._refCount&&this._Release()}ReleaseRasterizedResult(){this._rasterizedResult&&(this._manager.ReleaseResult(this._rasterizedResult),this._rasterizedResult=null)}_Release(){this.ReleaseRasterizedResult(),this._manager._RemoveImage(this),this._manager=null}GetDataSource(){return this._dataSource}IncReference(){this._refCount++}HasReferences(){return this._refCount>0}GetRasterizedResult(){return this._rasterizedResult}ForceRasterAgain(){this._forceRaster=!0}async StartRasterForSize(e,t,r){if(0===t||0===r||this._hadError)return;if(this._isRasterizing)return;let s=C3.nextHighestPowerOfTwo(Math.ceil(t)),a=C3.nextHighestPowerOfTwo(Math.ceil(r));const i=Math.max(s,a);if(i>4096){const e=4096/i;t*=e,r*=e,s=Math.min(Math.ceil(s*e),4096),a=Math.min(Math.ceil(a*e),4096)}if(t<s&&r<a){const e=t/r;s/a>e?(t=a*e,r=a):(t=s,r=s/e)}if(this._manager.IsNpotSurfaceAllowed()&&(s=Math.ceil(t),a=Math.ceil(r)),s<=this._rasterSurfaceWidth&&a<=this._rasterSurfaceHeight&&!this._forceRaster)return;this._isRasterizing=!0,this._rasterSurfaceWidth=s,this._rasterSurfaceHeight=a;const h=await this._manager.RasterAtSize(this._dataSource,e,this._rasterSurfaceWidth,this._rasterSurfaceHeight,t,r);this._manager&&(this.ReleaseRasterizedResult(),this._rasterizedResult=h,this._rasterImageWidth=t,this._rasterImageHeight=r,this._isRasterizing=!1,this._forceRaster=!1,this._manager.Redraw())}WhenBaseSizeReady(){return this._getBaseSizePromise}GetBaseWidth(){return this._baseWidth}GetBaseHeight(){return this._baseHeight}GetRasterWidth(){return this._rasterImageWidth}GetRasterHeight(){return this._rasterImageHeight}HadError(){return this._hadError}};
}

// ../lib/str/str.js
{
const C3=self.C3;C3.UTF8_BOM="\ufeff";const NUMERIC_CHARS=new Set("0123456789");C3.IsNumericChar=function(t){return NUMERIC_CHARS.has(t)};const WHITESPACE_CHARS=new Set(" \t\n\r            ​\u2028\u2029  　");C3.IsWhitespaceChar=function(t){return WHITESPACE_CHARS.has(t)},C3.FilterWhitespace=function(t){return[...t].filter((t=>!C3.IsWhitespaceChar(t))).join("")},C3.IsStringAllWhitespace=function(t){for(const e of t)if(!C3.IsWhitespaceChar(e))return!1;return!0},C3.IsCharArrayAllWhitespace=function(t){for(const e of t)if(!C3.IsWhitespaceChar(e))return!1;return!0},C3.IsUnprintableChar=function(t){return 1===t.length&&t.charCodeAt(0)<32},C3.FilterUnprintableChars=function(t){return[...t].filter((t=>!C3.IsUnprintableChar(t))).join("")};let cjkPunctuationRegex=null;try{cjkPunctuationRegex=new RegExp("\\p{P}(?<=[\\u3000-\\u303F\\uFF00-\\uFFEF])","u")}catch(t){console.warn("Unable to detect CJK punctuation: ",t)}C3.IsCJKPunctuationChar=function(t){return!C3.IsWhitespaceChar(t)&&cjkPunctuationRegex&&cjkPunctuationRegex.test(t)};const NUMERIC_STRING_CHARS=new Set("0123456789.+-e");C3.IsStringNumber=function(t){if(!(t=t.trim()).length)return!1;let e=t.charAt(0);if("-"!==e&&!NUMERIC_CHARS.has(e))return!1;for(let e of t)if(!NUMERIC_STRING_CHARS.has(e))return!1;return!0},C3.RemoveTrailingDigits=function(t){let e=t.length;for(;e>0;){let n=t.charAt(e-1);if(!C3.IsNumericChar(n))break;--e}return t.substr(0,e)},C3.IncrementNumberAtEndOf=function(t){let e=C3.RemoveTrailingDigits(t),n=t.substr(e.length);return n=n?(parseInt(n,10)+1).toString():"2",e+n};const HTML_ENTITY_MAP=new Map([["&","&amp;"],["<","&lt;"],[">","&gt;"],['"',"&quot;"],["'","&#39;"]]);function lookupHtmlEntity(t){return HTML_ENTITY_MAP.get(t)}const HTML_ENTITY_REGEX=/[&<>"']/g;C3.EscapeHTML=function(t){return t.replace(HTML_ENTITY_REGEX,lookupHtmlEntity)},C3.EscapeJS=function(t){let e=C3.ReplaceAll(t,"\\","\\\\");return e=C3.ReplaceAll(e,'"','\\"'),e=C3.ReplaceAll(e,"\t","\\t"),e=C3.ReplaceAll(e,"\r",""),C3.ReplaceAll(e,"\n","\\n")},C3.EscapeXML=function(t){let e=C3.ReplaceAll(t,"&","&amp;");return e=C3.ReplaceAll(e,"<","&lt;"),e=C3.ReplaceAll(e,">","&gt;"),C3.ReplaceAll(e,'"',"&quot;")};const ESCAPE_REGEX=/[-[\]{}()*+?.,\\^$|#\s]/g;C3.EscapeRegex=function(t){return t.replace(ESCAPE_REGEX,"\\$&")},C3.CountCharsInString=function(t,e){let n=0;for(const r of t)r===e&&++n;return n},C3.StringPosToLineNumber=function(t,e){let n=0,r=0;for(;n<e;){if(n=t.indexOf("\n",n),-1===n)return r;r++,n++}return r},C3.FindAll=function(t,e,n=!1){if(!e)return[];n||(t=t.toLowerCase(),e=e.toLowerCase());const r=e.length;let o=0,i=0,l=[];for(;(i=t.indexOf(e,o))>-1;)l.push(i),o=i+r;return l},C3.ReplaceAll=function(t,e,n){return t.replaceAll(e,(()=>n))},C3.ReplaceAllCaseInsensitive=function(t,e,n){return t.replace(new RegExp(C3.EscapeRegex(e),"gi"),(()=>n))},C3.SetElementContent=function(t,e){"string"==typeof e?t.textContent=e:e.isPlainText()?t.textContent=e.toString():(t.innerHTML=e.toHTML(),e instanceof C3.BBString&&e.attachLinkHandlers(t))},C3.StringLikeEquals=function(t,e){return t instanceof C3.HtmlString||t instanceof C3.BBString?t.equals(e):e instanceof C3.HtmlString||e instanceof C3.BBString?e.equals(t):t===e},C3.StringSubstitute=function(t,...e){let n=t;for(let r=0,o=e.length;r<o;++r){const o=`{${r}}`;if(!t.includes(o))throw new Error(`missing placeholder '${o}' in string substitution`);n=n.replace(o,e[r].toString())}return n},C3.StringSubstituteAllowMissing=function(t,...e){let n=t,r=-1,o=-1;for(let i=0,l=e.length;i<l;++i){const l=`{${i}}`;t.includes(l)?(o=i,n=n.replace(l,e[i].toString())):-1===r&&(r=i)}if(r>=0&&o>=0&&r<o)throw new Error(`missing placeholder '${r}' in string substitution`);return n},C3.StringSubstituteMap=function(t,e){let n=t;for(let[t,r]of Object.entries(e))n=n.replaceAll(t,r.toString());return n},C3.SortAZ=function(t,e){return t>e?1:t<e?-1:0},C3.SortAZCaseInsensitive=function(t,e){let n=t.toLowerCase(),r=e.toLowerCase();return n>r?1:n<r?-1:0};const intlSegmenter=new self["Intl"]["Segmenter"];C3.SplitGraphemes=function(t){const e=[];for(const n of intlSegmenter["segment"](t))e.push(n["segment"]);return e},C3.IterateGraphemes=function*(t){for(const e of intlSegmenter["segment"](t))yield e["segment"]},C3.CountGraphemes=function(t){let e=0;for(const n of intlSegmenter["segment"](t))++e;return e};const KILOBYTE=1024,MEGABYTE=1048576,GIGABYTE=1073741824,TERABYTE=1099511627776;C3.FormatDataSize=function(t,e){let n="common."+(e?"dataRates":"dataSizes")+".";const r=self.langSub;if(t<1024)return r(n+"bytes",t);if(t<1048576){let e=t/1024;return e=e<10?Math.round(10*e)/10:Math.round(e),r(n+"kilobytes",e)}if(t<GIGABYTE){let e=t/1048576;return e=e<10?Math.round(10*e)/10:Math.round(e),r(n+"megabytes",e)}if(t<TERABYTE){let e=t/GIGABYTE;return e=e<10?Math.round(10*e)/10:Math.round(e),r(n+"gigabytes",e)}{let e=t/TERABYTE;return e=e<10?Math.round(10*e)/10:Math.round(e),r(n+"terabytes",e)}};const DEFAULT_FORMATTIME_OPTS={approximate:!1,days:!0,hours:!0,minutes:!0,seconds:!0};C3.FormatTime=function(t,e){e=Object.assign({},DEFAULT_FORMATTIME_OPTS,e),C3.Lang.PushContext("common.time");const n=[],r=self.lang,o=self.langPluralSub;if(e.days){const e=Math.floor(t/86400);e>0&&(t-=24*e*3600,n.push(o(".days",null,e)))}if(e.hours){const e=Math.floor(t/3600);(e>0||n.length)&&(t-=3600*e,n.push(o(".hours",null,e)))}if(e.minutes){const r=Math.floor(t/60);(r>0||n.length||!e.seconds)&&(t-=60*r,n.push(o(".minutes",null,r)))}if(e.seconds){const e=Math.floor(t%60);n.push(o(".seconds",null,e))}const i=(e.approximate?r(".approx-prefix"):"")+n.join(r(".separator"));return C3.Lang.PopContext(),i},C3.ZeroPad=function(t,e){let n=t<0?"-":"",r=(t=Math.abs(t)).toString(),o=e-r.length;for(let t=0;t<o;++t)n+="0";return n+r},C3.StringToTitleCase=function(t){return t.toLowerCase().replace(/\b\w/g,(t=>t.toUpperCase()))},C3.CompareVersionStrings=function(t,e){let n=t.split(".").map((t=>t.trim())),r=e.split(".").map((t=>t.trim()));C3.resizeArray(n,4,"0"),C3.resizeArray(r,4,"0"),n=n.map((t=>parseInt(t,10))),r=r.map((t=>parseInt(t,10)));for(let t=0;t<4;++t){const e=n[t]-r[t];if(0!==e)return e<0?-1:1}return 0},C3.CreateGUID=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const e=Math.floor(16*Math.random());return("x"===t?e:3&e|8).toString(16)}))},C3.StringHammingDistance=function(t,e){if(t.length!==e.length)throw new Error("strings must be same length");let n=0;for(let r=0,o=t.length;r<o;++r)t.charAt(r)!==e.charAt(r)&&++n;return n},C3.StringLevenshteinDistance=function(t,e){if(0===t.length)return e.length;if(0===e.length)return t.length;let n,r,o,i,l,s;for(t.length>e.length&&(n=t,t=e,e=n),s=Array(t.length+1),r=0;r<=t.length;r++)s[r]=r;for(r=1;r<=e.length;r++){for(i=r,o=1;o<=t.length;o++)l=e[r-1]===t[o-1]?s[o-1]:Math.min(s[o-1]+1,Math.min(i+1,s[o]+1)),s[o-1]=i,i=l;s[t.length]=i}return s[t.length]};
}

// ../lib/str/bbstring.js
{
const C3=self.C3,assert=self.assert,BB_CODE_MAP=new Map([["b","strong"],["i","em"],["s","s"],["u","u"],["sub","sub"],["sup","sup"],["small","small"],["mark","mark"],["code","code"],["a1","a"],["a2","a"],["a3","a"],["a4","a"],["a5","a"],["a6","a"],["a7","a"],["a8","a"],["a9","a"],["tip1","abbr"],["tip2","abbr"],["tip3","abbr"],["tip4","abbr"],["tip5","abbr"],["tip6","abbr"],["tip7","abbr"],["tip8","abbr"],["tip9","abbr"],["bad",["span","bbCodeBad"]],["good",["span","bbCodeGood"]],["info",["span","bbCodeInfo"]],["h1",["span","bbCodeH1"]],["h2",["span","bbCodeH2"]],["h3",["span","bbCodeH3"]],["h4",["span","bbCodeH4"]],["item",["span","bbCodeItem"]]]),SELF_CLOSING_TAGS=new Set(["icon"]),BBREGEX=/\[(\/?)([a-zA-Z0-9]+)\]/g,CUSTOM_BBREGEX=/\[(\/?)([^\[\n]*?)\]/g;let linkActions=null,tipList=null,classIndex=0;function bbToHtmlReplacerFunc(t,s,i){const n=BB_CODE_MAP.get(i);if(!n)return"class"===i?s?"</span>":`<span class="bbclass${classIndex++}">`:t;if("string"==typeof n){if("a"===n&&0===linkActions.length||"abbr"===n&&0===tipList.length)return t;if("a"!==n||s){if("abbr"!==n||s)return"<"+s+n+">";{const t=parseInt(i.substring(3),10)-1;if(t<0||t>=tipList.length)throw new Error("invalid bbcode tip substitution");const s=tipList[t];let n="";if("string"==typeof s?n=s:"function"==typeof s&&(n=s()),"string"!=typeof n)throw new TypeError("invalid bbcode tip");return`<abbr title="${C3.ReplaceAll(n,'"',"&quot;")}">`}}{const t=parseInt(i.substring(1),10)-1;if(t<0||t>=linkActions.length)throw new Error("invalid bbcode link substitution");const s=linkActions[t];if("string"==typeof s)return`<a href="${linkActions[t]}">`;if("function"==typeof s)return`<a class="bblink${t}">`;throw new TypeError("invalid bbcode link action")}}if(Array.isArray(n)){let t=n[0],i=n[1];return s?"</"+t+">":`<${t} class="${i}">`}}const LINEBREAK_REGEX=/\n/g;C3.BBString=class{constructor(t,s){if(this._bbstr=s&&s.noEscape?t:C3.EscapeHTML(t),this._htmlstr="",this._convertLineBreaks=!1,this._linkActions=[],this._tipList=[],s){if(this._convertLineBreaks=!!s.convertLineBreaks,s.links){if(s.links.length>9)throw new Error("too many links");this._linkActions=s.links}if(s.tips){if(s.tips.length>9)throw new Error("too many tips");this._tipList=s.tips}}this._hasAnyBBtags=this._bbstr.includes("["),this._needsLineBreakConversion=this._convertLineBreaks&&this._bbstr.includes("\n"),this._isPlain=!this._hasAnyBBtags&&!this._needsLineBreakConversion&&!this._bbstr.includes("&"),this._hasParsedFragments=!1,this._fragments=[]}toString(){return this._bbstr}valueOf(){return this._bbstr}isPlainText(){return this._isPlain}toPlainText(){return this._hasAnyBBtags?this._bbstr.replace(BBREGEX,""):this._bbstr}toHTML(){if(this._isPlain)return this._bbstr;if(!this._htmlstr&&this._bbstr){let t=this._bbstr;this._hasAnyBBtags&&(classIndex=0,linkActions=this._linkActions,tipList=this._tipList,t=t.replace(BBREGEX,bbToHtmlReplacerFunc),linkActions=null,tipList=null),this._needsLineBreakConversion&&(t=t.replace(LINEBREAK_REGEX,"<br>")),this._htmlstr=t}return this._htmlstr}attachLinkHandlers(t){if(this._linkActions.length)for(let s=0,i=this._linkActions.length;s<i;++s){const i=this._linkActions[s];if("function"!=typeof i)continue;const n=t.querySelector(".bblink"+s);if(!n)throw new Error("unable to attach BBString link handler");n.onclick=i}}equals(t){return t instanceof C3.HtmlString?this.toHTML()===t.toHTML():t instanceof C3.BBString?this._bbstr===t._bbstr:this._bbstr===t}toFragmentList(){if(this._hasParsedFragments)return this._fragments;const t=[],s=this._bbstr,i=[];CUSTOM_BBREGEX.lastIndex=0;let n=0,e=null;for(;null!==(e=CUSTOM_BBREGEX.exec(s));){const r=e.index;if(r>0&&"\\"===s.charAt(r-1))continue;const a=e[0],o=e[1],l=e[2],b=s.substring(n,r);if(n=r+a.length,b&&t.push({text:b,styles:i.slice(0)}),l)if(o){const t=l.toLowerCase();for(let s=i.length-1;s>=0;--s)if(i[s].tag===t){i.splice(s,1);break}}else{let s=l,n=null;const e=l.indexOf("=");if(-1!==e?(s=l.substring(0,e).toLowerCase(),n=l.substring(e+1)):s=s.toLowerCase(),SELF_CLOSING_TAGS.has(s)){if("icon"!==s)throw new Error(`unknown self-closing tag ${s}`);t.push({icon:n,styles:i.slice(0)})}else i.push({tag:s,param:n})}}n<s.length&&t.push({text:s.substring(n),styles:i.slice(0)});for(const s of t)s.text&&(s.text=this._ProcessBBCodeEscapeSequences(s.text));return this._fragments=t.map((t=>t.icon?C3.New(C3.IconFragment,{icon:t.icon,styles:t.styles}):C3.New(C3.TextFragment,{chArr:C3.SplitGraphemes(t.text),styles:t.styles}))),this._hasParsedFragments=!0,this._fragments}_ProcessBBCodeEscapeSequences(t){return t=C3.ReplaceAll(t,"\\[","["),C3.ReplaceAll(t,"\\\\","\\")}static StripTags(t){return C3.New(C3.BBString,t,{noEscape:!0}).toPlainText()}static StripAnyTags(t){return t.replace(CUSTOM_BBREGEX,"")}};
}

// ../lib/str/textLayout/wordWrap.js
{
const C3=self.C3;function IsWordBreakWhiteSpace(t){return" "!==t&&" "!==t&&C3.IsWhitespaceChar(t)}const CJK_OPEN_PUNCTUATION=new Set("〈《「『【〔〖〘〚〝");function IsOpeningCJKPunctiationChar(t){return CJK_OPEN_PUNCTUATION.has(t)}function IsContinuingCJKPunctuationChar(t){return C3.IsCJKPunctuationChar(t)&&!IsOpeningCJKPunctiationChar(t)}function WordBreakTrimEnd(t){for(;t.length>0&&IsWordBreakWhiteSpace(t.at(-1));)t.pop()}function IsNewline(t){return"\n"===t||"\r\n"===t}C3.WordWrap=class{constructor(){this._lines=[],this._iconSet=null}GetLines(){return this._lines}GetLineCount(){return this._lines.length}SetIconSet(t){this._iconSet=t}_MeasureLine(t,e){let n=0,s=0,i=0,o=0,r=0;for(const h of t){if(-1===h.GetWidth()){const t=e(h);h.SetHeight(t.height),h.SetFontBoundingBoxAscent(t.fontBoundingBoxAscent||0),h.SetFontBoundingBoxDescent(t.fontBoundingBoxDescent||0),h.SetTopToAlphabeticDistance(t.topToAlphabeticDistance||0),h.IsText()?h.SetWidth(t.width):h.IsIcon()&&h.CalculateWidthFromHeight(this._iconSet)}n+=h.GetWidth(),s=Math.max(s,h.GetHeight()),i=Math.max(i,h.GetFontBoundingBoxAscent()),o=Math.max(o,h.GetFontBoundingBoxDescent()),r=Math.max(r,h.GetTopToAlphabeticDistance())}return{width:n,height:s,fontBoundingBoxAscent:i,fontBoundingBoxDescent:o,topToAlphabeticDistance:r}}_AddLine(t,e,n,s,i,o){this._lines.push(C3.New(C3.WordWrap.Line,{fragments:t,width:e,height:n,fontBoundingBoxAscent:s,fontBoundingBoxDescent:i,topToAlphabeticDistance:o}))}WordWrap(t,e,n,s,i){if("string"==typeof t&&(t=[C3.New(C3.TextFragment,{chArr:C3.SplitGraphemes(t)})]),C3.clearArray(this._lines),!t.length||1===t.length&&t[0].IsText()&&t[0].IsEmpty()||n<2)return;if(1===t.length){const s=t[0];if(s.IsText()&&s.GetLength()<=100&&!s.HasNewLine()){let{width:t,height:o,fontBoundingBoxAscent:r,fontBoundingBoxDescent:h,topToAlphabeticDistance:a}=e(s);if(t+=i,s.SetWidth(t),s.SetHeight(o),s.SetFontBoundingBoxAscent(r||0),s.SetFontBoundingBoxDescent(h||0),s.SetTopToAlphabeticDistance(a||0),t<=n)return void this._AddLine([s],t,o,r,h,a)}}let o;o="word"===s?this._TokeniseByWord(t):"cjk"===s?this._TokeniseByCJK(t):this._TokeniseByChar(t),this._WrapText(o,e,n,i)}_TokeniseByWord(t){const e=[];let n=[],s=!1;for(const i of t){const t=i.GetStyles();if(i.IsIcon())n.length>0&&e.push(n),e.push([i]),n=[];else for(const o of i.GetCharacterArray())if(IsNewline(o))n.length>0&&e.push(n),e.push([C3.New(C3.TextFragment,{chArr:["\n"],styles:t})]),n=[];else if(0===n.length)n.push(C3.New(C3.TextFragment,{chArr:[o],styles:t})),s=IsWordBreakWhiteSpace(o);else{const i=IsWordBreakWhiteSpace(o);if(i===s){const e=n.at(-1);e.GetStyles()===t?e._AppendChar(o):n.push(C3.New(C3.TextFragment,{chArr:[o],styles:t}))}else e.push(n),n=[C3.New(C3.TextFragment,{chArr:[o],styles:t})],s=i}}return n.length>0&&e.push(n),e}_TokeniseByCJK(t){const e=[];let n=[],s=!1;for(const i of t){const t=i.GetStyles();if(i.IsIcon())n.length>0&&e.push(n),e.push([i]),n=[];else for(const o of i.GetCharacterArray())if(IsNewline(o))n.length>0&&e.push(n),e.push([C3.New(C3.TextFragment,{chArr:["\n"],styles:t})]),n=[];else if(0===n.length)n.push(C3.New(C3.TextFragment,{chArr:[o],styles:t})),s=IsOpeningCJKPunctiationChar(o);else if(s||IsContinuingCJKPunctuationChar(o)){const e=n.at(-1);e.GetStyles()===t?e._AppendChar(o):n.push(C3.New(C3.TextFragment,{chArr:[o],styles:t})),s=IsOpeningCJKPunctiationChar(o)}else e.push(n),n=[C3.New(C3.TextFragment,{chArr:[o],styles:t})],s=IsOpeningCJKPunctiationChar(o)}return n.length>0&&e.push(n),e}_TokeniseByChar(t){const e=[];for(const n of t)if(n.IsText()){const t=n.GetCharacterArray();C3.appendArray(e,t.map((t=>[C3.New(C3.TextFragment,{chArr:[t],styles:n.GetStyles()})])))}else e.push([n]);return e}_CopyLine(t){return t.map((t=>t._Clone()))}_AddWordToLine(t,e){const n=t.length?t.at(-1):null;let s=0;n&&n.IsText()&&e[0].IsText()&&e[0].GetStyles()===n.GetStyles()&&(n._Append(e[0].GetCharacterArray()),s=1);for(let n=e.length;s<n;++s){const n=e[s];t.push(n._Clone())}}_WrapText(t,e,n,s){let i=[],o=0,r=0,h=0,a=0,c=0;for(const s of t){if(1===s.length&&s[0].IsText()&&1===s[0].GetLength()&&IsNewline(s[0].GetCharacterArray()[0])){if(0===r){const t=e(C3.New(C3.TextFragment,{chArr:[" "],styles:s[0].GetStyles()}));r=t.height,h=t.fontBoundingBoxAscent||0,a=t.fontBoundingBoxDescent||0,c=t.topToAlphabeticDistance||0}this._AddLine(i,o,r,h,a,c),i=[],o=0,r=0,h=0,a=0,c=0;continue}const t=this._CopyLine(i);this._AddWordToLine(t,s);const l=this._MeasureLine(t,e),u=l.width;if(u>=n)if(i.length>0&&this._AddLine(i,o,r,h,a,c),i=[],s[0].IsText()&&C3.IsCharArrayAllWhitespace(s[0].GetCharacterArray()))o=0,r=0,h=0,a=0,c=0;else{this._AddWordToLine(i,s);const t=this._MeasureLine(i,e);o=t.width,r=t.height,h=t.fontBoundingBoxAscent,a=t.fontBoundingBoxDescent,c=t.topToAlphabeticDistance}else i=t,o=u,r=l.height,h=l.fontBoundingBoxAscent,a=l.fontBoundingBoxDescent,c=l.topToAlphabeticDistance}i.length>0&&this._AddLine(i,o,r,h,a,c),this._TrimLinesTrailingWhitespace(e,s)}_TrimLinesTrailingWhitespace(t,e){for(const n of this._lines){const s=n._GetFragmentsArray();if(!s.length)continue;let i=s.at(-1);if(i.IsText()){const o=i.GetCharacterArray(),r=o.slice(0);if(WordBreakTrimEnd(r),0===r.length)n.OffsetWidth(-i.GetWidth()),s.pop();else if(r.length<o.length){i.SetCharacterArray(r);const e=t(i).width,s=i.GetWidth()-e;i.SetWidth(e),n.OffsetWidth(-s)}0!==e&&s.length>0&&(i=s.at(-1),i.OffsetWidth(e),n.OffsetWidth(e))}}}Clear(){C3.clearArray(this._lines)}GetMaxLineWidth(){return this._lines.reduce(((t,e)=>Math.max(t,e.GetWidth())),0)}GetTotalLineHeight(){return this._lines.reduce(((t,e)=>t+e.GetHeight()),0)}};
}

// ../lib/str/textLayout/line.js
{
const C3=self.C3;C3.WordWrap.Line=class{constructor(t){this._fragments=t.fragments||[],this._width=t.width||-1,this._height=t.height||-1,this._fontBoundingBoxAscent=t.fontBoundingBoxAscent||-1,this._fontBoundingBoxDescent=t.fontBoundingBoxDescent||-1,this._topToAlphabeticDistance=t.topToAlphabeticDistance||-1,this._posX=0,this._posY=0}fragments(){return this._fragments.values()}*fragmentsReverse(){const t=this._fragments;for(let e=t.length-1;e>=0;--e)yield t[e]}_GetFragmentsArray(){return this._fragments}OffsetWidth(t){this._width+=t}GetWidth(){return this._width}GetHeight(){return this._height}GetFoundBoundingBoxAscent(){return this._fontBoundingBoxAscent}GetFontBoundingBoxDescent(){return this._fontBoundingBoxDescent}GetTopToAlphabeticDistance(){return this._topToAlphabeticDistance}SetPosX(t){this._posX=t}GetPosX(){return this._posX}SetPosY(t){this._posY=t}GetPosY(){return this._posY}};
}

// ../lib/str/textLayout/fragmentBase.js
{
const C3=self.C3;C3.FragmentBase=class{constructor(t){this._styles=t.styles||[],this._width=t.width||-1,this._height=t.height||-1,this._fontBoundingBoxAscent=t.fontBoundingBoxAscent||-1,this._fontBoundingBoxDescent=t.fontBoundingBoxDescent||-1,this._topToAlphabeticDistance=t.topToAlphabeticDistance||-1,this._posX=0,this._posY=0}IsText(){return!1}IsIcon(){return!1}GetStyles(){return this._styles}GetStyleTag(t){const e=this._styles;for(let s=e.length-1;s>=0;--s){const n=e[s];if(n.tag===t)return n}return null}HasStyleTag(t){return!!this.GetStyleTag(t)}GetStyleMap(){const t=new Map;for(const e of this._styles)t.set(e.tag,e.param);return t}OffsetWidth(t){this._width+=t}SetWidth(t){this._width=t}GetWidth(){return this._width}SetHeight(t){this._height=t}GetHeight(){return this._height}SetFontBoundingBoxAscent(t){this._fontBoundingBoxAscent=t}GetFontBoundingBoxAscent(){return this._fontBoundingBoxAscent}SetFontBoundingBoxDescent(t){this._fontBoundingBoxDescent=t}GetFontBoundingBoxDescent(){return this._fontBoundingBoxDescent}SetTopToAlphabeticDistance(t){this._topToAlphabeticDistance=t}GetTopToAlphabeticDistance(){return this._topToAlphabeticDistance}SetPosX(t){this._posX=t}GetPosX(){return this._posX}SetPosY(t){this._posY=t}GetPosY(){return this._posY}};
}

// ../lib/str/textLayout/textFragment.js
{
const C3=self.C3;C3.TextFragment=class extends C3.FragmentBase{constructor(t){super(t),this._chArr=t.chArr}IsText(){return!0}_Append(t){C3.appendArray(this._chArr,t),this._width=-1,this._height=-1,this._fontBoundingBoxAscent=-1,this._fontBoundingBoxDescent=-1,this._topToAlphabeticDistance=-1}_AppendChar(t){this._chArr.push(t)}_Clone(){return C3.New(C3.TextFragment,{chArr:this._chArr.slice(0),styles:this._styles,width:this._width,height:this._height,fontBoundingBoxAscent:this._fontBoundingBoxAscent,fontBoundingBoxDescent:this._fontBoundingBoxDescent,topToAlphabeticDistance:this._topToAlphabeticDistance})}GetCharacterArray(){return this._chArr}SetCharacterArray(t){this._chArr=t}GetLength(){return this._chArr.length}IsEmpty(){return 0===this._chArr.length}HasNewLine(){return this._chArr.includes("\n")}};
}

// ../lib/str/textLayout/iconFragment.js
{
const C3=self.C3;C3.IconFragment=class extends C3.FragmentBase{constructor(t){super(t),this._icon=t.icon}IsIcon(){return!0}GetIconParameter(){return this._icon}_Clone(){return C3.New(C3.IconFragment,{icon:this._icon,styles:this._styles,width:this._width,height:this._height,fontBoundingBoxAscent:this._fontBoundingBoxAscent,fontBoundingBoxDescent:this._fontBoundingBoxDescent,topToAlphabeticDistance:this._topToAlphabeticDistance})}GetTextIcon(t){if(!t)return null;let e=Number(this._icon);return String(e)===this._icon?(e=Math.floor(e),t.GetTextIconByIndex(e)):t.GetTextIconByTag(this._icon)}CalculateWidthFromHeight(t){const e=this.GetTextIcon(t);this._width=e?this._height*e.GetWidth()/e.GetHeight():0}GetDrawable(t){const e=this.GetTextIcon(t);return e?e.GetDrawable():null}GetLength(){return 1}};
}

// ../lib/str/textLayout/textIconManager.js
{
const C3=self.C3;C3.TextIconManager=class{constructor(t){this._iconSets=new Map,this._getIconSetMetaCallback=t.getIconSetMeta,this._getIconSetContentCallback=t.getIconSetContent}Release(){for(const t of this._iconSets.values())t.Release();this._iconSets.clear()}GetIconSet(t){let e=this._iconSets.get(t);if(e)return e;const n=this._getIconSetMetaCallback(t);return e=C3.New(C3.TextIconSet,this,{source:t,iconMeta:n}),this._iconSets.set(t,e),e}HasIconSet(t){return this._iconSets.has(t)}DeleteIconSet(t){const e=this._iconSets.get(t);e&&e.Release(),this._iconSets.delete(t)}async _GetIconSetContent(t){return await this._getIconSetContentCallback(t)}};
}

// ../lib/str/textLayout/textIconSet.js
{
const C3=self.C3;C3.TextIconSet=class{constructor(t,s){this._textIconManager=t,this._source=s.source,this._iconsArray=[],this._iconsByTag=new Map,this._hasStartedLoad=!1,this._isLoading=!1,this._loadPromise=null;const o=s.iconMeta.icons;for(let t=0,s=o.length;t<s;++t){const s=o[t],e=C3.New(C3.TextIcon,this,{index:t,tag:s.tag,source:s.source,width:s.width,height:s.height});this._iconsArray.push(e),s.tag&&this._iconsByTag.set(s.tag.toLowerCase(),e)}}Release(){for(const t of this._iconsArray)t.Release();C3.clearArray(this._iconsArray),this._iconsByTag.clear(),this._textIconManager=null,this._source=null}HasLoaded(){return this._hasStartedLoad}IsLoading(){return this._isLoading}LoadContent(){return this._loadPromise||(this._loadPromise=this._DoLoadContent()),this._loadPromise}async _DoLoadContent(){if(this._hasStartedLoad)return;this._hasStartedLoad=!0,this._isLoading=!0;const t=await this._textIconManager._GetIconSetContent(this._source);if(!this._textIconManager)return;const s=t.icons;for(let t=0,o=Math.min(s.length,this._iconsArray.length);t<o;++t){const o=s[t].drawable;this._iconsArray[t]._SetDrawable(o)}this._isLoading=!1}GetTextIconByIndex(t){return(t=Math.floor(t))<0||t>=this._iconsArray.length?null:this._iconsArray[t]}GetTextIconByTag(t){return this._iconsByTag.get(t.toLowerCase())||null}};
}

// ../lib/str/textLayout/textIcon.js
{
const C3=self.C3;C3.TextIcon=class{constructor(t,e){this._textIconSet=t,this._source=e.source||null,this._index=e.index,this._tag=e.tag,this._width=e.width,this._height=e.height,this._drawable=null}Release(){this._width=0,this._height=0,this._textIconSet=null}GetSource(){return this._source}GetWidth(){return this._width}GetHeight(){return this._height}_SetDrawable(t){this._drawable=t}GetDrawable(){return this._drawable}};
}

// ../lib/gfx/gfx.js
{
const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,mat4=glMatrix.mat4,tempVec3a=vec3.create(),tempVec3b=vec3.create(),tempVec3c=vec3.create(),tempVec4=vec4.create(),tempMat4=mat4.create(),neartl=vec3.create(),neartr=vec3.create(),nearbl=vec3.create(),nearbr=vec3.create(),fartl=vec3.create(),fartr=vec3.create(),farbl=vec3.create(),farbr=vec3.create(),unitViewport=vec4.fromValues(0,0,1,1);function PlaneFromPoints(t,e,r,n){const a=tempVec3c;vec3.subtract(tempVec3a,r,e),vec3.subtract(tempVec3b,t,e),vec3.cross(a,tempVec3a,tempVec3b),vec3.normalize(a,a),n.set(a[0],a[1],a[2],vec3.dot(t,a))}function IsInFrontOfPlane(t,e,r,n,a,c,s){const o=s.x,i=s.y,l=s.z,f=s.w,P=s.xF,h=s.yF,m=s.zF,p=1-P,v=1-h,u=1-m;if(o*t*P+o*n*p+i*e*h+i*a*v+l*r*m+l*c*u>=f)return!0;return o*n*P+o*t*p+i*a*h+i*e*v+l*c*m+l*r*u>f}function IsPointInFrontOfPlane(t,e,r,n){return n.x*t+n.y*e+n.z*r>=n.w}C3.Gfx={Project(t,e,r,n,a,c,s){const o=n[0]*t+n[4]*e+n[8]*r+n[12],i=n[1]*t+n[5]*e+n[9]*r+n[13],l=n[2]*t+n[6]*e+n[10]*r+n[14],f=n[3]*t+n[7]*e+n[11]*r+n[15];let P=a[0]*o+a[4]*i+a[8]*l+a[12]*f,h=a[1]*o+a[5]*i+a[9]*l+a[13]*f,m=a[2]*o+a[6]*i+a[10]*l+a[14]*f,p=a[3]*o+a[7]*i+a[11]*l+a[15]*f;return 0!==p&&(p=1/p,P*=p,h*=p,m*=p,s[0]=(.5*P+.5)*c[2]+c[0],s[1]=(.5*h+.5)*c[3]+c[1],s[2]=.5*(1+m),!0)},Unproject(t,e,r,n,a,c,s){const o=tempMat4,i=tempVec4;return mat4.multiply(o,a,n),null!==mat4.invert(o,o)&&(i[0]=(t-c[0])/c[2]*2-1,i[1]=(e-c[1])/c[3]*2-1,i[2]=2*r-1,i[3]=1,vec4.transformMat4(i,i,o),0!==i[3]&&(i[3]=1/i[3],s[0]=i[0]*i[3],s[1]=i[1]*i[3],s[2]=i[2]*i[3],!0))},UnprojectScreenToWorldZ(t,e,r,n,a,c,s){const o=tempVec3a,i=tempVec3b;if(!C3.Gfx.Unproject(t,e,0,n,a,c,o))return!1;if(!C3.Gfx.Unproject(t,e,1,n,a,c,i))return!1;const l=tempVec3b;vec3.subtract(l,i,o);const f=tempVec3c;vec3.set(f,0,0,1);const P=-r,h=vec3.dot(f,l);let m=0;if(0===h){if(0!==vec3.dot(f,o)+P)return!1}else if(m=-(vec3.dot(o,f)+P)/h,m<0)return!1;return vec3.scaleAndAdd(s,o,l,m),!0}};class Plane{constructor(){this.x=NaN,this.y=NaN,this.z=NaN,this.w=NaN,this.xF=NaN,this.yF=NaN,this.zF=NaN}set(t,e,r,n){this.x=t,this.y=e,this.z=r,this.w=n,this.xF=t>0?1:0,this.yF=e>0?1:0,this.zF=r>0?1:0}}C3.Gfx.ViewFrustum=class{constructor(){this._leftP=new Plane,this._topP=new Plane,this._rightP=new Plane,this._bottomP=new Plane,this._nearP=new Plane,this._farP=new Plane}CalculatePlanes(t,e){const r=unitViewport;C3.Gfx.Unproject(0,1,0,t,e,r,neartl),C3.Gfx.Unproject(1,1,0,t,e,r,neartr),C3.Gfx.Unproject(0,0,0,t,e,r,nearbl),C3.Gfx.Unproject(1,0,0,t,e,r,nearbr),C3.Gfx.Unproject(0,1,1,t,e,r,fartl),C3.Gfx.Unproject(1,1,1,t,e,r,fartr),C3.Gfx.Unproject(0,0,1,t,e,r,farbl),C3.Gfx.Unproject(1,0,1,t,e,r,farbr),PlaneFromPoints(nearbl,neartl,fartl,this._leftP),PlaneFromPoints(neartl,neartr,fartr,this._topP),PlaneFromPoints(neartr,nearbr,farbr,this._rightP),PlaneFromPoints(nearbr,nearbl,farbl,this._bottomP),PlaneFromPoints(farbl,fartl,fartr,this._farP),PlaneFromPoints(nearbr,neartr,neartl,this._nearP)}ContainsAABB(t,e,r,n,a,c){return IsInFrontOfPlane(t,e,r,n,a,c,this._leftP)&&IsInFrontOfPlane(t,e,r,n,a,c,this._topP)&&IsInFrontOfPlane(t,e,r,n,a,c,this._rightP)&&IsInFrontOfPlane(t,e,r,n,a,c,this._bottomP)&&IsInFrontOfPlane(t,e,r,n,a,c,this._nearP)&&IsInFrontOfPlane(t,e,r,n,a,c,this._farP)}IsBehindNearPlane(t,e,r){return!IsPointInFrontOfPlane(t,e,r,this._nearP)}};
}

// ../lib/gfx/rendererBase.js
{
const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,mat4=glMatrix.mat4,tempMat4=mat4.create(),tmpVec3a=vec3.fromValues(0,0,0),tmpVec3b=vec3.fromValues(0,0,0),tmpVec3c=vec3.fromValues(0,0,0),defaultUpVector=vec3.fromValues(0,1,0),tmpVec4=vec4.fromValues(0,0,0,0),tmpQuad=new C3.Quad,tmpRect=new C3.Rect,defaultTexCoordsQuad=new C3.Quad(0,0,1,0,1,1,0,1),DEFAULT_RENDERERBASE_OPTS={nearZ:1,farZ:1e4},matWebGLtoWebGPU=mat4.fromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);C3.Gfx.RendererBase=class{constructor(e){e=Object.assign({},DEFAULT_RENDERERBASE_OPTS,e),this._width=0,this._height=0,this._fovY=C3.toRadians(45),this._tan_fovY_2=Math.tan(this._fovY/2),this._matP=mat4.create(),this._matMV=mat4.create(),this._zAxisScale=!1,this._nearZ=e.nearZ,this._farZ=e.farZ,this._allShaderPrograms=[],this._shaderProgramsByName=new Map,this._spTextureFill=null,this._spPoints=null,this._spTilemapFill=null,this._spTileRandomization=null,this._spColorFill=null,this._spLinearGradientFill=null,this._spPenumbraFill=null,this._spHardEllipseFill=null,this._spHardEllipseOutline=null,this._spSmoothEllipseFill=null,this._spSmoothEllipseOutline=null,this._spSmoothLineFill=null,this._stateGroups=new Map,this._currentStateGroup=null,this._blendModeTable=[],this._namedBlendModeMap=new Map,this._baseZ=0,this._currentZ=0,this._lineWidth=1,this._lineWidthStack=[this._lineWidth],this._lineCap=1,this._lineCapStack=[this._lineCap],this._lineOffset=.5,this._lineOffsetStack=[this._lineOffset],this._frameNumber=0,this._enableMipmaps=!0,this._hasMajorPerformanceCaveat=!1}FillIndexBufferData(e){let t=0,i=e.length,a=0;for(;t<i;)e[t++]=a,e[t++]=a+1,e[t++]=a+2,e[t++]=a,e[t++]=a+2,e[t++]=a+3,a+=4}_ClearState(){this._baseZ=0,this._currentZ=0,this._spTextureFill=null,this._spPoints=null,this._spTilemapFill=null,this._spTileRandomization=null,this._spColorFill=null,this._spLinearGradientFill=null,this._spPenumbraFill=null,this._spHardEllipseFill=null,this._spHardEllipseOutline=null,this._spSmoothEllipseFill=null,this._spSmoothEllipseOutline=null,this._spSmoothLineFill=null,this._ClearAllShaderPrograms()}InitState(){this._ClearState(),this._currentStateGroup=null}OnDeviceOrContextLost(){for(const e of this._allShaderPrograms)e.Release();this._ClearState()}GetWidth(){return this._width}GetHeight(){return this._height}GetDefaultCameraZ(e){return this.IsZAxisScaleNormalized()?100:e/(2*this._GetTanFovYDiv2())}GetZAxisScaleFactor(e){if(this.IsZAxisScaleNormalized()){return e/(2*this._GetTanFovYDiv2())/this.GetDefaultCameraZ(e)}return 1}SetNearZ(e){this._nearZ=e}GetNearZ(){return this._nearZ}SetFarZ(e){this._farZ=e}GetFarZ(){return this._farZ}SetFovY(e){this._fovY=e,this._tan_fovY_2=Math.tan(this._fovY/2)}GetFovY(){return this._fovY}_GetTanFovYDiv2(){return this._tan_fovY_2}SetZAxisScaleNormalized(){this._zAxisScale=!1}SetZAxisScaleRegular(){this._zAxisScale=!0}IsZAxisScaleNormalized(){return!this._zAxisScale}IsZAxisScaleRegular(){return this._zAxisScale}CalculatePerspectiveMatrix(e,t,i=.5,a=.5){const s=this.GetNearZ(),r=this.GetFarZ(),l=this.GetFovY();if(.5===i&&.5===a)this.IsWebGPU()?mat4.perspectiveZO(e,l,t,s,r):mat4.perspective(e,l,t,s,r);else{const l=2*(i=1-i)-2,n=2*i,h=2*a-2,o=2*a,p=this._GetTanFovYDiv2()*s,_=p*t;mat4.frustum(e,l*_,n*_,h*p,o*p,s,r),this.IsWebGPU()&&mat4.mul(e,matWebGLtoWebGPU,e)}}CalculateOrthographicMatrix(e,t,i,a=1){const s=self.devicePixelRatio,r=2*this.GetDefaultCameraZ(i)*s*this._GetTanFovYDiv2()/i,l=t*r/(2*s*a),n=i*r/(2*s*a),h=-l,o=l,p=-n,_=n;this.IsWebGPU()?mat4.orthoZO(e,h,o,p,_,this.GetNearZ(),this.GetFarZ()):mat4.ortho(e,h,o,p,_,this.GetNearZ(),this.GetFarZ())}CalculateLookAtModelView(e,t,i,a,s,r=1){let l=1;this.IsZAxisScaleNormalized()&&(l=200*this._GetTanFovYDiv2()/s);const n=tmpVec3c;vec3.set(n,l,-l,1);const h=tmpVec3a,o=tmpVec3b;vec3.multiply(h,t,n),vec3.multiply(o,i,n),mat4.lookAt(e,h,o,a||defaultUpVector),n[2]=r,mat4.scale(e,e,n)}CalculateLookAtModelView2(e,t,i,a,s,r,l,n){return vec3.set(tmpVec3a,e,t,i),vec3.set(tmpVec3b,a,s,r),this.CalculateLookAtModelView(tempMat4,tmpVec3a,tmpVec3b,defaultUpVector,l,n),tempMat4}_AddShaderProgram(e){this._allShaderPrograms.push(e),this._shaderProgramsByName.set(e.GetName(),e)}_RemoveShaderProgram(e){const t=this._allShaderPrograms.indexOf(e);-1!==t&&this._allShaderPrograms.splice(t,1),this._shaderProgramsByName.delete(e.GetName())}_ClearAllShaderPrograms(){C3.clearArray(this._allShaderPrograms),this._shaderProgramsByName.clear()}GetShaderProgramByName(e){return this._shaderProgramsByName.get(e)||null}GetTextureFillShaderProgram(){return this._spTextureFill}SetTextureFillMode(){this.SetProgram(this._spTextureFill)}GetPointsRenderingProgram(){return this._spPoints}SetPointsRenderingProgram(){this.SetProgram(this._spPoints)}SetTilemapFillMode(){this.SetProgram(this._spTilemapFill)}SetTileRandomizationMode(){this.SetProgram(this._spTileRandomization)}SetColorFillMode(){this.SetProgram(this._spColorFill)}SetLinearGradientFillMode(){this.SetProgram(this._spLinearGradientFill)}SetPenumbraFillMode(){this.SetProgram(this._spPenumbraFill)}SetHardEllipseFillMode(){this.SetProgram(this._spHardEllipseFill)}SetHardEllipseOutlineMode(){this.SetProgram(this._spHardEllipseOutline)}SetSmoothEllipseFillMode(){this.SetProgram(this._spSmoothEllipseFill)}SetSmoothEllipseOutlineMode(){this.SetProgram(this._spSmoothEllipseOutline)}SetSmoothLineFillMode(){this.SetProgram(this._spSmoothLineFill)}_SetCurrentStateGroup(e){this._currentStateGroup=e}GetCurrentStateGroup(){return this._currentStateGroup}AcquireStateGroup(e,t,i,a){const s=C3.Gfx.StateGroup.MakeKey(e,t,i,a);let r=this._stateGroups.get(s);return r||(r=C3.New(C3.Gfx.StateGroup,this,e,t,i,a),this._stateGroups.set(s,r)),r.AddRef(),r}ReleaseStateGroup(e){e.DecRef(),0===e._GetRefCount()&&(this._currentStateGroup===e&&(this._currentStateGroup=null),this._stateGroups.delete(e.GetKey()),e.Release())}_InitBlendModeData(e){C3.clearArray(this._blendModeTable),this._namedBlendModeMap.clear();let t=0;for(const i of e){const e=i[0],a=i[1],s=i[2];this._blendModeTable.push([a,s]),this._namedBlendModeMap.set(e,{number:t,srcBlend:a,destBlend:s}),t++}}_GetBlendByIndex(e){return this._blendModeTable[e]}GetSrcBlendByIndex(e){return this._GetBlendByIndex(e)[0]}GetDestBlendByIndex(e){return this._GetBlendByIndex(e)[1]}GetNamedBlend(e){const t=this._namedBlendModeMap.get(e);if(void 0===t)throw new Error("invalid blend name");return t}NamedBlendToNumber(e){const t=this._namedBlendModeMap.get(e);if(void 0===t)throw new Error("invalid blend name");return t.number}SetBaseZ(e){this._baseZ=e}GetBaseZ(){return this._baseZ}SetCurrentZ(e){this._currentZ=e,this._currentStateGroup=null}GetCurrentZ(){return this._currentZ}Line(e,t,i,a){const s=C3.angleTo(e,t,i,a),r=Math.sin(s),l=Math.cos(s),n=.5*this._lineWidth,h=r*n,o=l*n,p=this._lineCap;2===p?this.LinePreCalc_LineCap2(e,t,0,i,a,0,h,o):1===p?this.LinePreCalc_LineCap1(e,t,0,i,a,0,h,o):this.LinePreCalc_LineCap0(e,t,0,i,a,0,h,o)}Line3D(e,t,i,a,s,r){const l=C3.angleTo(e,t,a,s),n=Math.sin(l),h=Math.cos(l),o=.5*this._lineWidth,p=n*o,_=h*o,c=this._lineCap;2===c?this.LinePreCalc_LineCap2(e,t,i,a,s,r,p,_):1===c?this.LinePreCalc_LineCap1(e,t,i,a,s,r,p,_):this.LinePreCalc_LineCap0(e,t,i,a,s,r,p,_)}LinePreCalc_LineCap2(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h-n,p=t+h-l,_=a+h+n,c=s+h+l,u=2*n,d=2*l,C=o+l,m=p-n,L=o-l+u,f=p+n+d,g=_+l,S=c-n,P=_-l-u,G=c+n-d;this.Quad3D2(C,m,i,g,S,r,P,G,r,L,f,i,defaultTexCoordsQuad)}LinePreCalc_LineCap1(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h-n,p=t+h-l,_=a+h+n,c=s+h+l,u=o+l,d=p-n,C=o-l,m=p+n,L=_+l,f=c-n,g=_-l,S=c+n;this.Quad3D2(u,d,i,L,f,r,g,S,r,C,m,i,defaultTexCoordsQuad)}LinePreCalc_LineCap0(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h,p=t+h,_=a+h,c=s+h,u=o+l,d=p-n,C=o-l,m=p+n,L=_+l,f=c-n,g=_-l,S=c+n;this.Quad3D2(u,d,i,L,f,r,g,S,r,C,m,i,defaultTexCoordsQuad)}TexturedLine(e,t,i,a,s,r){const l=C3.angleTo(e,t,i,a),n=Math.sin(l),h=Math.cos(l),o=.5*this._lineWidth,p=n*o,_=h*o,c=this._lineCap;2===c?this.TexturedLinePreCalc_LineCap2(e,t,i,a,p,_,s,r):1===c?this.TexturedLinePreCalc_LineCap1(e,t,i,a,p,_,s,r):this.TexturedLinePreCalc_LineCap0(e,t,i,a,p,_,s,r)}TexturedLinePreCalc_LineCap2(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h-r,p=t+h-s,_=i+h+r,c=a+h+s,u=2*r,d=2*s,C=o+s,m=p-r,L=o-s+u,f=p+r+d,g=_+s,S=c-r,P=_-s-u,G=c+r-d;tmpQuad.set(C,m,g,S,P,G,L,f),tmpRect.set(l,0,n,0),this.Quad3(tmpQuad,tmpRect)}TexturedLinePreCalc_LineCap1(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h-r,p=t+h-s,_=i+h+r,c=a+h+s,u=o+s,d=p-r,C=o-s,m=p+r,L=_+s,f=c-r,g=_-s,S=c+r;tmpQuad.set(u,d,L,f,g,S,C,m),tmpRect.set(l,0,n,0),this.Quad3(tmpQuad,tmpRect)}TexturedLinePreCalc_LineCap0(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h,p=t+h,_=i+h,c=a+h,u=o+s,d=p-r,C=o-s,m=p+r,L=_+s,f=c-r,g=_-s,S=c+r;tmpQuad.set(u,d,L,f,g,S,C,m),tmpRect.set(l,0,n,0),this.Quad3(tmpQuad,tmpRect)}LineRect(e,t,i,a){const s=.5*this._lineWidth,r=this._lineCap;2===r?this._LineRectPreCalc_LineCap2(e,t,i,a,s):1===r?this._LineRectPreCalc_LineCap1(e,t,i,a,s):this._LineRectPreCalc_LineCap0(e,t,i,a,s)}_LineRectPreCalc_LineCap2(e,t,i,a,s){this.LinePreCalc_LineCap2(e,t,0,i,t,0,0,s),this.LinePreCalc_LineCap2(i,t,0,i,a,0,s,0),this.LinePreCalc_LineCap2(i,a,0,e,a,0,0,-s),this.LinePreCalc_LineCap2(e,a,0,e,t,0,-s,0)}_LineRectPreCalc_LineCap1(e,t,i,a,s){this.LinePreCalc_LineCap1(e,t,0,i,t,0,0,s),this.LinePreCalc_LineCap1(i,t,0,i,a,0,s,0),this.LinePreCalc_LineCap1(i,a,0,e,a,0,0,-s),this.LinePreCalc_LineCap1(e,a,0,e,t,0,-s,0)}_LineRectPreCalc_LineCap0(e,t,i,a,s){this.LinePreCalc_LineCap0(e,t,0,i,t,0,0,s),this.LinePreCalc_LineCap0(i,t,0,i,a,0,s,0),this.LinePreCalc_LineCap0(i,a,0,e,a,0,0,-s),this.LinePreCalc_LineCap0(e,a,0,e,t,0,-s,0)}LineRect2(e){this.LineRect(e.getLeft(),e.getTop(),e.getRight(),e.getBottom())}LineQuad(e){const t=C3.angleTo(e.getTlx(),e.getTly(),e.getTrx(),e.getTry()),i=Math.sin(t),a=Math.cos(t),s=.5*this._lineWidth,r=i*s,l=a*s,n=this._lineCap;2===n?this._LineQuadPreCalc_LineCap2(e,r,l):1===n?this._LineQuadPreCalc_LineCap1(e,r,l):this._LineQuadPreCalc_LineCap0(e,r,l)}_LineQuadPreCalc_LineCap2(e,t,i){this.LinePreCalc_LineCap2(e.getTlx(),e.getTly(),0,e.getTrx(),e.getTry(),0,t,i),this.LinePreCalc_LineCap2(e.getTrx(),e.getTry(),0,e.getBrx(),e.getBry(),0,i,-t),this.LinePreCalc_LineCap2(e.getBrx(),e.getBry(),0,e.getBlx(),e.getBly(),0,-t,-i),this.LinePreCalc_LineCap2(e.getBlx(),e.getBly(),0,e.getTlx(),e.getTly(),0,-i,t)}_LineQuadPreCalc_LineCap1(e,t,i){this.LinePreCalc_LineCap1(e.getTlx(),e.getTly(),0,e.getTrx(),e.getTry(),0,t,i),this.LinePreCalc_LineCap1(e.getTrx(),e.getTry(),0,e.getBrx(),e.getBry(),0,i,-t),this.LinePreCalc_LineCap1(e.getBrx(),e.getBry(),0,e.getBlx(),e.getBly(),0,-t,-i),this.LinePreCalc_LineCap1(e.getBlx(),e.getBly(),0,e.getTlx(),e.getTly(),0,-i,t)}_LineQuadPreCalc_LineCap0(e,t,i){this.LinePreCalc_LineCap0(e.getTlx(),e.getTly(),0,e.getTrx(),e.getTry(),0,t,i),this.LinePreCalc_LineCap0(e.getTrx(),e.getTry(),0,e.getBrx(),e.getBry(),0,i,-t),this.LinePreCalc_LineCap0(e.getBrx(),e.getBry(),0,e.getBlx(),e.getBly(),0,-t,-i),this.LinePreCalc_LineCap0(e.getBlx(),e.getBly(),0,e.getTlx(),e.getTly(),0,-i,t)}SetLineWidth(e){this._lineWidth=e,this._lineWidthStack[this._lineWidthStack.length-1]=e}GetLineWidth(){return this._lineWidth}PushLineWidth(e){if(this._lineWidthStack.length>=100)throw new Error("pushed too many line widths - check push/pop pairs");this._lineWidthStack.push(e),this._lineWidth=e}PopLineWidth(){if(this._lineWidthStack.length<=1)throw new Error("cannot pop last line width - check push/pop pairs");this._lineWidthStack.pop(),this._lineWidth=this._lineWidthStack.at(-1)}SetLineCapButt(){this._lineCap=0,this._lineCapStack[this._lineCapStack.length-1]=0}SetLineCapSquare(){this._lineCap=1,this._lineCapStack[this._lineCapStack.length-1]=0}SetLineCapZag(){this._lineCap=2,this._lineCapStack[this._lineCapStack.length-1]=0}PushLineCap(e){if("butt"===e)this.PushLineCapButt();else if("square"===e)this.PushLineCapSquare();else{if("zag"!==e)throw new Error("invalid line cap");this.PushLineCapZag()}}PushLineCapButt(){if(this._lineCapStack.length>=100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(0),this._lineCap=0}PushLineCapSquare(){if(this._lineCapStack.length>=100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(1),this._lineCap=1}PushLineCapZag(){if(this._lineCapStack.length>=100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(2),this._lineCap=2}PopLineCap(){if(this._lineCapStack.length<=1)throw new Error("cannot pop last line cap - check push/pop pairs");this._lineCapStack.pop(),this._lineCap=this._lineCapStack.at(-1)}SetLineOffset(e){this._lineOffset=e,this._lineOffsetStack[this._lineOffsetStack.length-1]=e}GetLineOffset(){return this._lineOffset}PushLineOffset(e){if(this._lineOffsetStack.length>=100)throw new Error("pushed too many line offsets - check push/pop pairs");this._lineOffsetStack.push(e),this._lineOffset=e}PopLineOffset(){if(this._lineOffsetStack.length<=1)throw new Error("cannot pop last line offset - check push/pop pairs");this._lineOffsetStack.pop(),this._lineOffset=this._lineOffsetStack.at(-1)}ConvexPoly(e){const t=e.length/2;if(t<3)throw new Error("need at least 3 points");const i=t-2,a=i-1,s=e[0],r=e[1];for(let t=0;t<i;t+=2){const i=2*t,l=e[i+2],n=e[i+3],h=e[i+4],o=e[i+5];if(t===a)this.Quad2(s,r,l,n,h,o,h,o);else{const t=e[i+6],a=e[i+7];this.Quad2(s,r,l,n,h,o,t,a)}}}GetNumVertexComponents(){return 3}Finish(){this.EndBatch(!0),this._frameNumber++}GetFrameNumber(){return this._frameNumber}IncrementFrameNumber(){this._frameNumber++}SetMipmapsEnabled(e){this._enableMipmaps=!!e}AreMipmapsEnabled(){return this._enableMipmaps}SetHasMajorPerformanceCaveat(e){this._hasMajorPerformanceCaveat=!!e}HasMajorPerformanceCaveat(){return this._hasMajorPerformanceCaveat}IsWebGL(){return!1}IsWebGPU(){return!1}GetEstimatedBackBufferMemoryUsage(){}GetEstimatedRenderBufferMemoryUsage(){}GetEstimatedTextureMemoryUsage(){}GetEstimatedTotalMemoryUsage(){return this.GetEstimatedBackBufferMemoryUsage()+this.GetEstimatedRenderBufferMemoryUsage()+this.GetEstimatedTextureMemoryUsage()}CreateRendererText(){return C3.New(C3.Gfx.RendererText,this)}};
}

// ../lib/gfx/shaderProgramBase.js
{
const C3=self.C3;C3.Gfx.ShaderProgramBase=class{constructor(e,t){this._name=t.name,this._renderer=e,this._extendBoxHorizontal=t.extendBoxHorizontal||0,this._extendBoxVertical=t.extendBoxVertical||0,this._crossSampling=!!t.crossSampling,this._mustPreDraw=!!t.mustPreDraw,this._preservesOpaqueness=!!t.preservesOpaqueness,this._supports3dDirectRendering=!!t.supports3dDirectRendering,this._animated=!!t.animated,this._blendsBackground=!!t.blendsBackground,this._usesDepth=!!t.usesDepth,this._usesAnySrcRectOrPixelSize=!1,this._needsPostDrawOrExtendBox=this._crossSampling||this._blendsBackground||0!==this._extendBoxHorizontal||0!==this._extendBoxVertical}Release(){this._renderer=null}GetRenderer(){return this._renderer}GetName(){return this._name}ExtendsBox(){return 0!==this._extendBoxHorizontal||0!==this._extendBoxVertical}GetBoxExtendHorizontal(){return this._extendBoxHorizontal}GetBoxExtendVertical(){return this._extendBoxVertical}UsesCrossSampling(){return this._crossSampling}MustPreDraw(){return this._mustPreDraw}PreservesOpaqueness(){return this._preservesOpaqueness}Supports3DDirectRendering(){return this._supports3dDirectRendering}IsAnimated(){return this._animated}BlendsBackground(){return this._blendsBackground}UsesDepth(){return this._usesDepth}UsesAnySrcRectOrPixelSize(){return this._usesAnySrcRectOrPixelSize}NeedsPostDrawOrExtendsBox(){return this._needsPostDrawOrExtendBox}UsesIsSrcTexRotated(){return!1}};
}

// ../lib/gfx/stateGroup.js
{
const C3=self.C3;C3.Gfx.StateGroup=class{constructor(e,r,t,s,o){this._renderer=e,this._refCount=0,this._shaderProgram=null,this._shaderProgramName="",this._blendMode=t,this._color=C3.New(C3.Color),this._color.set(s),this._zElevation=o,"string"==typeof r?this._shaderProgramName=r:(this._shaderProgram=r,this._shaderProgramName=this._shaderProgram.GetName())}Release(){if(this._refCount>0)throw new Error("releasing state group still in use");this._renderer=null,this._shaderProgram=null,this._shaderProgramName=""}Apply(){const e=this._renderer;e.SetProgram(this._shaderProgram),e.SetBlendMode(this._blendMode),e.SetColor(this._color),e.SetCurrentZ(this._zElevation),e._SetCurrentStateGroup(this)}GetKey(){return C3.Gfx.StateGroup.MakeKey(this._shaderProgramName,this._blendMode,this._color,this._zElevation)}AddRef(){++this._refCount}DecRef(){--this._refCount}_GetRefCount(){return this._refCount}OnContextLost(){this._shaderProgram=null}OnContextRestored(e){if(this._shaderProgram=e.GetShaderProgramByName(this._shaderProgramName),!this._shaderProgram)throw new Error("failed to restore shader program")}static MakeKey(e,r,t,s){return("string"==typeof e?e:e.GetName())+","+r+","+t.getR()+","+t.getG()+","+t.getB()+","+t.getA()+","+s}};
}

// ../lib/gfx/mesh.js
{
const C3=self.C3,tempQuadTex=C3.New(C3.Quad);function interpolateQuad(t,e,s){const i=s.getTlx(),n=s.getTly(),o=s.getTrx()-i,h=s.getTry()-n;return[i+o*t+(s.getBlx()-i)*e,n+h*t+(s.getBly()-n)*e]}C3.Gfx.MeshPoint=class{constructor(t,e,s){this._mesh=t,this._col=e,this._row=s,this._x=NaN,this._y=NaN,this._zElevation=NaN,this._u=NaN,this._v=NaN,this._x=0,this._y=0,this._zElevation=0,this._u=0,this._v=0}_Init(t,e,s,i){this._x=t,this._y=e,this._u=s,this._v=i}GetX(){return this._x}SetX(t){this._x!==t&&(this._x=t,this._mesh._SetPointsChanged())}GetY(){return this._y}SetY(t){this._y!==t&&(this._y=t,this._mesh._SetPointsChanged())}GetZElevation(){return this._zElevation}SetZElevation(t){this._zElevation!==t&&(this._zElevation=Math.max(t,0),this._mesh._SetPointsChanged())}GetU(){return this._u}SetU(t){this._u=t}GetV(){return this._v}SetV(t){this._v=t}_Interpolate_TexRect(t,e,s){[this._x,this._y]=interpolateQuad(t._x,t._y,e),this._zElevation=t._zElevation,this._u=C3.lerp(s.getLeft(),s.getRight(),t._u),this._v=C3.lerp(s.getTop(),s.getBottom(),t._v)}_Interpolate_TexQuad(t,e,s){[this._x,this._y]=interpolateQuad(t._x,t._y,e),this._zElevation=t._zElevation,[this._u,this._v]=interpolateQuad(t._u,t._v,s)}SaveToJson(){return{"x":this.GetX(),"y":this.GetY(),"z":this.GetZElevation(),"u":this.GetU(),"v":this.GetV()}}LoadFromJson(t){this.SetX(t["x"]),this.SetY(t["y"]),t.hasOwnProperty("z")&&this.SetZElevation(t["z"]),this.SetU(t["u"]),this.SetV(t["v"])}GetMesh(){return this._mesh}GetColumn(){return this._col}GetRow(){return this._row}},C3.Gfx.Mesh=class{constructor(t,e,s){if(t<2||e<2)throw new Error("invalid mesh size");this._hsize=t,this._vsize=e,this._owner=s||null,this._pts=[],this._minX=0,this._minY=0,this._maxX=1,this._maxY=1,this._maxZ=0,this._pointsChanged=!1;const i=t-1,n=e-1;for(let s=0;s<e;++s){const e=[];for(let o=0;o<t;++o){const t=C3.New(C3.Gfx.MeshPoint,this,o,s),h=o/i,r=s/n;t._Init(h,r,h,r),e.push(t)}this._pts.push(e)}}Release(){C3.clearArray(this._pts)}GetHSize(){return this._hsize}GetVSize(){return this._vsize}GetOwner(){return this._owner}_GetPoints(){return this._pts}_SetPointsChanged(){this._pointsChanged=!0}_MaybeComputeBounds(){if(!this._pointsChanged)return;let t=1/0,e=1/0,s=-1/0,i=-1/0,n=0;for(const o of this._pts)for(const h of o){const o=h.GetX(),r=h.GetY();t=Math.min(t,o),e=Math.min(e,r),s=Math.max(s,o),i=Math.max(i,r),n=Math.max(n,h.GetZElevation())}this._minX=t,this._minY=e,this._maxX=s,this._maxY=i,this._maxZ=n,this._pointsChanged=!1}GetMinX(){return this._MaybeComputeBounds(),this._minX}GetMinY(){return this._MaybeComputeBounds(),this._minY}GetMaxX(){return this._MaybeComputeBounds(),this._maxX}GetMaxY(){return this._MaybeComputeBounds(),this._maxY}GetMaxZ(){return this._MaybeComputeBounds(),this._maxZ}HasAnyZElevation(){return this.GetMaxZ()>0}GetMeshPointAt(t,e){return t=Math.floor(t),e=Math.floor(e),t<0||t>=this._hsize||e<0||e>=this._vsize?null:this._pts[e][t]}CalculateTransformedMesh(t,e,s){const i=s instanceof C3.Rect;if(t.GetHSize()!==this.GetHSize()||t.GetVSize()!==this.GetVSize())throw new Error("source mesh wrong size");const n=t._pts,o=this._pts;for(let t=0,h=o.length;t<h;++t){const h=n[t],r=o[t];for(let t=0,n=r.length;t<n;++t){const n=h[t],o=r[t];i?o._Interpolate_TexRect(n,e,s):o._Interpolate_TexQuad(n,e,s)}}}Draw(t){const e=this._pts;let s=e[0];for(let i=1,n=e.length;i<n;++i){const n=e[i];let o=s[0],h=n[0];for(let e=1,i=n.length;e<i;++e){const i=s[e],r=n[e];tempQuadTex.set(o.GetU(),o.GetV(),i.GetU(),i.GetV(),r.GetU(),r.GetV(),h.GetU(),h.GetV()),t.Quad3D2(o.GetX(),o.GetY(),o.GetZElevation(),i.GetX(),i.GetY(),i.GetZElevation(),r.GetX(),r.GetY(),r.GetZElevation(),h.GetX(),h.GetY(),h.GetZElevation(),tempQuadTex),o=i,h=r}s=n}}Outline(t,e){e||(e=(t,e,s)=>[t,e,s]);const s=this._pts;let i=s[0];for(let n=1,o=s.length;n<o;++n){const h=s[n];let r=i[0],a=h[0];for(let s=1,l=h.length;s<l;++s){const _=i[s],G=h[s],[u,c,m]=e(r.GetX(),r.GetY(),r.GetZElevation()),[p,C,f]=e(_.GetX(),_.GetY(),_.GetZElevation()),[x,v,M]=e(G.GetX(),G.GetY(),G.GetZElevation()),[g,y,d]=e(a.GetX(),a.GetY(),a.GetZElevation());t.Line3D(u,c,m,p,C,f),t.Line3D(u,c,m,x,v,M),t.Line3D(u,c,m,g,y,d),s===l-1&&t.Line3D(p,C,f,x,v,M),n===o-1&&t.Line3D(g,y,d,x,v,M),r=_,a=G}i=h}}InsertPolyMeshVertices(t){const e=.001,s=.99999999,i=t.pointsArr(),n=[],o=this.GetHSize()-1,h=this.GetVSize()-1,r=1/o,a=1/h,l=o-1,_=h-1;let G=i[0],u=i[1],c=C3.clamp(Math.floor(G*o),0,l),m=C3.clamp(Math.floor(u*h),0,_),p=!0,C=0,f=0,x=0;let v=-1;const M=()=>{G=C3.clamp(C3.lerp(G,C,x),0,1),u=C3.clamp(C3.lerp(u,f,x),0,1),n.push(G,u)};for(let t=0,g=i.length;t<g;t+=2){G=i[t],u=i[t+1],n.push(G,u),c=C3.clamp(Math.floor(G*o),0,l),m=C3.clamp(Math.floor(u*h),0,_);const y=(t+2)%g;for(C=i[y],f=i[y+1],v=-1;;){if(n.length>1e6)throw new Error("Too many mesh poly points");const t=c*r,i=m*a,o=(c+1)*r,h=(m+1)*a;if(p=C3.isPointInTriangleInclusive(G,u,t,i,o,i,o,h),0!==v&&(x=C3.rayIntersectExtended(G,u,C,f,t,i,o,h,-.001),x>=0&&x<=s))M(),p=!p,v=0;else if(m>0&&2!==v&&(x=C3.rayIntersectExtended(G,u,C,f,t,i,o,i,e),x>=0&&x<=s))M(),m--,p=!1,v=4;else if(c<l&&3!==v&&(x=C3.rayIntersectExtended(G,u,C,f,o,i,o,h,e),x>=0&&x<=s))M(),c++,p=!1,v=1;else if(c>0&&1!==v&&(x=C3.rayIntersectExtended(G,u,C,f,t,i,t,h,e),x>=0&&x<=s))M(),c--,p=!0,v=3;else{if(!(m<_&&4!==v&&(x=C3.rayIntersectExtended(G,u,C,f,t,h,o,h,e),x>=0&&x<=s)))break;M(),m++,p=!0,v=2}}}return C3.New(C3.CollisionPoly,n)}TransformCollisionPoly(t,e){const s=this._TransformPolyPoints(t);this._SimplifyPoly(s),e.setPoints(s)}_TransformPolyPoints(t){const e=[],s=t.pointsArr();for(let t=0,i=s.length;t<i;t+=2){const i=s[t],n=s[t+1],[o,h]=this.TransformPoint(i,n);e.push(o,h)}return e}TransformPoint(t,e){const s=this.GetHSize()-1,i=this.GetVSize()-1,n=1/s,o=1/i,h=C3.clamp(Math.floor(t*s),0,s-1),r=C3.clamp(Math.floor(e*i),0,i-1),a=h*n,l=r*o,_=(h+1)*n,G=(r+1)*o,u=this.GetMeshPointAt(h,r),c=this.GetMeshPointAt(h+1,r+1),m=C3.isPointInTriangleInclusive(t,e,a,l,_,l,_,G),p=m?a+n:a,C=m?l:l+o,f=this.GetMeshPointAt(h+(m?1:0),r+(m?0:1)),[x,v,M]=C3.triangleCartesianToBarycentric(t,e,a,l,p,C,_,G);return C3.triangleBarycentricToCartesian3d(x,v,M,u.GetX(),u.GetY(),u.GetZElevation(),f.GetX(),f.GetY(),f.GetZElevation(),c.GetX(),c.GetY(),c.GetZElevation())}_SimplifyPoly(t){const e=[],s=1e-7;let i=t[0],n=t[1],o=i-t.at(-2),h=n-t.at(-1);for(let r=0,a=t.length;r<a;r+=2){const l=(r+2)%a,_=t[l],G=t[l+1],u=_-i,c=G-n,m=Math.abs(u)<s&&Math.abs(o)<s&&Math.sign(c)===Math.sign(h),p=Math.abs(c)<s&&Math.abs(h)<s&&Math.sign(u)===Math.sign(o);(!m&&!p&&Math.abs(u/o-c/h)>.001||0==u&&0===c)&&e.push(i,n),i=_,n=G,o=u,h=c}e.length>=6&&e.length<t.length&&C3.shallowAssignArray(t,e)}SaveToJson(){return{"cols":this.GetHSize(),"rows":this.GetVSize(),"points":this._pts.map((t=>t.map((t=>t.SaveToJson()))))}}LoadFromJson(t){const e=this.GetHSize(),s=this.GetVSize();if(t["cols"]!==e||t["rows"]!==s)throw new Error("mesh data wrong size");const i=t["points"];for(let t=0;t<s;++t){const s=i[t];for(let i=0;i<e;++i){this.GetMeshPointAt(i,t).LoadFromJson(s[i])}}}};
}

// ../lib/gfx/webgl/texture.js
{
const C3=self.C3,VALID_PIXEL_FORMATS=new Set(["rgba8","rgb8","rgba4","rgb5_a1","rgb565"]),VALID_SAMPLINGS=new Set(["nearest","bilinear","trilinear"]),VALID_MIPMAP_QUALITIES=new Set(["default","low","high"]),VALID_WRAP_MODES=new Set(["clamp-to-edge","repeat","mirror-repeat"]);function GetFormatSpecifiers(e,t){let i,r,a,s;switch(e){case"rgba8":i=t.RGBA8,r=t.RGBA,a=t.RGBA,s=t.UNSIGNED_BYTE;break;case"rgb8":i=t.RGB8,r=t.RGB,a=t.RGB,s=t.UNSIGNED_BYTE;break;case"rgba4":i=t.RGBA4,r=t.RGBA,a=t.RGBA,s=t.UNSIGNED_SHORT_4_4_4_4;break;case"rgb5_a1":i=t.RGB5_A1,r=t.RGBA,a=t.RGBA,s=t.UNSIGNED_SHORT_5_5_5_1;break;case"rgb565":i=t.RGB565,r=t.RGB,a=t.RGB,s=t.UNSIGNED_SHORT_5_6_5;break;default:throw new Error("invalid pixel format")}return{sizedinternalformat:i,internalformat:r,format:a,type:s}}const CREATEFROM_DEFAULT_OPTIONS={wrapX:"clamp-to-edge",wrapY:"clamp-to-edge",sampling:"trilinear",anisotropy:0,pixelFormat:"rgba8",mipMap:!0,mipMapQuality:"default",premultiplyAlpha:!0,isSvg:!1,width:-1,height:-1},UPDATE_DEFAULT_OPTIONS={premultiplyAlpha:!0,flipY:!1},allTextures=new Set;C3.Gfx.WebGLRendererTexture=class{constructor(e){this._renderer=e,this._texture=null,this._width=0,this._height=0,this._isStatic=!0,this._wrapX="clamp-to-edge",this._wrapY="clamp-to-edge",this._sampling="trilinear",this._anisotropy=0,this._pixelFormat="rgba8",this._isMipMapped=!1,this._mipMapQuality="default",this._refCount=0}_CreateStatic(e,t){if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||e instanceof ImageData||e instanceof ArrayBuffer||null===e))throw new Error("invalid texture source");if(t=Object.assign({},CREATEFROM_DEFAULT_OPTIONS,t),this._texture)throw new Error("already created texture");if(this._wrapX=t.wrapX,this._wrapY=t.wrapY,this._sampling=t.sampling,this._anisotropy=t.anisotropy,this._pixelFormat=t.pixelFormat,this._isMipMapped=!!t.mipMap&&this._renderer.AreMipmapsEnabled(),this._mipMapQuality=t.mipMapQuality,!VALID_WRAP_MODES.has(this._wrapX)||!VALID_WRAP_MODES.has(this._wrapY))throw new Error("invalid wrap mode");if(!VALID_SAMPLINGS.has(this._sampling))throw new Error("invalid sampling");if(!VALID_PIXEL_FORMATS.has(this._pixelFormat))throw new Error("invalid pixel format");if(!VALID_MIPMAP_QUALITIES.has(this._mipMapQuality))throw new Error("invalid mipmap quality");if(this._isStatic=!0,e instanceof ArrayBuffer||null===e||t.isSvg){if(this._width=t.width,this._height=t.height,e instanceof ArrayBuffer&&e.byteLength!==this._width*this._height*4)throw new Error("ArrayBuffer wrong size")}else this._width=e.width,this._height=e.height;if(this._width<=0||this._height<=0)throw new Error("invalid texture data size");if(t.isSvg){const t=C3.CreateCanvas(this._width,this._height);t.getContext("2d").drawImage(e,0,0,this._width,this._height),e=t}const i=C3.isPOT(this._width)&&C3.isPOT(this._height),r=this._renderer.GetMaxTextureSize();if(this._width>r||this._height>r)throw new Error("texture data exceeds maximum texture size");const a=this._renderer.GetContext(),s=this._renderer.GetWebGLVersionNumber();this._texture=a.createTexture(),a.bindTexture(a.TEXTURE_2D,this._texture),a.pixelStorei(a["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],t.premultiplyAlpha),a.pixelStorei(a["UNPACK_FLIP_Y_WEBGL"],!1);const h=GetFormatSpecifiers(this._pixelFormat,a);if(this._renderer.SupportsNPOTTextures()||i||!this._IsTiled())if(s>=2){let t;t=this._isMipMapped?Math.floor(Math.log2(Math.max(this._width,this._height))+1):1,a.texStorage2D(a.TEXTURE_2D,t,h.sizedinternalformat,this._width,this._height),e instanceof ArrayBuffer?a.texSubImage2D(a.TEXTURE_2D,0,0,0,this._width,this._height,h.format,h.type,new Uint8Array(e)):null!==e&&a.texSubImage2D(a.TEXTURE_2D,0,0,0,h.format,h.type,e)}else e instanceof ArrayBuffer?a.texImage2D(a.TEXTURE_2D,0,h.internalformat,this._width,this._height,0,h.format,h.type,new Uint8Array(e)):null===e?a.texImage2D(a.TEXTURE_2D,0,h.internalformat,this._width,this._height,0,h.format,h.type,null):a.texImage2D(a.TEXTURE_2D,0,h.internalformat,h.format,h.type,e);else{if(null===e)throw new Error("cannot pass null data when creating a NPOT tiled texture without NPOT support");if(e instanceof ArrayBuffer&&(e=new ImageData(new Uint8ClampedArray(e),this._width,this._height)),e instanceof ImageData){const t=C3.CreateCanvas(this._width,this._height);t.getContext("2d").putImageData(e,0,0),e=t}const t=C3.CreateCanvas(C3.nextHighestPowerOfTwo(this._width),C3.nextHighestPowerOfTwo(this._height)),i=t.getContext("2d");i.imageSmoothingEnabled="nearest"!==this._sampling,i.drawImage(e,0,0,this._width,this._height,0,0,t.width,t.height),a.texImage2D(a.TEXTURE_2D,0,h.internalformat,h.format,h.type,t)}null!==e&&this._SetTextureParameters(a),a.bindTexture(a.TEXTURE_2D,null),this._renderer._ResetLastTexture(),this._refCount=1,allTextures.add(this)}_CreateDynamic(e,t,i){if(i=Object.assign({},CREATEFROM_DEFAULT_OPTIONS,i),this._texture)throw new Error("already created texture");if(this._wrapX=i.wrapX,this._wrapY=i.wrapY,this._sampling=i.sampling,this._pixelFormat=i.pixelFormat,this._isMipMapped=!!i.mipMap&&this._renderer.AreMipmapsEnabled(),this._mipMapQuality=i.mipMapQuality,!VALID_WRAP_MODES.has(this._wrapX)||!VALID_WRAP_MODES.has(this._wrapY))throw new Error("invalid wrap mode");if(!VALID_SAMPLINGS.has(this._sampling))throw new Error("invalid sampling");if(!VALID_PIXEL_FORMATS.has(this._pixelFormat))throw new Error("invalid pixel format");if(!VALID_MIPMAP_QUALITIES.has(this._mipMapQuality))throw new Error("invalid mipmap quality");this._isStatic=!1,this._width=Math.floor(e),this._height=Math.floor(t);const r=C3.isPOT(this._width)&&C3.isPOT(this._height),a=this._renderer.GetMaxTextureSize();if(this._width<=0||this._height<=0)throw new Error("invalid texture size");if(this._width>a||this._height>a)throw new Error("texture exceeds maximum texture size");if(!this._renderer.SupportsNPOTTextures()&&this._IsTiled()&&!r)throw new Error("non-power-of-two tiled textures not supported");const s=this._renderer.GetContext(),h=this._renderer.GetWebGLVersionNumber();this._texture=s.createTexture(),s.bindTexture(s.TEXTURE_2D,this._texture),s.pixelStorei(s["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],i.premultiplyAlpha),s.pixelStorei(s["UNPACK_FLIP_Y_WEBGL"],!1);const n=GetFormatSpecifiers(this._pixelFormat,s),_=h>=2?n.sizedinternalformat:n.internalformat;s.texImage2D(s.TEXTURE_2D,0,_,this._width,this._height,0,n.format,n.type,null),this._SetTextureParameters(s),s.bindTexture(s.TEXTURE_2D,null),this._renderer._ResetLastTexture(),this._refCount=1,allTextures.add(this)}_GetMipMapHint(e){if("default"===this._mipMapQuality)return this._isStatic?e.NICEST:e.FASTEST;if("low"===this._mipMapQuality)return e.FASTEST;if("high"===this._mipMapQuality)return e.NICEST;throw new Error("invalid mipmap quality")}_IsTiled(){return"clamp-to-edge"!==this._wrapX||"clamp-to-edge"!==this._wrapY}_GetTextureWrapMode(e,t){if("clamp-to-edge"===t)return e.CLAMP_TO_EDGE;if("repeat"===t)return e.REPEAT;if("mirror-repeat"===t)return e.MIRRORED_REPEAT;throw new Error("invalid wrap mode")}_SetTextureParameters(e){const t=C3.isPOT(this._width)&&C3.isPOT(this._height);if(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,this._GetTextureWrapMode(e,this._wrapX)),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,this._GetTextureWrapMode(e,this._wrapY)),"nearest"===this._sampling)e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),this._isMipMapped=!1;else if(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),(t||this._renderer.SupportsNPOTTextures())&&this._isMipMapped){e.hint(e.GENERATE_MIPMAP_HINT,this._GetMipMapHint(e)),e.generateMipmap(e.TEXTURE_2D);const t="trilinear"===this._sampling&&!this._renderer.HasMajorPerformanceCaveat();e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.LINEAR_MIPMAP_NEAREST)}else e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),this._isMipMapped=!1;const i=this._renderer._GetAnisotropicExtension();i&&this._anisotropy>0&&"nearest"!==this._sampling&&e.texParameterf(e.TEXTURE_2D,i["TEXTURE_MAX_ANISOTROPY_EXT"],Math.min(this._anisotropy,this._renderer._GetMaxAnisotropy()))}_Update(e,t){if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||e instanceof ImageData))throw new Error("invalid texture source");if(!this._texture||this._refCount<=0)throw new Error("texture not created");if(this._isStatic)throw new Error("cannot update static texture");t=Object.assign({},UPDATE_DEFAULT_OPTIONS,t);const i=e.width||e.videoWidth,r=e.height||e.videoHeight,a=this._renderer.GetWebGLVersionNumber(),s=this._renderer.GetContext();s.bindTexture(s.TEXTURE_2D,this._texture),s.pixelStorei(s["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],t.premultiplyAlpha),s.pixelStorei(s["UNPACK_FLIP_Y_WEBGL"],!!t.flipY);const h=GetFormatSpecifiers(this._pixelFormat,s),n=a>=2?h.sizedinternalformat:h.internalformat;try{if(this._width===i&&this._height===r){const t=C3.isPOT(this._width)&&C3.isPOT(this._height);s.texSubImage2D(s.TEXTURE_2D,0,0,0,h.format,h.type,e),(t||this._renderer.SupportsNPOTTextures())&&this._isMipMapped&&(s.hint(s.GENERATE_MIPMAP_HINT,this._GetMipMapHint(s)),s.generateMipmap(s.TEXTURE_2D))}else{this._width=i,this._height=r;const t=C3.isPOT(this._width)&&C3.isPOT(this._height);if(!this._renderer.SupportsNPOTTextures()&&this._IsTiled()&&!t)throw new Error("non-power-of-two tiled textures not supported");s.texImage2D(s.TEXTURE_2D,0,n,h.format,h.type,e),(t||this._renderer.SupportsNPOTTextures())&&this._isMipMapped&&(s.hint(s.GENERATE_MIPMAP_HINT,this._GetMipMapHint(s)),s.generateMipmap(s.TEXTURE_2D))}}catch(e){console.error("Error updating WebGL texture: ",e)}s.bindTexture(s.TEXTURE_2D,null),this._renderer._ResetLastTexture()}_Delete(){if(this._refCount>0)throw new Error("texture still has references");if(!this._texture)throw new Error("already deleted texture");allTextures.delete(this);this._renderer.GetContext().deleteTexture(this._texture),this._texture=null}IsValid(){return!!this._texture}_GetTexture(){return this._texture}GetRenderer(){return this._renderer}AddReference(){this._refCount++}SubtractReference(){if(this._refCount<=0)throw new Error("no more references");this._refCount--}GetReferenceCount(){return this._refCount}GetWidth(){return this._width}GetHeight(){return this._height}IsStatic(){return this._isStatic}GetEstimatedMemoryUsage(){let e=this._width*this._height;switch(this._pixelFormat){case"rgba8":e*=4;break;case"rgb8":e*=3;break;case"rgba4":case"rgb5_a1":case"rgb565":e*=2}return this._isMipMapped&&(e+=Math.floor(e/3)),e}static OnContextLost(){allTextures.clear()}static allTextures(){return allTextures.values()}};
}

// ../lib/gfx/webgl/renderTarget.js
{
const C3=self.C3,assert=self.assert,glMatrix=self.glMatrix,vec3=glMatrix.vec3,mat4=glMatrix.mat4,VALID_SAMPLINGS=new Set(["nearest","bilinear","trilinear"]),DEFAULT_RENDERTARGET_OPTIONS={sampling:"trilinear",alpha:!0,depth:!1,isSampled:!0,isDefaultSize:!0,multisampling:0},allRenderTargets=new Set;C3.Gfx.WebGLRenderTarget=class{constructor(e){this._renderer=e,this._frameBuffer=null,this._frameBufferNoDepth=null,this._texture=null,this._renderBuffer=null,this._width=0,this._height=0,this._isDefaultSize=!0,this._sampling="trilinear",this._alpha=!0,this._depth=!1,this._isSampled=!0,this._multisampling=0,this._projectionMatrix=mat4.create(),this._lastFov=0,this._lastNearZ=0,this._lastFarZ=0}_Create(e,t,r){r=Object.assign({},DEFAULT_RENDERTARGET_OPTIONS,r);const i=this._renderer.GetWebGLVersionNumber();if(this._texture||this._renderBuffer)throw new Error("already created render target");if(this._sampling=r.sampling,this._alpha=!!r.alpha,this._depth=!!r.depth,this._isSampled=!!r.isSampled,this._isDefaultSize=!!r.isDefaultSize,this._multisampling=r.multisampling,!VALID_SAMPLINGS.has(this._sampling))throw new Error("invalid sampling");if(this._multisampling>0&&(i<2||this._isSampled))throw new Error("invalid use of multisampling");if(i<2&&(this._isSampled=!0),this._width=e,this._height=t,this._width<=0||this._height<=0)throw new Error("invalid render target size");this._CalculateProjection();const s=this._renderer.GetContext();if(this._frameBuffer=s.createFramebuffer(),this._depth&&(this._frameBufferNoDepth=s.createFramebuffer()),this._isSampled){this._texture=this._renderer.CreateDynamicTexture(this._width,this._height,{sampling:this._sampling,pixelFormat:this._alpha?"rgba8":"rgb8",mipMap:!1});const e=this._texture._GetTexture();s.bindFramebuffer(s.FRAMEBUFFER,this._frameBuffer),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,e,0),this._depth&&(s.bindFramebuffer(s.FRAMEBUFFER,this._frameBufferNoDepth),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,e,0))}else{this._renderBuffer=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,this._renderBuffer);const e=this._alpha?s.RGBA8:s.RGB8;if(this._multisampling>0){const t=s.getInternalformatParameter(s.RENDERBUFFER,e,s.SAMPLES);if(t&&t[0]){const e=t[0];this._multisampling>e&&(this._multisampling=e)}else this._multisampling=0}0===this._multisampling?s.renderbufferStorage(s.RENDERBUFFER,e,this._width,this._height):s.renderbufferStorageMultisample(s.RENDERBUFFER,this._multisampling,e,this._width,this._height),s.bindFramebuffer(s.FRAMEBUFFER,this._frameBuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,this._renderBuffer),this._depth&&(s.bindFramebuffer(s.FRAMEBUFFER,this._frameBufferNoDepth),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,this._renderBuffer)),s.bindRenderbuffer(s.RENDERBUFFER,null)}const h=this._renderer._GetDepthBuffer();this._depth&&h&&(s.bindFramebuffer(s.FRAMEBUFFER,this._frameBuffer),this._renderer._CanSampleDepth()?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.TEXTURE_2D,h,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,h)),s.bindFramebuffer(s.FRAMEBUFFER,null),allRenderTargets.add(this)}_Resize(e,t){if(this._width===e&&this._height===t)return;this._width=e,this._height=t,this._CalculateProjection();const r=this._renderer.GetContext();r.bindFramebuffer(r.FRAMEBUFFER,this._frameBuffer),this._texture?this._texture._Update(new ImageData(this._width,this._height)):(r.bindRenderbuffer(r.RENDERBUFFER,this._renderBuffer),r.renderbufferStorage(r.RENDERBUFFER,this._alpha?r.RGBA8:r.RGB8,this._width,this._height),r.bindRenderbuffer(r.RENDERBUFFER,null));const i=this._renderer._GetDepthBuffer();this._depth&&i&&(this._renderer._CanSampleDepth()?r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,i,0):r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,i)),r.bindFramebuffer(r.FRAMEBUFFER,null)}_Delete(){if(!this._texture&&!this._renderBuffer)throw new Error("already deleted render target");allRenderTargets.delete(this);const e=this._renderer.GetContext();this._texture?(e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0),this._depth&&(e.bindFramebuffer(e.FRAMEBUFFER,this._frameBufferNoDepth),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)),this._renderer.DeleteTexture(this._texture),this._texture=null):this._renderBuffer&&(e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,null),this._depth&&(e.bindFramebuffer(e.FRAMEBUFFER,this._frameBufferNoDepth),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,null)),e.deleteRenderbuffer(this._renderBuffer),this._renderBuffer=null),e.bindFramebuffer(e.FRAMEBUFFER,null),this._renderer.GetWebGLVersionNumber()>=2&&(e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null)),e.deleteFramebuffer(this._frameBuffer),this._depth&&e.deleteFramebuffer(this._frameBufferNoDepth);const t=this._renderer.GetBatchState();t.currentFramebuffer=null,t.currentFramebufferNoDepth=null,this._frameBuffer=null}_CalculateProjection(){this._renderer.CalculatePerspectiveMatrix(this._projectionMatrix,this._width/this._height),this._lastFov=this._renderer.GetFovY(),this._lastNearZ=this._renderer.GetNearZ(),this._lastFarZ=this._renderer.GetFarZ()}_GetFramebuffer(){return this._frameBuffer}_GetFramebufferNoDepth(){return this._frameBufferNoDepth}GetRenderer(){return this._renderer}GetTexture(){return this._texture}GetProjectionMatrix(){return this._renderer.GetFovY()===this._lastFov&&this._renderer.GetNearZ()===this._lastNearZ&&this._renderer.GetFarZ()===this._lastFarZ||this._CalculateProjection(),this._projectionMatrix}IsLinearSampling(){return"nearest"!==this._sampling}HasAlpha(){return this._alpha}IsSampled(){return this._isSampled}HasDepthBuffer(){return this._depth}GetWidth(){return this._width}GetHeight(){return this._height}IsDefaultSize(){return this._isDefaultSize}GetMultisampling(){return this._multisampling}GetOptions(){const e={sampling:this._sampling,alpha:this._alpha,isSampled:this._isSampled};return this._isDefaultSize||(e.width=this._width,e.height=this._height),e}IsCompatibleWithOptions(e){return"nearest"!==(e=Object.assign({},DEFAULT_RENDERTARGET_OPTIONS,e)).sampling===this.IsLinearSampling()&&(!!e.alpha===this.HasAlpha()&&(!!e.depth===this.HasDepthBuffer()&&(!(this._renderer.GetWebGLVersionNumber()>=2&&!!e.isSampled!==this.IsSampled())&&("number"==typeof e.width||"number"==typeof e.height?!this.IsDefaultSize()&&this.GetWidth()===Math.floor(e.width)&&this.GetHeight()===Math.floor(e.height):this.IsDefaultSize()))))}_GetWebGLTexture(){return this._texture?this._texture._GetTexture():null}GetEstimatedMemoryUsage(){return this._texture?this._texture.GetEstimatedMemoryUsage():this._width*this._height*(this._alpha?4:3)}static async DebugReadPixelsToBlob(e,t){const r=await e.ReadBackRenderTargetToImageData(t,!0);return await C3.ImageDataToBlob(r)}static OnContextLost(){allRenderTargets.clear()}static allRenderTargets(){return allRenderTargets.values()}static ResizeAll(e,t){for(const r of allRenderTargets)r.IsDefaultSize()&&r._Resize(e,t)}};
}

// ../lib/gfx/webgl/shaderProgram.js
{
const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,mat4=glMatrix.mat4,RESERVED_UNIFORM_NAMES=new Set(["aPos","aTex","aPoints","matP","matMV","samplerFront","samplerBack","samplerDepth","destStart","destEnd","srcStart","srcEnd","srcOriginStart","srcOriginEnd","pixelSize","seconds","devicePixelRatio","layerScale","layerAngle","layoutStart","layoutEnd","color","color2_","pointTexStart","pointTexEnd","zElevation","tileSize","tileSpacing","outlineThickness","zNear","zFar"]);C3.Gfx.WebGLShaderProgram=class extends C3.Gfx.ShaderProgramBase{static async Compile(e,t){const i=e.GetContext(),r=t.src,o=t.vertexSrc,n=t.name,a=i.createShader(i.FRAGMENT_SHADER);i.shaderSource(a,r),i.compileShader(a);const l=i.createShader(i.VERTEX_SHADER);i.shaderSource(l,o),i.compileShader(l);const s=i.createProgram();i.attachShader(s,a),i.attachShader(s,l),i.bindAttribLocation(s,0,"aPos"),i.bindAttribLocation(s,1,"aTex"),i.bindAttribLocation(s,2,"aPoints"),i.linkProgram(s);const h=e._GetParallelShaderCompileExtension();if(h?await e._WaitForObjectReady((()=>i.getProgramParameter(s,h["COMPLETION_STATUS_KHR"]))):await C3.Wait(5),!i.getShaderParameter(a,i.COMPILE_STATUS)){const e=i.getShaderInfoLog(a);throw i.deleteShader(a),i.deleteShader(l),i.deleteProgram(s),new Error("Error compiling fragment shader: "+e)}if(!i.getShaderParameter(l,i.COMPILE_STATUS)){const e=i.getShaderInfoLog(l);throw i.deleteShader(a),i.deleteShader(l),i.deleteProgram(s),new Error("Error compiling vertex shader: "+e)}if(!i.getProgramParameter(s,i.LINK_STATUS)){const e=i.getProgramInfoLog(s);throw i.deleteShader(a),i.deleteShader(l),i.deleteProgram(s),new Error("Error linking shader program: "+e)}const c=C3.FilterUnprintableChars(i.getProgramInfoLog(s)||"").trim();return c&&!C3.IsStringAllWhitespace(c)&&console.info(`[WebGL] Shader program '${n}' compilation log: `,c),i.deleteShader(a),i.deleteShader(l),s}static async Create(e,t){const i=await C3.Gfx.WebGLShaderProgram.Compile(e,t);return new C3.Gfx.WebGLShaderProgram(e,i,t)}constructor(e,t,i){super(e,i);const r=e.GetContext(),o=e.GetBatchState();e.EndBatch(),r.useProgram(t),this._gl=r,this._shaderProgram=t,this._isDeviceTransform="<default-device-transform>"===i.name;const n=r.getAttribLocation(t,"aPos"),a=r.getAttribLocation(t,"aTex");this._locAPoints=r.getAttribLocation(t,"aPoints"),-1!==n&&(r.bindBuffer(r.ARRAY_BUFFER,e._vertexBuffer),r.vertexAttribPointer(n,e.GetNumVertexComponents(),r.FLOAT,!1,0,0),r.enableVertexAttribArray(n)),-1!==a&&(r.bindBuffer(r.ARRAY_BUFFER,e._texcoordBuffer),r.vertexAttribPointer(a,2,r.FLOAT,!1,0,0),r.enableVertexAttribArray(a)),-1!==this._locAPoints&&(r.bindBuffer(r.ARRAY_BUFFER,e._pointBuffer),r.vertexAttribPointer(this._locAPoints,4,r.FLOAT,!1,0,0),r.enableVertexAttribArray(this._locAPoints)),r.bindBuffer(r.ARRAY_BUFFER,null),this._uMatP=new C3.Gfx.WebGLShaderUniform(this,"matP","mat4"),this._uMatMV=new C3.Gfx.WebGLShaderUniform(this,"matMV","mat4"),this._uColor=new C3.Gfx.WebGLShaderUniform(this,"color","vec4"),this._uSamplerFront=new C3.Gfx.WebGLShaderUniform(this,"samplerFront","sampler"),this._uPointTexStart=new C3.Gfx.WebGLShaderUniform(this,"pointTexStart","vec2"),this._uPointTexEnd=new C3.Gfx.WebGLShaderUniform(this,"pointTexEnd","vec2"),this._uZElevation=new C3.Gfx.WebGLShaderUniform(this,"zElevation","float"),this._uTileSize=new C3.Gfx.WebGLShaderUniform(this,"tileSize","vec2"),this._uTileSpacing=new C3.Gfx.WebGLShaderUniform(this,"tileSpacing","vec2"),this._uColor2=new C3.Gfx.WebGLShaderUniform(this,"color2_","vec4"),this._uOutlineThickness=new C3.Gfx.WebGLShaderUniform(this,"outlineThickness","float"),this._uSamplerBack=new C3.Gfx.WebGLShaderUniform(this,"samplerBack","sampler"),this._uSamplerDepth=new C3.Gfx.WebGLShaderUniform(this,"samplerDepth","sampler"),this._uDestStart=new C3.Gfx.WebGLShaderUniform(this,"destStart","vec2"),this._uDestEnd=new C3.Gfx.WebGLShaderUniform(this,"destEnd","vec2"),this._uSrcStart=new C3.Gfx.WebGLShaderUniform(this,"srcStart","vec2"),this._uSrcEnd=new C3.Gfx.WebGLShaderUniform(this,"srcEnd","vec2"),this._uSrcOriginStart=new C3.Gfx.WebGLShaderUniform(this,"srcOriginStart","vec2"),this._uSrcOriginEnd=new C3.Gfx.WebGLShaderUniform(this,"srcOriginEnd","vec2"),this._uPixelSize=new C3.Gfx.WebGLShaderUniform(this,"pixelSize","vec2"),this._uSeconds=new C3.Gfx.WebGLShaderUniform(this,"seconds","float"),this._uDevicePixelRatio=new C3.Gfx.WebGLShaderUniform(this,"devicePixelRatio","float"),this._uLayerScale=new C3.Gfx.WebGLShaderUniform(this,"layerScale","float"),this._uLayerAngle=new C3.Gfx.WebGLShaderUniform(this,"layerAngle","float"),this._uLayoutStart=new C3.Gfx.WebGLShaderUniform(this,"layoutStart","vec2"),this._uLayoutEnd=new C3.Gfx.WebGLShaderUniform(this,"layoutEnd","vec2"),this._uZNear=new C3.Gfx.WebGLShaderUniform(this,"zNear","float"),this._uZFar=new C3.Gfx.WebGLShaderUniform(this,"zFar","float"),this._hasAnyOptionalUniforms=!!(this._uPixelSize.IsUsed()||this._uSeconds.IsUsed()||this._uSamplerBack.IsUsed()||this._uDestStart.IsUsed()||this._uDestEnd.IsUsed()||this._uSrcStart.IsUsed()||this._uSrcEnd.IsUsed()||this._uSrcOriginStart.IsUsed()||this._uSrcOriginEnd.IsUsed()||this._uDevicePixelRatio.IsUsed()||this._uLayerScale.IsUsed()||this._uLayerAngle.IsUsed()||this._uLayoutStart.IsUsed()||this._uLayoutEnd.IsUsed());const l=i.parameters||[];this._uCustomParameters=[],this._usesAnySrcRectOrPixelSize=this._uPixelSize.IsUsed()||this._uSrcStart.IsUsed()||this._uSrcEnd.IsUsed()||this._uSrcOriginStart.IsUsed()||this._uSrcOriginEnd.IsUsed(),this._hasCurrentMatP=!1,this._hasCurrentMatMV=!1,this._uColor.Init4f(1,1,1,1),this._uColor2.Init4f(1,1,1,1),this._uSamplerFront.Init1i(0),this._uSamplerBack.Init1i(1),this._uSamplerDepth.Init1i(2),this._uPointTexStart.Init2f(0,0),this._uPointTexEnd.Init2f(1,1),this._uZElevation.Init1f(0),this._uTileSize.Init2f(0,0),this._uTileSpacing.Init2f(0,0),this._uDestStart.Init2f(0,0),this._uDestEnd.Init2f(1,1),this._uSrcStart.Init2f(0,0),this._uSrcEnd.Init2f(0,0),this._uSrcOriginStart.Init2f(0,0),this._uSrcOriginEnd.Init2f(0,0),this._uPixelSize.Init2f(0,0),this._uDevicePixelRatio.Init1f(1),this._uZNear.Init1f(e.GetNearZ()),this._uZFar.Init1f(e.GetFarZ()),this._uLayerScale.Init1f(1),this._uLayerAngle.Init1f(0),this._uSeconds.Init1f(0),this._uLayoutStart.Init2f(0,0),this._uLayoutEnd.Init2f(0,0),this._uOutlineThickness.Init1f(1);for(const e of l){const t=e[0],i=e[2],r=new C3.Gfx.WebGLShaderUniform(this,t,i);"color"===i?r.Init3f(0,0,0):r.Init1f(0),this._uCustomParameters.push(r)}this._isDeviceTransform?this._UpdateDeviceTransformUniforms(o.currentMatP):(this.UpdateMatP(o.currentMatP,!0),this.UpdateMatMV(o.currentMV,!0));const s=o.currentShader;r.useProgram(s?s._shaderProgram:null)}Release(){this._gl.deleteProgram(this._shaderProgram),this._shaderProgram=null,this._renderer._RemoveShaderProgram(this),this._gl=null,super.Release()}GetWebGLContext(){return this._gl}GetShaderProgram(){return this._shaderProgram}GetParameterCount(){return this._uCustomParameters.length}GetParameterType(e){return e<0||e>=this._uCustomParameters.length?null:this._uCustomParameters[e].GetType()}AreCustomParametersAlreadySetInBatch(e){for(let t=0,i=e.length;t<i;++t)if(!this._uCustomParameters[t].IsSetToCustomInBatch(e[t]))return!1;return!0}SetCustomParametersInBatch(e){for(let t=0,i=e.length;t<i;++t)this._uCustomParameters[t].SetBatchValueCustom(e[t])}AreOptionalUniformsAlreadySetInBatch(e,t,i,r,o,n,a,l,s,h){return!this._uSamplerBack.IsUsed()&&(!(this._uPixelSize.IsUsed()&&!this._uPixelSize.IsSetTo2InBatch(o,n))&&(!(this._uDestStart.IsUsed()&&!this._uDestStart.IsSetTo2InBatch(e.getLeft(),e.getTop()))&&(!(this._uDestEnd.IsUsed()&&!this._uDestEnd.IsSetTo2InBatch(e.getRight(),e.getBottom()))&&(!(this._uDevicePixelRatio.IsUsed()&&!this._uDevicePixelRatio.IsSetTo1InBatch(a))&&(!(this._uLayerScale.IsUsed()&&!this._uLayerScale.IsSetTo1InBatch(l))&&(!(this._uLayerAngle.IsUsed()&&!this._uLayerAngle.IsSetTo1InBatch(s))&&(!(this._uSrcStart.IsUsed()&&!this._uSrcStart.IsSetTo2InBatch(t.getLeft(),t.getTop()))&&(!(this._uSrcEnd.IsUsed()&&!this._uSrcEnd.IsSetTo2InBatch(t.getRight(),t.getBottom()))&&(!(this._uSrcOriginStart.IsUsed()&&!this._uSrcOriginStart.IsSetTo2InBatch(i.getLeft(),i.getTop()))&&(!(this._uSrcOriginEnd.IsUsed()&&!this._uSrcOriginEnd.IsSetTo2InBatch(i.getRight(),i.getBottom()))&&(!(this._uLayoutStart.IsUsed()&&!this._uLayoutStart.IsSetTo2InBatch(r.getLeft(),r.getTop()))&&(!(this._uLayoutEnd.IsUsed()&&!this._uLayoutEnd.IsSetTo2InBatch(r.getTop(),r.getBottom()))&&!(this._uSeconds.IsUsed()&&!this._uSeconds.IsSetTo1InBatch(h))))))))))))))}SetOptionalUniformsInBatch(e,t,i,r,o,n,a,l,s,h){this._uSamplerBack.IsUsed()||(this._uPixelSize.IsUsed()&&this._uPixelSize.SetBatch2(o,n),this._uDestStart.IsUsed()&&this._uDestStart.SetBatch2(e.getLeft(),e.getTop()),this._uDestEnd.IsUsed()&&this._uDestEnd.SetBatch2(e.getRight(),e.getBottom()),this._uDevicePixelRatio.IsUsed()&&this._uDevicePixelRatio.SetBatch1(a),this._uLayerScale.IsUsed()&&this._uLayerScale.SetBatch1(l),this._uLayerAngle.IsUsed()&&this._uLayerAngle.SetBatch1(s),this._uSrcStart.IsUsed()&&this._uSrcStart.SetBatch2(t.getLeft(),t.getTop()),this._uSrcEnd.IsUsed()&&this._uSrcEnd.SetBatch2(t.getRight(),t.getBottom()),this._uSrcOriginStart.IsUsed()&&this._uSrcOriginStart.SetBatch2(i.getLeft(),i.getTop()),this._uSrcOriginEnd.IsUsed()&&this._uSrcOriginEnd.SetBatch2(i.getRight(),i.getBottom()),this._uLayoutStart.IsUsed()&&this._uLayoutStart.SetBatch2(r.getLeft(),r.getTop()),this._uLayoutEnd.IsUsed()&&this._uLayoutEnd.SetBatch2(r.getTop(),r.getBottom()),this._uSeconds.IsUsed()&&this._uSeconds.SetBatch1(h))}UpdateMatP(e,t){this._hasCurrentMatP&&!t||this._isDeviceTransform||(this._uMatP.IsUsed()&&this._uMatP.UpdateMatrix4fv(e),this._hasCurrentMatP=!0)}SetMatPStale(){this._hasCurrentMatP=!1}UpdateMatMV(e,t){this._hasCurrentMatMV&&!t||this._isDeviceTransform||(this._uMatMV.IsUsed()&&this._uMatMV.UpdateMatrix4fv(e),this._hasCurrentMatMV=!0)}SetMatMVStale(){this._hasCurrentMatMV=!1}_UpdateDeviceTransformUniforms(e){if(!this._isDeviceTransform)throw new Error("not device transform shader");this._uMatP.UpdateMatrix4fv(e);const t=this._renderer,i=t.GetWidth()/2,r=t.GetHeight()/2,o=t.CalculateLookAtModelView2(i,r,t.GetDefaultCameraZ(t.GetHeight()),i,r,0,t.GetHeight());this._uMatMV.UpdateMatrix4fv(o)}UpdateColor(e){this._uColor.IsUsed()&&this._uColor.Update4f(e[0],e[1],e[2],e[3])}static GetReservedUniformNames(){return RESERVED_UNIFORM_NAMES}static _GetConservativeDepthShaderPrefix(e){return e?"\n#extension GL_EXT_conservative_depth : enable\nlayout (depth_greater) out highp float gl_FragDepth;\n\t":""}static GetDefaultVertexShaderSource(e){const t=e?"highp":"mediump";return["attribute highp vec3 aPos;",`attribute ${t} vec2 aTex;`,`varying ${t} vec2 vTex;`,"uniform highp mat4 matP;","uniform highp mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPos, 1.0);","\tvTex = aTex;","}"].join("\n")}static GetDefaultVertexShaderSource_WebGL2(e){const t=e?"highp":"mediump";return["#version 300 es","in highp vec3 aPos;",`in ${t} vec2 aTex;`,`out ${t} vec2 vTex;`,"uniform highp mat4 matP;","uniform highp mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPos, 1.0);","\tvTex = aTex;","}"].join("\n")}static GetTextureFillFragmentShaderSource_WebGL1_NoFragDepth(){return["varying mediump vec2 vTex;","uniform lowp vec4 color;","uniform lowp sampler2D samplerFront;","void main(void) {","\tgl_FragColor = texture2D(samplerFront, vTex) * color;","}"].join("\n")}static GetTextureFillFragmentShaderSource_WebGL1_FragDepthEXT(){return["#extension GL_EXT_frag_depth : enable","varying mediump vec2 vTex;","uniform lowp vec4 color;","uniform lowp sampler2D samplerFront;","void main(void) {","\tgl_FragColor = texture2D(samplerFront, vTex) * color;","\tgl_FragDepthEXT = (gl_FragColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetTextureFillFragmentShaderSource_WebGL2(e){return["#version 300 es",C3.Gfx.WebGLShaderProgram._GetConservativeDepthShaderPrefix(e),"in mediump vec2 vTex;","out lowp vec4 outColor;","uniform lowp vec4 color;","uniform lowp sampler2D samplerFront;","void main(void) {","\toutColor = texture(samplerFront, vTex) * color;","\tgl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetTilemapFragmentShaderSource_WebGL1_NoFragDepth(){return["varying highp vec2 vTex;","uniform lowp vec4 color;","uniform lowp sampler2D samplerFront;","uniform highp vec2 srcStart;","uniform highp vec2 pixelSize;","uniform highp vec2 tileSize;","uniform highp vec2 tileSpacing;","void main(void) {","\thighp vec2 tile = floor(vTex);","\thighp vec2 tex = fract(vTex);","\thighp vec2 tileOrigin = srcStart + tile * (tileSize + tileSpacing);","\thighp vec2 lowerBound = tileOrigin + pixelSize / 2.0;","\thighp vec2 upperBound = tileOrigin + tileSize - pixelSize / 2.0;","\tgl_FragColor = texture2D(samplerFront, clamp(tex, lowerBound, upperBound), -16.0) * color;","}"].join("\n")}static GetTilemapFragmentShaderSource_WebGL1_FragDepthEXT(){return["#extension GL_EXT_frag_depth : enable","varying highp vec2 vTex;","uniform lowp vec4 color;","uniform lowp sampler2D samplerFront;","uniform highp vec2 srcStart;","uniform highp vec2 pixelSize;","uniform highp vec2 tileSize;","uniform highp vec2 tileSpacing;","void main(void) {","\thighp vec2 tile = floor(vTex);","\thighp vec2 tex = fract(vTex);","\thighp vec2 tileOrigin = srcStart + tile * (tileSize + tileSpacing);","\thighp vec2 lowerBound = tileOrigin + pixelSize / 2.0;","\thighp vec2 upperBound = tileOrigin + tileSize - pixelSize / 2.0;","\tgl_FragColor = texture2D(samplerFront, clamp(tex, lowerBound, upperBound), -16.0) * color;","\tgl_FragDepthEXT = (gl_FragColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetTilemapFragmentShaderSource_WebGL2(e){return["#version 300 es",C3.Gfx.WebGLShaderProgram._GetConservativeDepthShaderPrefix(e),"in highp vec2 vTex;","out lowp vec4 outColor;","uniform lowp vec4 color;","uniform lowp sampler2D samplerFront;","uniform highp vec2 srcStart;","uniform highp vec2 pixelSize;","uniform highp vec2 tileSize;","uniform highp vec2 tileSpacing;","void main(void) {","\thighp vec2 tile = floor(vTex);","\thighp vec2 tex = fract(vTex);","\thighp vec2 tileOrigin = srcStart + tile * (tileSize + tileSpacing);","\thighp vec2 lowerBound = tileOrigin + pixelSize / 2.0;","\thighp vec2 upperBound = tileOrigin + tileSize - pixelSize / 2.0;","\toutColor = texture(samplerFront, clamp(tex, lowerBound, upperBound), -16.0) * color;","\tgl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetTileRandomizationFragmentShaderSource(e,t,i,r){let o="";return e>=2?o="#version 300 es\n"+C3.Gfx.WebGLShaderProgram._GetConservativeDepthShaderPrefix(r):(t&&(o="#extension GL_EXT_frag_depth : enable\n"),i&&(o+="#extension GL_EXT_shader_texture_lod : enable\n",o+="#extension GL_OES_standard_derivatives : enable\n")),o+`\nprecision highp float;\n${e>=2?"in":"varying"} vec2 vTex;\n${e>=2?"out lowp vec4 outColor;":""}\nuniform lowp vec4 color;\nuniform lowp sampler2D samplerFront;\nuniform vec2 pixelSize;\n\nuniform vec2 tileSize;\nuniform vec2 tileSpacing;\nuniform float outlineThickness;\n\nconst float PI = 3.1415926;\n\nlowp vec4 cospVec4(lowp vec4 a, lowp vec4 b, float x)\n{\n\treturn (a + b + (a - b) * cos(x * PI)) / 2.0;\n}\n\nvec3 randVec3(vec2 seed)\n{\n\treturn vec3(fract(sin(dot(seed.xy + vec2(0.1, 0.1), vec2(12.9898,78.233))) * 43758.5453),\n\t\t\t\tfract(sin(dot(seed.yx + vec2(0.1, 0.1), vec2(12.9898,-78.233))) * 43758.5453),\n\t\t\t\tfract(sin(dot(seed.xy + vec2(0.1, 0.1), vec2(-12.9898,-78.233))) * 43758.5453));\n}\n\nlowp vec4 sampleTile(vec2 tile, vec2 uv, vec2 ddx, vec2 ddy)\n{\n\tvec2 posRandom = tileSize;\n\tfloat angleRandom = outlineThickness;\n\t\n\tvec3 rand = (randVec3(floor(tile + 0.5)) - 0.5) * 2.0;\n\t\n\tfloat angle = angleRandom * rand.z * PI;\n\tfloat sin_a = sin(angle);\n\tfloat cos_a = cos(angle);\n\tfloat aspect = pixelSize.x / pixelSize.y;\n\n\tvec2 mid = tile + vec2(0.5, 0.5);\n\tvec2 dp = uv - mid;\n\tdp.x /= aspect;\n\tvec2 r = vec2(dp.x * cos_a - dp.y * sin_a,\n\t\t\t\t  dp.y * cos_a + dp.x * sin_a);\n\tr.x *= aspect;\n\n\tvec2 p = mid + r + (posRandom * rand.xy / 2.0);\n\t\n\t${e>=2?"return textureGrad(samplerFront, p, ddx, ddy);":""}\n\t${e<2&&i?"return texture2DGradEXT(samplerFront, p, ddx, ddy);":""}\n\t${e<2&&!i?"return texture2D(samplerFront, p);":""}\n}\n\nvoid main(void) {\n\t\n\t${e<2?"lowp vec4 outColor;":""}\n\t\n\tfloat blendMarginX = tileSpacing.x;\n\tfloat blendMarginY = tileSpacing.y;\n\t\n\tvec2 tile = floor(vTex);\n\tvec2 tex = fract(vTex);\n\tvec2 ddx = ${e>=2||i?"dFdx(vTex)":"vec2(0.0, 0.0)"};\n\tvec2 ddy = ${e>=2||i?"dFdy(vTex)":"vec2(0.0, 0.0)"};\n\t\n\tvec4 curTile = sampleTile(tile, vTex, ddx, ddy);\n\t\n\tbool inLeftMargin = (tex.x < blendMarginX);\n\tbool inRightMargin = (tex.x > 1.0 - blendMarginX);\n\tbool inTopMargin = (tex.y < blendMarginY);\n\tbool inBottomMargin = (tex.y > 1.0 - blendMarginY);\n\t\n\tif (inLeftMargin)\n\t{\n\t\tlowp vec4 leftTile = sampleTile(tile + vec2(-1.0, 0.0), vTex, ddx, ddy);\n\t\tfloat leftMix = (tex.x / (blendMarginX * 2.0)) + 0.5;\n\t\tlowp vec4 leftMixedTile = cospVec4(leftTile, curTile, leftMix);\n\t\t\n\t\tif (inTopMargin)\n\t\t{\n\t\t\tlowp vec4 topTile =     sampleTile(tile + vec2(0.0,  -1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 topLeftTile = sampleTile(tile + vec2(-1.0, -1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 topLeftMixedTile = cospVec4(topLeftTile, topTile, leftMix);\n\t\t\t\n\t\t\toutColor = cospVec4(topLeftMixedTile, leftMixedTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t\t}\n\t\telse if (inBottomMargin)\n\t\t{\n\t\t\tlowp vec4 bottomTile =     sampleTile(tile + vec2(0.0,  1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 bottomLeftTile = sampleTile(tile + vec2(-1.0, 1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 bottomLeftMixedTile = cospVec4(bottomLeftTile, bottomTile, leftMix);\n\t\t\t\n\t\t\toutColor = cospVec4(leftMixedTile, bottomLeftMixedTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t\t}\n\t\telse\n\t\t{\n\t\t\toutColor = leftMixedTile;\n\t\t}\n\t}\n\telse if (inRightMargin)\n\t{\n\t\tlowp vec4 rightTile = sampleTile(tile + vec2(1.0, 0.0), vTex, ddx, ddy);\n\t\tfloat rightMix = (tex.x - (1.0 - blendMarginX)) / (blendMarginX * 2.0);\n\t\tlowp vec4 rightMixedTile = cospVec4(curTile, rightTile, rightMix);\n\t\t\n\t\tif (inTopMargin)\n\t\t{\n\t\t\tlowp vec4 topTile =      sampleTile(tile + vec2(0.0, -1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 topRightTile = sampleTile(tile + vec2(1.0, -1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 topRightMixedTile = cospVec4(topTile, topRightTile, rightMix);\n\t\t\t\n\t\t\toutColor = cospVec4(topRightMixedTile, rightMixedTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t\t}\n\t\telse if (inBottomMargin)\n\t\t{\n\t\t\tlowp vec4 bottomTile =      sampleTile(tile + vec2(0.0, 1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 bottomRightTile = sampleTile(tile + vec2(1.0, 1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 bottomRightMixedTile = cospVec4(bottomTile, bottomRightTile, rightMix);\n\t\t\t\n\t\t\toutColor = cospVec4(rightMixedTile, bottomRightMixedTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t\t}\n\t\telse\n\t\t{\n\t\t\toutColor = rightMixedTile;\n\t\t}\n\t}\n\telse if (inTopMargin)\n\t{\n\t\tlowp vec4 topTile = sampleTile(tile + vec2(0.0, -1.0), vTex, ddx, ddy);\n\t\toutColor = cospVec4(topTile, curTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t}\n\telse if (inBottomMargin)\n\t{\n\t\tlowp vec4 bottomTile = sampleTile(tile + vec2(0.0, 1.0), vTex, ddx, ddy);\n\t\toutColor = cospVec4(curTile, bottomTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t}\n\telse\n\t{\n\t\toutColor = curTile;\n\t}\n\t\n\toutColor *= color;\n\t${e<2?"gl_FragColor = outColor;":""}\n\t${e>=2?"gl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);":""}\n\t${e<2&&t?"gl_FragDepthEXT = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);":""}\n}\n`}static GetPointVertexShaderSource_WebGL1(){return["attribute vec4 aPoints;","varying float pointOpacity;","uniform float zElevation;","uniform mat4 matP;","uniform mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPoints.xy, zElevation, 1.0);","\tgl_PointSize = aPoints.z;","\tpointOpacity = aPoints.w;","}"].join("\n")}static GetPointVertexShaderSource_WebGL2(){return["#version 300 es","in vec4 aPoints;","out float pointOpacity;","uniform float zElevation;","uniform mat4 matP;","uniform mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPoints.xy, zElevation, 1.0);","\tgl_PointSize = aPoints.z;","\tpointOpacity = aPoints.w;","}"].join("\n")}static GetPointFragmentShaderSource_WebGL1_NoFragDepth(){return["uniform lowp sampler2D samplerFront;","varying lowp float pointOpacity;","uniform mediump vec2 pointTexStart;","uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);","\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));","\tgl_FragColor = texture2D(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","}"].join("\n")}static GetPointFragmentShaderSource_WebGL1_FragDepthEXT(){return["#extension GL_EXT_frag_depth : enable","uniform lowp sampler2D samplerFront;","varying lowp float pointOpacity;","uniform mediump vec2 pointTexStart;","uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);","\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));","\tgl_FragColor = texture2D(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","\tgl_FragDepthEXT = (gl_FragColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetPointFragmentShaderSource_WebGL2(e){return["#version 300 es",C3.Gfx.WebGLShaderProgram._GetConservativeDepthShaderPrefix(e),"uniform lowp sampler2D samplerFront;","in lowp float pointOpacity;","uniform mediump vec2 pointTexStart;","uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","out lowp vec4 outColor;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);","\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));","\toutColor = texture(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","\tgl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetColorFillFragmentShaderSource(){return["uniform lowp vec4 color;","void main(void) {","\tgl_FragColor = color;","}"].join("\n")}static GetLinearGradientFillFragmentShaderSource(){return["precision lowp float;","varying mediump vec2 vTex;","uniform vec4 color;","uniform vec4 color2_;","vec3 fromLinear(vec3 linearRGB)","{","\tbvec3 cutoff = lessThan(linearRGB, vec3(0.0031308));","\tvec3 higher = vec3(1.055) * pow(abs(linearRGB), vec3(1.0/2.4)) - vec3(0.055);","\tvec3 lower = linearRGB * vec3(12.92);","\treturn mix(higher, lower, vec3(cutoff));","}","vec3 toLinear(vec3 sRGB)","{","\tbvec3 cutoff = lessThan(sRGB, vec3(0.04045));","\tvec3 higher = pow(abs((sRGB + vec3(0.055))/vec3(1.055)), vec3(2.4));","\tvec3 lower = sRGB/vec3(12.92);","\treturn mix(higher, lower, vec3(cutoff));","}","void main(void) {","\tvec3 linearGrad = mix(toLinear(color.rgb), toLinear(color2_.rgb), vTex.x);","\tfloat a = mix(color.a, color2_.a, vTex.x);","\tgl_FragColor = vec4(fromLinear(linearGrad) * a, a);","}"].join("\n")}static GetPenumbraFillFragmentShaderSource(){return["precision lowp float;","varying highp vec2 vTex;","uniform vec4 color;","void main(void) {","\thighp float grad = vTex.x / (1.0 - vTex.y);","\tgl_FragColor = color * (1.0 - (cos(grad * 3.141592653589793) + 1.0) / 2.0);","}"].join("\n")}static GetSmoothLineFillFragmentShaderSource(){return["varying mediump vec2 vTex;","uniform lowp vec4 color;","void main(void) {","\tlowp float f = 1.0 - abs(vTex.y - 0.5) * 2.0;","\tgl_FragColor = color * f;","}"].join("\n")}static GetHardEllipseFillFragmentShaderSource(){return["varying highp vec2 vTex;","uniform lowp vec4 color;","void main(void) {","\thighp vec2 diff = vTex - vec2(0.5, 0.5);","\thighp vec2 diffSq = diff * diff;","\thighp float f = step(diffSq.x + diffSq.y, 0.25);","\tgl_FragColor = color * f;","}"].join("\n")}static GetHardEllipseOutlineFragmentShaderSource(){return["varying highp vec2 vTex;","uniform lowp vec4 color;","uniform highp vec2 pixelSize;","uniform highp float outlineThickness;","void main(void) {","\thighp vec2 diff = vTex - vec2(0.5, 0.5);","\thighp vec2 diffSq = diff * diff;","\thighp float distSq = diffSq.x + diffSq.y;","\thighp vec2 norm = normalize(diff);","\thighp vec2 halfNorm = norm * 0.5;","\thighp float innerF = step(distSq, 0.25);","\thighp vec2 innerEdge = halfNorm - pixelSize * norm * outlineThickness;","\thighp vec2 innerEdgeSq = innerEdge * innerEdge;","\thighp float outerF = step(innerEdgeSq.x + innerEdgeSq.y, distSq);","\tgl_FragColor = color * innerF * outerF;","}"].join("\n")}static GetSmoothEllipseFillFragmentShaderSource(){return["varying highp vec2 vTex;","uniform lowp vec4 color;","uniform highp vec2 pixelSize;","void main(void) {","\thighp vec2 diff = vTex - vec2(0.5, 0.5);","\thighp vec2 diffSq = diff * diff;","\thighp vec2 norm = normalize(diff);","\thighp vec2 halfNorm = norm * 0.5;","\thighp vec2 halfNormSq = halfNorm * halfNorm;","\thighp vec2 innerEdge = halfNorm - pixelSize * norm;","\thighp vec2 innerEdgeSq = innerEdge * innerEdge;","\thighp float f = smoothstep(halfNormSq.x + halfNormSq.y, innerEdgeSq.x + innerEdgeSq.y, diffSq.x + diffSq.y);","\tgl_FragColor = color * f;","}"].join("\n")}static GetSmoothEllipseOutlineFragmentShaderSource(){return["varying highp vec2 vTex;","uniform lowp vec4 color;","uniform highp vec2 pixelSize;","uniform highp float outlineThickness;","void main(void) {","\thighp vec2 diff = vTex - vec2(0.5, 0.5);","\thighp vec2 diffSq = diff * diff;","\thighp float distSq = diffSq.x + diffSq.y;","\thighp vec2 norm = normalize(diff);","\thighp vec2 halfNorm = norm * 0.5;","\thighp vec2 halfNormSq = halfNorm * halfNorm;","\thighp vec2 pxNorm = pixelSize * norm;","\thighp vec2 innerEdge1 = halfNorm - pxNorm;","\thighp vec2 innerEdge1Sq = innerEdge1 * innerEdge1;","\thighp float innerF = smoothstep(halfNormSq.x + halfNormSq.y, innerEdge1Sq.x + innerEdge1Sq.y, distSq);","\thighp vec2 innerEdge2 = halfNorm - pxNorm * outlineThickness;","\thighp vec2 innerEdge2Sq = innerEdge2 * innerEdge2;","\thighp vec2 innerEdge3 = halfNorm - pxNorm * (outlineThickness + 1.0);","\thighp vec2 innerEdge3Sq = innerEdge3 * innerEdge3;","\thighp float outerF = smoothstep(innerEdge3Sq.x + innerEdge3Sq.y, innerEdge2Sq.x + innerEdge2Sq.y, distSq);","\tgl_FragColor = color * innerF * outerF;","}"].join("\n")}};
}

// ../lib/gfx/webgl/shaderUniform.js
{
const C3=self.C3,glMatrix=self.glMatrix,mat4=glMatrix.mat4,TYPE_SIZES=new Map([["float",1],["percent",1],["sampler",1],["vec2",2],["vec3",3],["color",3],["vec4",4],["mat4",16]]);C3.Gfx.WebGLShaderUniform=class{constructor(t,s,a){if(!TYPE_SIZES.has(a))throw new Error("invalid uniform type");this._owner=t,this._gl=this._owner.GetWebGLContext(),this._name=s,this._type=a,this._isColorType="color"===this._type,this._location=this._gl.getUniformLocation(this._owner.GetShaderProgram(),s),this._isUsed=!!this._location;const i=TYPE_SIZES.get(a);this._lastValue=new Float32Array(i),this._lastBatchValue=new Float32Array(i)}Release(){this._owner=null,this._gl=null,this._location=null}IsUsed(){return this._isUsed}GetType(){return this._type}IsColorType(){return this._isColorType}Init1f(t){this.IsUsed()&&(this._lastValue[0]=t,this._lastBatchValue.set(this._lastValue),this._gl.uniform1f(this._location,t))}Init1i(t){this.IsUsed()&&(this._lastValue[0]=t,this._lastBatchValue.set(this._lastValue),this._gl.uniform1i(this._location,t))}Init2f(t,s){this.IsUsed()&&(this._lastValue[0]=t,this._lastValue[1]=s,this._lastBatchValue.set(this._lastValue),this._gl.uniform2f(this._location,t,s))}Init3f(t,s,a){this.IsUsed()&&(this._lastValue[0]=t,this._lastValue[1]=s,this._lastValue[2]=a,this._lastBatchValue.set(this._lastValue),this._gl.uniform3f(this._location,t,s,a))}Init4f(t,s,a,i){this.IsUsed()&&(this._lastValue[0]=t,this._lastValue[1]=s,this._lastValue[2]=a,this._lastValue[3]=i,this._lastBatchValue.set(this._lastValue),this._gl.uniform4f(this._location,t,s,a,i))}Update1f(t){t=Math.fround(t);const s=this._lastValue;s[0]!==t&&(s[0]=t,this._gl.uniform1f(this._location,t))}Update1i(t){const s=this._lastValue;s[0]!==t&&(s[0]=t,this._gl.uniform1i(this._location,t))}Update2f(t,s){t=Math.fround(t),s=Math.fround(s);const a=this._lastValue;a[0]===t&&a[1]===s||(a[0]=t,a[1]=s,this._gl.uniform2f(this._location,t,s))}Update3f(t,s,a){t=Math.fround(t),s=Math.fround(s),a=Math.fround(a);const i=this._lastValue;i[0]===t&&i[1]===s&&i[2]===a||(i[0]=t,i[1]=s,i[2]=a,this._gl.uniform3f(this._location,t,s,a))}Update4f(t,s,a,i){t=Math.fround(t),s=Math.fround(s),a=Math.fround(a),i=Math.fround(i);const l=this._lastValue;l[0]===t&&l[1]===s&&l[2]===a&&l[3]===i||(l[0]=t,l[1]=s,l[2]=a,l[3]=i,this._gl.uniform4f(this._location,t,s,a,i))}UpdateMatrix4fv(t){const s=this._lastValue;mat4.exactEquals(s,t)||(C3.typedArraySet16(s,t,0),this._gl.uniformMatrix4fv(this._location,!1,t))}IsSetToCustomInBatch(t){const s=this._lastBatchValue;return this.IsColorType()?s[0]===Math.fround(t.getR())&&s[1]===Math.fround(t.getG())&&s[2]===Math.fround(t.getB()):s[0]===Math.fround(t)}SetBatchValueCustom(t){const s=this._lastBatchValue;this.IsColorType()?(s[0]=t.getR(),s[1]=t.getG(),s[2]=t.getB()):s[0]=t}IsSetTo1InBatch(t){return this._lastBatchValue[0]===Math.fround(t)}IsSetTo2InBatch(t,s){const a=this._lastBatchValue;return a[0]===Math.fround(t)&&a[1]===Math.fround(s)}SetBatch1(t){this._lastBatchValue[0]=t}SetBatch2(t,s){const a=this._lastBatchValue;a[0]=t,a[1]=s}};
}

// ../lib/gfx/webgl/batchJob.js
{
const C3=self.C3,glMatrix=self.glMatrix,vec4=glMatrix.vec4,mat4=glMatrix.mat4,BATCH_NULL=0,BATCH_QUAD=1,BATCH_SETTEXTURE=2,BATCH_SETCOLOR=3,BATCH_SETBLEND=4,BATCH_SETVIEWPORT=5,BATCH_SETPROJECTION=6,BATCH_SETMODELVIEW=7,BATCH_SETRENDERTARGET=8,BATCH_CLEARSURFACE=9,BATCH_POINTS=10,BATCH_SETPROGRAM=11,BATCH_SETPROGRAMPARAMETERS=12,BATCH_SETPROGRAMCUSTOMPARAMETERS=13,BATCH_INVALIDATEFRAMEBUFFER=14,BATCH_SETPOINTTEXCOORDS=15,BATCH_SETTILEMAPINFO=16,BATCH_BLITFRAMEBUFFER=17,BATCH_STARTQUERY=18,BATCH_ENDQUERY=19,BATCH_SETELLIPSEPARAMS=20,BATCH_SETGRADIENTCOLOR=21,BATCH_CLEARDEPTH=22,BATCH_SETDEPTHENABLED=23,BATCH_SETDEPTHSAMPLINGENABLED=24,BATCH_COPLANAR_STARTSTENCILPASS=25,BATCH_COPLANAR_STARTCOLORPASS=26,BATCH_COPLANAR_RESTORE=27,BATCH_SET_SCISSOR=28,BATCH_SETTILERANDOMIZATIONINFO=29;C3.Gfx.BatchState=class{constructor(t){this.renderer=t,this.currentMV=mat4.create(),this.currentMatP=mat4.create(),this.currentFramebuffer=null,this.currentFramebufferNoDepth=null,this.isDepthSamplingEnabled=!1,this.currentColor=vec4.fromValues(1,1,1,1),this.currentShader=null,this.pointTexCoords=new C3.Rect,this.clearColor=C3.New(C3.Color,0,0,0,0)}},C3.Gfx.WebGLBatchJob=class{constructor(t){const e=new ArrayBuffer(96);this._type=0,this._batchState=t,this._gl=t.renderer.GetContext(),this._startIndex=0,this._indexCount=0,this._texParam=null,this._mat4param=new Float32Array(e,0,16),this._colorParam=new Float32Array(e,64,4),this._srcOriginRect=new Float32Array(e,80,4),this._shaderParams=[]}InitQuad(t,e){this._type=1,this._startIndex=t,this._indexCount=e}DoQuad(){const t=this._gl;t.drawElements(t.TRIANGLES,this._indexCount,t.UNSIGNED_SHORT,this._startIndex)}InitSetTexture(t){this._type=2,this._texParam=t}DoSetTexture(){const t=this._gl,e=this._texParam;t.bindTexture(t.TEXTURE_2D,e?e._GetTexture():null)}InitSetColor(t){this._type=3,t.writeToTypedArray(this._colorParam,0)}DoSetColor(){const t=this._colorParam,e=this._batchState;vec4.copy(e.currentColor,t),e.currentShader.UpdateColor(t)}InitSetGradientColor(t){this._type=21,t.writeToTypedArray(this._colorParam,0)}DoSetGradientColor(){const t=this._colorParam,e=this._batchState.currentShader;e._uColor2.IsUsed()&&e._uColor2.Update4f(t[0],t[1],t[2],t[3])}InitSetBlend(t,e){this._type=4,this._startIndex=t,this._indexCount=e}DoSetBlend(){this._gl.blendFunc(this._startIndex,this._indexCount)}InitSetViewport(t,e,r,a){this._type=5;const s=this._colorParam;s[0]=t,s[1]=e,s[2]=r,s[3]=a}DoSetViewport(){const t=this._colorParam;this._gl.viewport(t[0],t[1],t[2],t[3])}InitSetProjection(t){this._type=6,mat4.copy(this._mat4param,t)}DoSetProjection(){const t=this._batchState,e=t.renderer._allShaderPrograms,r=t.currentShader,a=this._mat4param;for(let t=0,s=e.length;t<s;++t){const s=e[t];s===r?s.UpdateMatP(a,!0):s.SetMatPStale()}mat4.copy(t.currentMatP,a)}InitSetModelView(t){this._type=7,mat4.copy(this._mat4param,t)}DoSetModelView(){const t=this._batchState,e=t.renderer._allShaderPrograms,r=t.currentShader,a=this._mat4param;for(let t=0,s=e.length;t<s;++t){const s=e[t];s===r?s.UpdateMatMV(a,!0):s.SetMatMVStale()}mat4.copy(t.currentMV,a)}InitSetRenderTarget(t){this._type=8,this._texParam=t}DoSetRenderTarget(){const t=this._gl,e=this._texParam,r=this._batchState;e?(r.currentFramebuffer=e._GetFramebuffer(),r.currentFramebufferNoDepth=e._GetFramebufferNoDepth(),r.isDepthSamplingEnabled&&r.currentFramebufferNoDepth?t.bindFramebuffer(t.FRAMEBUFFER,r.currentFramebufferNoDepth):t.bindFramebuffer(t.FRAMEBUFFER,r.currentFramebuffer)):(r.currentFramebuffer=null,r.currentFramebufferNoDepth=null,t.bindFramebuffer(t.FRAMEBUFFER,null))}InitClearSurface(t){this._type=9,t.writeToTypedArray(this._mat4param,0)}InitClearSurface2(t,e,r,a){this._type=9;const s=this._mat4param;s[0]=t,s[1]=e,s[2]=r,s[3]=a}DoClearSurface(){const t=this._gl,e=this._mat4param,r=this._batchState.clearColor,a=e[0],s=e[1],i=e[2],n=e[3];r.equalsRgba(a,s,i,n)||(t.clearColor(a,s,i,n),r.setRgba(a,s,i,n)),t.clear(t.COLOR_BUFFER_BIT)}InitSetPointTexCoords(t){this._type=15,t.writeToTypedArray(this._mat4param,0)}DoSetPointTextureCoords(){const t=this._mat4param;this._batchState.pointTexCoords.set(t[0],t[1],t[2],t[3])}InitPoints(t,e){this._type=10,this._startIndex=t,this._indexCount=1,this._mat4param[0]=e}DoPoints(){const t=this._gl,e=this._batchState,r=e.renderer._spPoints;t.useProgram(r._shaderProgram),r.UpdateMatP(e.currentMatP,!1),r.UpdateMatMV(e.currentMV,!1);const a=e.pointTexCoords;r._uPointTexStart.IsUsed()&&r._uPointTexStart.Update2f(a.getLeft(),a.getTop()),r._uPointTexEnd.IsUsed()&&r._uPointTexEnd.Update2f(a.getRight(),a.getBottom());const s=this._mat4param[0];if(r._uZElevation.IsUsed()&&r._uZElevation.Update1f(s),r._uColor.IsUsed()){const t=e.currentColor;r._uColor.Update4f(t[0],t[1],t[2],t[3])}t.drawArrays(t.POINTS,this._startIndex/4,this._indexCount),t.useProgram(e.currentShader._shaderProgram)}InitSetProgram(t){this._type=11,this._texParam=t}DoSetProgram(){const t=this._gl,e=this._batchState,r=this._texParam;if(e.currentShader=r,t.useProgram(r._shaderProgram),r.UpdateMatP(e.currentMatP,!1),r.UpdateMatMV(e.currentMV,!1),r._uColor.IsUsed()){const t=e.currentColor;r._uColor.Update4f(t[0],t[1],t[2],t[3])}}InitSetProgramParameters(){this._type=12}DoSetProgramParameters(){const t=this._batchState.currentShader,e=this._gl,r=this._mat4param,a=this._colorParam,s=this._srcOriginRect;if(t._uSamplerBack.IsUsed()){const t=this._batchState.renderer,r=this._texParam;t._lastTexture1!==r&&(e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,r?r._GetTexture():null),t._lastTexture1=r,e.activeTexture(e.TEXTURE0))}t._uPixelSize.IsUsed()&&t._uPixelSize.Update2f(r[0],r[1]),t._uDestStart.IsUsed()&&t._uDestStart.Update2f(r[2],r[3]),t._uDestEnd.IsUsed()&&t._uDestEnd.Update2f(r[4],r[5]),t._uDevicePixelRatio.IsUsed()&&t._uDevicePixelRatio.Update1f(this._indexCount),t._uLayerScale.IsUsed()&&t._uLayerScale.Update1f(r[6]),t._uLayerAngle.IsUsed()&&t._uLayerAngle.Update1f(r[7]),t._uSrcStart.IsUsed()&&t._uSrcStart.Update2f(r[12],r[13]),t._uSrcEnd.IsUsed()&&t._uSrcEnd.Update2f(r[14],r[15]),t._uSrcOriginStart.IsUsed()&&t._uSrcOriginStart.Update2f(s[0],s[1]),t._uSrcOriginEnd.IsUsed()&&t._uSrcOriginEnd.Update2f(s[2],s[3]),t._uLayoutStart.IsUsed()&&t._uLayoutStart.Update2f(a[0],a[1]),t._uLayoutEnd.IsUsed()&&t._uLayoutEnd.Update2f(a[2],a[3]),t._uSeconds.IsUsed()&&t._uSeconds.Update1f(this._startIndex)}InitSetProgramCustomParameters(){this._type=13}DoSetProgramCustomParameters(){const t=this._batchState.currentShader._uCustomParameters,e=this._shaderParams;for(let r=0,a=t.length;r<a;++r){const a=t[r],s=e[r];a.IsColorType()?a.Update3f(s.getR(),s.getG(),s.getB()):a.Update1f(s)}}InitInvalidateFramebuffer(t){this._type=14,this._texParam=t}DoInvalidateFramebuffer(){const t=this._gl,e=this._texParam,r=this._batchState.currentFramebuffer;e!==r&&t.bindFramebuffer(t.FRAMEBUFFER,e),t.invalidateFramebuffer(t.FRAMEBUFFER,[t.COLOR_ATTACHMENT0]),e!==r&&t.bindFramebuffer(t.FRAMEBUFFER,r)}InitBlitFramebuffer(t,e,r){this._type=17;const a=this._mat4param,s=this._batchState.renderer;a[0]=t.GetWidth(),a[1]=t.GetHeight(),a[2]=e?e.GetWidth():s.GetWidth(),a[3]=e?e.GetHeight():s.GetHeight(),a[4]=t.IsLinearSampling()?1:0,a[5]="stretch"===r;const i=this._shaderParams;C3.clearArray(i),i.push(t._GetFramebuffer()),i.push(e?e._GetFramebuffer():null)}DoBlitFramebuffer(){const t=this._mat4param,e=this._shaderParams,r=this._gl,a=t[0],s=t[1],i=t[2],n=t[3],o=0!==t[4],_=0!==t[5],h=e[0],u=e[1];if(r.bindFramebuffer(r.READ_FRAMEBUFFER,h),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,u),_)r.blitFramebuffer(0,0,a,s,0,0,i,n,r.COLOR_BUFFER_BIT,o?r.LINEAR:r.NEAREST);else{const t=Math.min(a,i),e=Math.min(s,n),o=Math.max(s-n,0),_=Math.max(n-s,0);r.blitFramebuffer(0,o,t,e+o,0,_,t,e+_,r.COLOR_BUFFER_BIT,r.NEAREST)}}InitStartQuery(t){this._type=18,this._texParam=t}DoStartQuery(){this._texParam.BeginTimeElapsed(),this._texParam=null}InitEndQuery(t){this._type=19,this._texParam=t}DoEndQuery(){this._texParam.EndTimeElapsed(),this._texParam=null}InitSetEllipseParams(t,e,r){this._type=20;const a=this._mat4param;a[0]=t,a[1]=e,a[2]=r}DoSetEllipseParams(){const t=this._batchState.currentShader,e=this._mat4param;t._uPixelSize.IsUsed()&&t._uPixelSize.Update2f(e[0],e[1]),t._uOutlineThickness.IsUsed()&&t._uOutlineThickness.Update1f(e[2])}InitSetTilemapInfo(t,e,r,a,s,i,n){this._type=16;const o=this._mat4param;t.writeToTypedArray(o,0),o[4]=1/e,o[5]=1/r,o[6]=a/e,o[7]=s/r,o[8]=i/e,o[9]=n/r}DoSetTilemapInfo(){const t=this._batchState.currentShader,e=this._mat4param;t._uSrcStart.IsUsed()&&t._uSrcStart.Update2f(e[0],e[1]),t._uPixelSize.IsUsed()&&t._uPixelSize.Update2f(e[4],e[5]),t._uTileSize.IsUsed()&&t._uTileSize.Update2f(e[6],e[7]),t._uTileSpacing.IsUsed()&&t._uTileSpacing.Update2f(e[8],e[9])}InitSetTileRandomizationInfo(t,e,r,a,s,i,n){this._type=29;const o=this._mat4param;o[0]=1/t,o[1]=1/e,o[2]=r,o[3]=a,o[4]=s,o[5]=i,o[6]=n}DoSetTileRandomizationInfo(){const t=this._batchState.currentShader,e=this._mat4param;t._uPixelSize.IsUsed()&&t._uPixelSize.Update2f(e[0],e[1]),t._uTileSize.IsUsed()&&t._uTileSize.Update2f(e[2],e[3]),t._uOutlineThickness.IsUsed()&&t._uOutlineThickness.Update1f(e[4]),t._uTileSpacing.IsUsed()&&t._uTileSpacing.Update2f(e[5],e[6])}InitClearDepth(t){this._type=22,this._startIndex=t?1:0}DoClearDepth(){const t=this._gl,e=0!==this._startIndex;e||t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),e||t.depthMask(!1)}InitSetDepthEnabled(t){this._type=23,this._startIndex=t?1:0}DoSetDepthEnabled(){const t=this._gl;0===this._startIndex?(t.disable(t.DEPTH_TEST),t.depthMask(!1)):(t.enable(t.DEPTH_TEST),t.depthMask(!0))}InitSetDepthSamplingEnabled(t){this._type=24,this._startIndex=t?1:0}DoSetDepthSamplingEnabled(){const t=this._gl,e=this._batchState,r=e.renderer,a=0!==this._startIndex;e.isDepthSamplingEnabled=a,t.activeTexture(t.TEXTURE2),a?(e.currentFramebufferNoDepth&&t.bindFramebuffer(t.FRAMEBUFFER,e.currentFramebufferNoDepth),t.bindTexture(t.TEXTURE_2D,r._GetDepthBuffer())):(t.bindTexture(t.TEXTURE_2D,null),e.currentFramebufferNoDepth&&t.bindFramebuffer(t.FRAMEBUFFER,e.currentFramebuffer)),t.activeTexture(t.TEXTURE0)}InitCoplanarStartStencilPass(){this._type=25}DoCoplanarStartStencilPass(){const t=this._gl;t.clear(t.STENCIL_BUFFER_BIT),t.enable(t.STENCIL_TEST),t.stencilFunc(t.ALWAYS,1,1),t.stencilOp(t.KEEP,t.KEEP,t.REPLACE),t.colorMask(!1,!1,!1,!1)}InitCoplanarStartColorPass(){this._type=26}DoCoplanarStartColorPass(){const t=this._gl;t.colorMask(!0,!0,!0,!0),t.stencilFunc(t.EQUAL,1,1),t.stencilOp(t.KEEP,t.KEEP,t.KEEP)}InitCoplanarRestore(){this._type=27}DoCoplanarRestore(){const t=this._gl;t.disable(t.STENCIL_TEST)}InitSetScissor(t,e,r,a,s){this._type=28,this._startIndex=t?1:0;const i=this._mat4param;i[0]=e,i[1]=r,i[2]=a,i[3]=s}DoSetScissor(){const t=this._gl,e=this._mat4param;1===this._startIndex?(t.enable(t.SCISSOR_TEST),t.scissor(e[0],e[1],e[2],e[3])):t.disable(t.SCISSOR_TEST)}Run(){switch(this._type){case 1:return void this.DoQuad();case 2:return void this.DoSetTexture();case 3:return void this.DoSetColor();case 4:return void this.DoSetBlend();case 5:return void this.DoSetViewport();case 6:return void this.DoSetProjection();case 7:return void this.DoSetModelView();case 8:return void this.DoSetRenderTarget();case 9:return void this.DoClearSurface();case 10:return void this.DoPoints();case 11:return void this.DoSetProgram();case 12:return void this.DoSetProgramParameters();case 13:return void this.DoSetProgramCustomParameters();case 14:return void this.DoInvalidateFramebuffer();case 15:return void this.DoSetPointTextureCoords();case 16:return void this.DoSetTilemapInfo();case 17:return void this.DoBlitFramebuffer();case 18:return void this.DoStartQuery();case 19:return void this.DoEndQuery();case 20:return void this.DoSetEllipseParams();case 21:return void this.DoSetGradientColor();case 22:return void this.DoClearDepth();case 23:return void this.DoSetDepthEnabled();case 24:return void this.DoSetDepthSamplingEnabled();case 25:return void this.DoCoplanarStartStencilPass();case 26:return void this.DoCoplanarStartColorPass();case 27:return void this.DoCoplanarRestore();case 28:return void this.DoSetScissor();case 29:return void this.DoSetTileRandomizationInfo()}}};
}

// ../lib/gfx/text.js
{
const C3=self.C3,MAX_TEXTURE_SIZE=4096,EXTRA_LINE_HEIGHT=4,GENERIC_FONT_FAMILIES=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),DEFAULT_OPTS={timeout:60},tempColor=new C3.Color(0,0,0,1),VALID_HORIZ_ALIGNMENTS=new Set(["left","center","right"]),VALID_VERT_ALIGNMENTS=new Set(["top","center","bottom"]),VALID_WORD_WRAP_MODES=new Set(["word","cjk","character"]),VALID_TEXT_DIRECTIONS=new Set(["ltr","rtl"]),allRendererTexts=new Set;function fillOrStrokeRect(t,e,i,s,a,n){e?t.strokeRect(i,s,a,n):t.fillRect(i,s,a,n)}function ptToPx(t){return t*(4/3)}function getOffsetParam(t,e){t=t.trim();const i=parseFloat(t);return isFinite(i)?t.endsWith("%")?e*i/100:i:0}C3.FontManager&&C3.FontManager.addEventListener("fontload",(t=>{const e=t.font.GetName();for(const t of allRendererTexts)(t.IsBBCodeEnabled()||C3.equalsNoCase(t.GetFontName(),e))&&t._SetWordWrapChanged()}));let didCheckFoundBoundingBoxSupport=!1,supportsFontBoundingBoxMeasurements=!1;C3.Gfx.RendererText=class{constructor(t,e){e=Object.assign({},DEFAULT_OPTS,e),this._renderer=t,this._fontName="Arial",this._fontSize=16,this._fontSizeScale=1,this._lineHeight=0,this._isBold=!1,this._isItalic=!1,this._colorStr="black",this._isBBcodeEnabled=!1,this._iconSet=null,this._iconSmoothing=!0,this.onloadfont=null,this._alreadyLoadedFonts=new Set,this._horizontalAlign="left",this._verticalAlign="top",this._text="",this._bbString=null,this._wrappedText=C3.New(C3.WordWrap),this._wrapMode="word",this._textDirection="ltr",this._wordWrapChanged=!1,this._textLayoutChanged=!1,this._drawChanged=!1,this._drawMaxCharCount=-1,this._drawCharCount=0,this._cssWidth=0,this._cssHeight=0,this._width=0,this._height=0,this._zoom=1,this._textCanvas=null,this._textContext=null,this._measureContext=null,this._measureContextTop=null,this._lastCanvasWidth=-1,this._lastCanvasHeight=-1,this._lastTextCanvasFont="",this._lastMeasureCanvasFont="",this._lastTextCanvasFillStyle="",this._lastTextCanvasOpacity=1,this._lastTextCanvasLineWidth=1,this._measureTextCallback=t=>this._MeasureText(t),this._texture=null,this._rcTex=new C3.Rect,this._scaleFactor=1,this._textureTimeout=new C3.IdleTimeout((()=>{this.ReleaseTexture(),this._SetTextCanvasSize(8,8)}),e.timeout),this.ontextureupdate=null,this._wasReleased=!1,allRendererTexts.add(this)}Release(){this.onloadfont=null,this._alreadyLoadedFonts.clear(),this._iconSet=null,this._bbString=null,this._textCanvas=null,this._textContext=null,this._measureContext=null,this._measureContextTop=null,this._measureTextCallback=null,this._textureTimeout.Release(),this.ontextureupdate=null,this.ReleaseTexture(),this._wrappedText.Clear(),this._wrappedText=null,this._renderer=null,this._wasReleased=!0,allRendererTexts.delete(this)}_SetDrawChanged(){this._drawChanged=!0}_SetTextLayoutChanged(){this._SetDrawChanged(),this._textLayoutChanged=!0}_SetWordWrapChanged(){this._SetTextLayoutChanged(),this._wordWrapChanged=!0}SetBBCodeEnabled(t){if(t=!!t,this._isBBcodeEnabled===t)return;this._isBBcodeEnabled=t;const e=this._isBBcodeEnabled?"alphabetic":"top";this._textContext&&(this._textContext.textBaseline=e),this._measureContext&&(this._measureContext.textBaseline=e),this._SetWordWrapChanged()}IsBBCodeEnabled(){return this._isBBcodeEnabled}SetIconSet(t){this._iconSet!==t&&(this._iconSet=t,this._wrappedText.SetIconSet(t),this._iconSet&&this._iconSet.IsLoading()&&this._iconSet.LoadContent().then((()=>this._SetDrawChanged())),this._SetWordWrapChanged())}SetIconSmoothing(t){t=!!t,this._iconSmoothing!==t&&(this._iconSmoothing=t,this._SetDrawChanged())}SetFontName(t){t||(t="serif"),this._fontName!==t&&(this._fontName=t,this._SetWordWrapChanged())}GetFontName(){return this._fontName}SetFontSize(t){t<.1&&(t=.1),this._fontSize!==t&&(this._fontSize=t,this._SetWordWrapChanged())}GetFontSize(){return this._fontSize}SetFontSizeScale(t){this._fontSizeScale!==t&&(this._fontSizeScale=t,this._SetWordWrapChanged())}SetLineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this._SetTextLayoutChanged())}GetLineHeight(){return this._lineHeight}SetBold(t){t=!!t,this._isBold!==t&&(this._isBold=t,this._SetWordWrapChanged())}IsBold(){return this._isBold}SetItalic(t){t=!!t,this._isItalic!==t&&(this._isItalic=t,this._SetWordWrapChanged())}IsItalic(){return this._isItalic}SetDrawMaxCharacterCount(t){t=Math.floor(t),this._drawMaxCharCount!==t&&(this._drawMaxCharCount=t,this._SetDrawChanged())}GetDrawMaxCharacterCount(){return this._drawMaxCharCount}_GetFontString(t,e){let i=[];(this._isBold||e.HasStyleTag("b"))&&i.push("bold"),(this._isItalic||e.HasStyleTag("i"))&&i.push("italic");const s=e.GetStyleTag("size"),a=(s?parseFloat(s.param):this._fontSize)*this._fontSizeScale;t?i.push(a+"pt"):i.push(a*this.GetDrawScale()+"pt");let n=this._fontName;const h=e.GetStyleTag("font");return h&&h.param&&(n=h.param,this.onloadfont&&!this._alreadyLoadedFonts.has(n)&&(this.onloadfont(n),this._alreadyLoadedFonts.add(n))),n&&(GENERIC_FONT_FAMILIES.has(n)?i.push(n):i.push('"'+n+'"')),i.join(" ")}SetColor(t){t instanceof C3.Color&&(t=t.getCssRgb()),this._colorStr!==t&&(this._colorStr=t,this._SetDrawChanged())}SetColorRgb(t,e,i){tempColor.setRgb(t,e,i),this.SetColor(tempColor)}SetHorizontalAlignment(t){if(!VALID_HORIZ_ALIGNMENTS.has(t))throw new Error("invalid horizontal alignment");this._horizontalAlign!==t&&(this._horizontalAlign=t,this._SetTextLayoutChanged())}GetHorizontalAlignment(){return this._horizontalAlign}SetVerticalAlignment(t){if(!VALID_VERT_ALIGNMENTS.has(t))throw new Error("invalid vertical alignment");this._verticalAlign!==t&&(this._verticalAlign=t,this._SetTextLayoutChanged())}GetVerticalAlignment(){return this._verticalAlign}SetWordWrapMode(t){if(!VALID_WORD_WRAP_MODES.has(t))throw new Error("invalid word wrap mode");this._wrapMode!==t&&(this._wrapMode=t,this._SetWordWrapChanged())}GetWordWrapMode(){return this._wrapMode}SetTextDirection(t){if(!VALID_TEXT_DIRECTIONS.has(t))throw new Error("invalid text direction");this._textDirection!==t&&(this._textDirection=t,this._textContext&&(this._textContext.direction=this._textDirection),this._measureContext&&(this._measureContext.direction=this._textDirection),this._SetWordWrapChanged())}GetTextDirection(){return this._textDirection}SetText(t){this._text!==t&&(this._text=t,this._SetWordWrapChanged())}GetText(){return this._text}GetDrawScale(){return this._scaleFactor*this._zoom*self.devicePixelRatio}SetSize(t,e,i){if(void 0===i&&(i=1),t<=0||t<=0)return;if(this._cssWidth===t&&this._cssHeight===e&&this._zoom===i)return;const s=this._cssWidth;this._cssWidth=t,this._cssHeight=e,this._zoom=i;const a=self.devicePixelRatio;this._width=this._cssWidth*this._zoom*a,this._height=this._cssHeight*this._zoom*a;const n=Math.max(this._width,this._height),h=Math.min(this._renderer.GetMaxTextureSize(),4096);let o=1;n>h&&(o=h/n,this._width=Math.min(this._width*o,h),this._height=Math.min(this._height*o,h)),this._scaleFactor=o,this._cssWidth!==s?this._SetWordWrapChanged():this._SetTextLayoutChanged()}GetWidth(){return this._width}GetHeight(){return this._height}GetZoom(){return this._zoom}GetTextWidth(){return this._UpdateTextMeasurements(),this._wrappedText.GetMaxLineWidth()}GetTextHeight(){return this._UpdateTextMeasurements(),this._wrappedText.GetTotalLineHeight()+this._wrappedText.GetLineCount()*(this._lineHeight+4)-this._lineHeight}GetLengthInGraphemes(){this._UpdateTextMeasurements();let t=0;for(const e of this._wrappedText.GetLines())for(const i of e.fragments())t+=i.GetLength();return t}GetTexture(){return this._textureTimeout.Reset(),this._MaybeUpdate(),this._texture}HitTestFragment(t,e){this._UpdateTextMeasurements();const i=this.GetDrawScale(),s=this._wrappedText.GetLines();for(const a of s){const s=a.GetFontBoundingBoxDescent()*i;if(e>=a.GetPosY()-a.GetHeight()*i+s&&e<a.GetPosY()+s)for(const e of a.fragments())if(t>=e.GetPosX()&&t<e.GetPosX()+e.GetWidth()*i)return e}return null}*fragmentsWithTag(t){this._UpdateTextMeasurements();const e=this._wrappedText.GetLines();for(const i of e)for(const e of i.fragments()){const i=e.GetStyleTag("tag");i&&C3.equalsNoCase(i.param,t)&&(yield e)}}FindFragmentWithTag(t,e){for(const i of this.fragmentsWithTag(t)){if(0===e)return i;--e}return null}CountFragmentsWithTag(t){let e=0;for(const i of this.fragmentsWithTag(t))++e;return e}_MaybeUpdate(){(!this._texture||this._drawChanged||this._textLayoutChanged||this._wordWrapChanged)&&(this._wasReleased||this._width<=0||this._height<=0||(this._drawChanged=!1,this._DoUpdate()))}_DoUpdate(){this._wasReleased||(this._UpdateTextMeasurements(),this._SetTextCanvasSize(Math.max(C3.nextHighestPowerOfTwo(Math.ceil(this._width)),128),Math.max(C3.nextHighestPowerOfTwo(Math.ceil(this._height)),64)),this._DrawTextToCanvas(),this._UpdateTexture(),this._textureTimeout.Reset())}_SetTextCanvasSize(t,e){this._textCanvas||(this._textCanvas=C3.CreateCanvas(16,16));let i=!1;this._lastCanvasWidth===t&&this._lastCanvasHeight===e||(this._lastCanvasWidth=t,this._lastCanvasHeight=e,this._textCanvas.width=t,this._textCanvas.height=e,i=!0),this._textContext||(this._textContext=this._textCanvas.getContext("2d"),i=!0),i?(this._textContext.textBaseline=this._isBBcodeEnabled?"alphabetic":"top",this._textContext.direction=this._textDirection,this._textContext.font=this._lastTextCanvasFont,this._textContext.fillStyle=this._lastTextCanvasFillStyle,this._textContext.strokeStyle=this._lastTextCanvasFillStyle,this._textContext.globalAlpha=this._lastTextCanvasOpacity,this._textContext.lineWidth=this._lastTextCanvasLineWidth):this._textContext.clearRect(0,0,t,e)}_MaybeCreateMeasureContext(){this._measureContext||(this._measureContext=C3.CreateCanvas(16,16).getContext("2d"),this._measureContextTop=C3.CreateCanvas(16,16).getContext("2d"),this._measureContext.textBaseline=this._isBBcodeEnabled?"alphabetic":"top",this._measureContextTop.textBaseline="top",this._measureContext.direction=this._textDirection,this._measureContextTop.direction=this._textDirection)}_SetMeasureFontString(t){this._lastMeasureCanvasFont!==t&&(this._lastMeasureCanvasFont=t,this._measureContext.font=t,this._measureContextTop.font=t)}_SupportsFontBoundingBoxMeasurements(){if(!didCheckFoundBoundingBoxSupport){didCheckFoundBoundingBoxSupport=!0,this._MaybeCreateMeasureContext();const t=this._measureContext.measureText("test");supportsFontBoundingBoxMeasurements="number"==typeof t["fontBoundingBoxAscent"]&&"number"==typeof t["fontBoundingBoxDescent"]}return supportsFontBoundingBoxMeasurements}_UpdateTextMeasurements(){this._UpdateWordWrap(),this._UpdateTextLayout()}_UpdateWordWrap(){this._wordWrapChanged&&(this._MaybeCreateMeasureContext(),!this._isBBcodeEnabled||this._bbString&&this._bbString.toString()===this._text||(this._bbString=new C3.BBString(this._text,{noEscape:!0})),this._wrappedText.WordWrap(this._isBBcodeEnabled?this._bbString.toFragmentList():this._text,this._measureTextCallback,this._cssWidth,this._wrapMode,0),this._wordWrapChanged=!1)}_UpdateTextLayout(){this._textLayoutChanged&&(this._LayoutText(),this._textLayoutChanged=!1)}_MeasureText(t){const e=t.IsText()?t.GetCharacterArray().join(""):" ";this._SetMeasureFontString(this._GetFontString(!0,t));const i=t.GetStyleTag("size"),s=(i?parseFloat(i.param):this._fontSize)*this._fontSizeScale,a=this._measureContext.measureText(e);let n=0;if(this._isBBcodeEnabled&&this._SupportsFontBoundingBoxMeasurements()){const t=this._measureContextTop.measureText(e);n=a["fontBoundingBoxAscent"]-t["fontBoundingBoxAscent"]}return{width:a.width,height:ptToPx(s),fontBoundingBoxAscent:a["fontBoundingBoxAscent"]||0,fontBoundingBoxDescent:a["fontBoundingBoxDescent"]||0,topToAlphabeticDistance:n}}_SetDrawFontString(t){this._lastTextCanvasFont!==t&&(this._lastTextCanvasFont=t,this._textContext.font=t)}_SetDrawCanvasColor(t){this._lastTextCanvasFillStyle!==t&&(this._lastTextCanvasFillStyle=t,this._textContext.fillStyle=t,this._textContext.strokeStyle=t)}_SetDrawCanvasOpacity(t){this._lastTextCanvasOpacity!==t&&(this._lastTextCanvasOpacity=t,this._textContext.globalAlpha=t)}_SetDrawCanvasLineWith(t){this._lastTextCanvasLineWidth!==t&&(this._lastTextCanvasLineWidth=t,this._textContext.lineWidth=t)}_LayoutText(){const t=this.GetDrawScale(),e=(4+this._lineHeight)*t;let i=0;const s=this._wrappedText.GetLines();if(0===s.length)return;for(const t of s){t.SetPosX(NaN),t.SetPosY(NaN);for(const e of t.fragments())e.SetPosX(NaN),e.SetPosY(NaN)}const a=this._isBBcodeEnabled&&this._SupportsFontBoundingBoxMeasurements();let n=s[0].GetHeight()*t;if("center"===this._verticalAlign){const h=s.reduce(((i,s)=>i+s.GetHeight()*t+e),0)-e;i=Math.max(this._height/2-h/2,0),a&&(n=s[0].GetTopToAlphabeticDistance()*t)}else if("bottom"===this._verticalAlign){const n=s.reduce(((i,s)=>i+s.GetHeight()*t+e),0)-this._lineHeight*t,h=a?s.at(-1).GetFontBoundingBoxDescent()*t:0;i=this._height-n-h-2}for(let a=0,h=s.length;a<h;++a){const h=s[a],o=h.GetHeight()*t,r=i;if(this._isBBcodeEnabled){if(i+=0===a?n:o,a>0&&i>this._height-4*t)break}else if(a>0&&i>=this._height-o)break;r>=0&&this._LayoutTextLine(h,i,t),this._isBBcodeEnabled||(i+=o),i+=e}}_LayoutTextLine(t,e,i){let s=0;"center"===this._horizontalAlign?s=Math.floor((this._width-t.GetWidth()*i)/2):"right"===this._horizontalAlign&&(s=this._width-t.GetWidth()*i),t.SetPosX(s),t.SetPosY(e);for(const a of"ltr"===this._textDirection?t.fragments():t.fragmentsReverse())this._LayoutFragment(a,s,e,i),s+=a.GetWidth()*i}_LayoutFragment(t,e,i,s){const a=t.GetStyleTag("offsetx");e+=a?getOffsetParam(a.param,t.GetHeight())*s:0;const n=t.GetStyleTag("offsety");if(i+=n?getOffsetParam(n.param,t.GetHeight())*s:0,t.IsIcon()){const e=t.GetStyleTag("iconoffsety");i+=e?getOffsetParam(e.param,t.GetHeight())*s:.2*t.GetHeight()*s}t.SetPosX(e),t.SetPosY(i)}_DrawTextToCanvas(){this._textContext.imageSmoothingEnabled=this._iconSmoothing,this._textContext.imageSmoothingQuality="high",this._drawCharCount=0;const t=this.GetDrawScale(),e=this._wrappedText.GetLines();for(const i of e)this._DrawTextLine(i,t)}_DrawTextLine(t,e){const i=t.GetPosX(),s=t.GetPosY();if(Number.isFinite(i)&&Number.isFinite(s))for(const i of"ltr"===this._textDirection?t.fragments():t.fragmentsReverse())this._DrawFragment(i,e,t.GetHeight())}_DrawFragment(t,e,i){const s=this._textContext,a=t.GetPosX(),n=t.GetPosY();if(!Number.isFinite(a)||!Number.isFinite(n))return;const h=i/16;let o=t.GetWidth()*e;const r=t.GetHeight()*e,_=t.GetHeight()/16,l=(4+this._lineHeight)*e;let d=t.IsText()?t.GetCharacterArray():null;if(-1!==this._drawMaxCharCount){if(this._drawCharCount>=this._drawMaxCharCount)return;t.IsText()&&this._drawCharCount+d.length>this._drawMaxCharCount&&(d=d.slice(0,this._drawMaxCharCount-this._drawCharCount),o=this._MeasureText(t).width*e),this._drawCharCount+=t.GetLength()}const x=t.GetStyleTag("background"),u=t.HasStyleTag("u"),C=t.HasStyleTag("s");if(t.IsText()&&C3.IsCharArrayAllWhitespace(d)&&!x&&!u&&!C||t.HasStyleTag("hide"))return;const c=t.GetStyleTag("color"),g=t.GetStyleTag("opacity");this._SetDrawCanvasOpacity(g?parseFloat(g.param)/100:1),x&&(this._SetDrawCanvasColor(x.param),s.fillRect(a,n-r,o,r+l));const S=t.GetStyleTag("linethickness"),T=S?parseFloat(S.param):1,p=t.HasStyleTag("stroke");if(p&&this._SetDrawCanvasLineWith(.5*_*T*this.GetDrawScale()),t.IsText()){const e=d.join("");if(this._SetDrawFontString(this._GetFontString(!1,t)),!p){this._SetDrawCanvasLineWith(.5*_*T*this.GetDrawScale());const i=t.GetStyleTag("outlineback");i&&(this._SetDrawCanvasColor(i.param),this._FillOrStrokeText(!0,e,a,n,o))}if(this._SetDrawCanvasColor(c?c.param:this._colorStr),this._FillOrStrokeText(p,e,a,n,o),!p){this._SetDrawCanvasLineWith(.5*_*T*this.GetDrawScale());const i=t.GetStyleTag("outline");i&&(this._SetDrawCanvasColor(i.param),this._FillOrStrokeText(!0,e,a,n,o))}}else if(t.IsIcon()&&t.GetWidth()>0){const e=t.GetDrawable(this._iconSet);e&&s.drawImage(e,a,n-r,o,r)}if(this._SetDrawCanvasColor(c?c.param:this._colorStr),u&&fillOrStrokeRect(s,p,a,n+e*h,o,e*h*T),C){const t=e*_,i=n-r/4+t/2;s.fillRect(a,i-t*T/2,o,t*T)}}_FillOrStrokeText(t,e,i,s,a){"rtl"===this._textDirection&&(i+=a),t?"Gecko"===C3.Platform.BrowserEngine?this._textContext.strokeText(e,i,s,a):this._textContext.strokeText(e,i,s):"Gecko"===C3.Platform.BrowserEngine?this._textContext.fillText(e,i,s,a):this._textContext.fillText(e,i,s)}_UpdateTexture(){this._renderer.IsContextLost()||(this._texture||(this._texture=this._renderer.CreateDynamicTexture(this._textCanvas.width,this._textCanvas.height,{mipMap:!0,mipMapQuality:"high"})),this._renderer.UpdateTexture(this._textCanvas,this._texture),this._rcTex.set(0,0,this._width/this._texture.GetWidth(),this._height/this._texture.GetHeight()),this.ontextureupdate&&this.ontextureupdate())}GetTexRect(){return this._rcTex}ReleaseTexture(){this._texture&&(this._renderer.IsContextLost()||this._renderer.DeleteTexture(this._texture),this._texture=null)}static OnContextLost(){for(const t of allRendererTexts)t.ReleaseTexture()}static GetAll(){return allRendererTexts.values()}};
}

// ../lib/gfx/webgl/query.js
{
const C3=self.C3;class WebGLRealTimeElapsedQuery{constructor(e){this._gl=e.GetContext(),this._version=e.GetWebGLVersionNumber(),this._timerExt=e._GetDisjointTimerQueryExtension(),this._query=null,this._isActive=!1,this._hasResult=!1,this._result=0,1===this._version?this._query=this._timerExt["createQueryEXT"]():this._query=this._gl["createQuery"]()}Release(){this._DeleteQueryObject(),this._gl=null,this._timerExt=null,this._hasResult=!1}_DeleteQueryObject(){this._query&&(1===this._version?this._timerExt["deleteQueryEXT"](this._query):this._gl["deleteQuery"](this._query),this._query=null)}BeginTimeElapsed(){if(this._isActive)throw new Error("query already active");1===this._version?this._timerExt["beginQueryEXT"](this._timerExt["TIME_ELAPSED_EXT"],this._query):this._gl["beginQuery"](this._timerExt["TIME_ELAPSED_EXT"],this._query),this._isActive=!0}EndTimeElapsed(){if(!this._isActive)throw new Error("query not active");1===this._version?this._timerExt["endQueryEXT"](this._timerExt["TIME_ELAPSED_EXT"]):this._gl["endQuery"](this._timerExt["TIME_ELAPSED_EXT"]),this._isActive=!1}CheckForResult(){if(!this._query||this._hasResult||this._isActive)return;let e=!1;e=1===this._version?this._timerExt["getQueryObjectEXT"](this._query,this._timerExt["QUERY_RESULT_AVAILABLE_EXT"]):this._gl["getQueryParameter"](this._query,this._gl["QUERY_RESULT_AVAILABLE"]);const t=this._gl.getParameter(this._timerExt["GPU_DISJOINT_EXT"]);e&&!t&&(1===this._version?this._result=this._timerExt["getQueryObjectEXT"](this._query,this._timerExt["QUERY_RESULT_EXT"]):this._result=this._gl["getQueryParameter"](this._query,this._gl["QUERY_RESULT"]),this._result/=1e9,this._hasResult=!0),(e||t)&&this._DeleteQueryObject()}HasResult(){return this._hasResult}GetResult(){if(!this._hasResult)throw new Error("no result available");return this._result}}C3.Gfx.WebGLTimeElapsedQuery=class{constructor(e){this._renderer=e,this._frameNumber=e.GetFrameNumber(),this._isActive=!1,this._parentQuery=null,this._isNested=!1,this._realQuery=null,this._queries=[]}Release(){for(const e of this._queries)e instanceof WebGLRealTimeElapsedQuery&&e.Release();C3.clearArray(this._queries),this._parentQuery=null,this._realQuery=null,this._renderer=null}BeginTimeElapsed(){if(this._isActive)throw new Error("query already active");const e=this._renderer._GetTimeQueryStack();e.length>0?(this._isNested=!0,this._parentQuery=e.at(-1),this._parentQuery._EndReal(),this._parentQuery._queries.push(this)):(this._isNested=!1,this._parentQuery=null),this._isActive=!0,e.push(this),this._StartReal()}EndTimeElapsed(){if(!this._isActive)throw new Error("query not active");if(this._renderer._GetTimeQueryStack().pop()!==this)throw new Error("can only end most nested query");this._isActive=!1,this._EndReal(),this._parentQuery&&(this._parentQuery._StartReal(),this._parentQuery=null)}_StartReal(){this._realQuery=C3.New(WebGLRealTimeElapsedQuery,this._renderer),this._queries.push(this._realQuery),this._realQuery.BeginTimeElapsed()}_EndReal(){this._realQuery.EndTimeElapsed(),this._realQuery=null}CheckForResult(){for(const e of this._queries)e.CheckForResult()}IsNested(){return this._isNested}HasResult(){return this._queries.every((e=>e.HasResult()))}GetResult(){return this._queries.reduce(((e,t)=>e+t.GetResult()),0)}GetFrameNumber(){return this._frameNumber}};
}

// ../lib/gfx/webgl/queryResultBuffer.js
{
const C3=self.C3;C3.Gfx.WebGLQueryResultBuffer=class{constructor(e,r=1e3){this._renderer=e,this._maxQueries=r,this._buffer=[],this._renderer._AddQueryResultBuffer(this)}Release(){this.Clear(),this._renderer._RemoveQueryResultBuffer(this),this._renderer=null}Clear(){for(const e of this._buffer)e.Release();C3.clearArray(this._buffer)}AddTimeElapsedQuery(){const e=new C3.Gfx.WebGLTimeElapsedQuery(this._renderer);if(this._buffer.push(e),this._buffer.length>this._maxQueries){this._buffer.shift().Release()}return e}CheckForResults(e){for(const r of this._buffer){if(r.GetFrameNumber()>=e)return;if(r.IsNested())return;r.CheckForResult()}}GetFrameRangeResultSum(e,r){if(r<=e)return NaN;let t=0;for(const s of this._buffer){if(s.GetFrameNumber()>=r)break;if(!(s.GetFrameNumber()<e)){if(!s.HasResult())return NaN;t+=s.GetResult()}}return t}DeleteAllBeforeFrameNumber(e){for(let r=0,t=this._buffer.length;r<t;++r){const t=this._buffer[r];if(!(t.GetFrameNumber()<e))return void(r>0&&this._buffer.splice(0,r));t.Release()}}};
}

// ../lib/gfx/webgl/webglRenderer.js
{
const C3=self.C3,assert=self.assert,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,mat4=glMatrix.mat4,DEFAULT_WEBGLRENDERER_OPTS={powerPreference:"default",enableGpuProfiling:!0,alpha:!1,depth:!1,canSampleDepth:!1,maxWebGLVersion:2,failIfMajorPerformanceCaveat:!1},VALID_POWER_PREFERENCES=new Set(["default","low-power","high-performance"]),MAX_VERTICES=8e3,MAX_INDICES=12e3,MAX_POINTS=8e3,LAST_POINT=7996,PARTIAL_TEXTURE_UPLOAD_CHUNK_SIZE=262144,defaultTexCoordsQuad=new C3.Quad(0,0,1,0,1,1,0,1),tmpProjection=mat4.create(),tmpModelView=mat4.create(),tmpQuad=new C3.Quad,tmpRect=new C3.Rect;let loseContextExtension=null;C3.isDebug&&(self.debug_lose_webgl_context=function(){loseContextExtension?loseContextExtension.loseContext():console.warn("WEBGL_lose_context not supported")},self.debug_restore_webgl_context=function(){loseContextExtension?loseContextExtension.restoreContext():console.warn("WEBGL_lose_context not supported")});const pendingPolls=new Set;let pollRafId=-1;function CheckPendingPolls(){pollRafId=-1;for(const t of pendingPolls)t.checkFunc()&&(t.resolve(),pendingPolls.delete(t));pendingPolls.size>0&&(pollRafId=self.requestAnimationFrame(CheckPendingPolls))}C3.Gfx.WebGLRenderer=class extends C3.Gfx.RendererBase{constructor(t,e){if(super(e),e=Object.assign({},DEFAULT_WEBGLRENDERER_OPTS,e),!VALID_POWER_PREFERENCES.has(e.powerPreference))throw new Error("invalid power preference");const r={"alpha":!!e.alpha,"depth":!1,"antialias":!1,"powerPreference":e.powerPreference,"failIfMajorPerformanceCaveat":!!e.failIfMajorPerformanceCaveat};let i=null,s=0;if(e.maxWebGLVersion>=2&&(i=t.getContext("webgl2",r),s=2),i||(i=t.getContext("webgl",r),s=1),!i)throw new Error("renderer-unavailable (could not get WebGL context)");this._gl=i,this._attribs=i.getContextAttributes(),this._versionString=i.getParameter(i.VERSION),this._version=s,this._viewport=vec4.create(),this._didChangeTransform=!1,this._bbProjectionMatrix=mat4.create(),this._usesDepthBuffer=!!e.depth,this._canSampleDepth=!(!e.depth||!e.canSampleDepth),this._isDepthEnabled=this._usesDepthBuffer,this._isDepthSamplingEnabled=!1,this._depthBuffer=null,this._isAutoSizeDepthBuffer=!0,this._depthBufferWidth=0,this._depthBufferHeight=0,this._vertexBuffer=null,this._texcoordBuffer=null,this._indexBuffer=null,this._pointBuffer=null,this._vertexData=new Float32Array(8e3*this.GetNumVertexComponents()),this._indexData=new Uint16Array(12e3),this._texcoordData=new Float32Array(16e3),this._pointData=new Float32Array(32e3),this._vertexPtr=0,this._texPtr=0,this._pointPtr=0,this._lastVertexPtr=0,this._lastProgram=null,this._spDeviceTransformTextureFill=null,this._batch=[],this._batchPtr=0,this._topOfBatch=0,this._currentRenderTarget=null,this._lastPointZ=0,this._batchState=C3.New(C3.Gfx.BatchState,this),this._lastColor=C3.New(C3.Color,1,1,1,1),this._lastTexture0=null,this._lastTexture1=null,this._lastSrcBlend=0,this._lastDestBlend=0,this._lastPointTexCoords=new C3.Rect,this._lastScissorRect=C3.New(C3.Rect,0,0,-1,-1),this._coplanarMode=0,this._maxTextureSize=-1,this._minPointSize=0,this._maxPointSize=0,this._unmaskedVendor="(unavailable)",this._unmaskedRenderer="(unavailable)",this._extensions=[],this._isInitialisingAfterContextRestored=!1,this._parallelShaderCompileExt=null,this._anisotropicExt=null,this._conservativeDepthExt=null,this._depthTextureExt=null,this._fragDepthExt=null,this._stdDerivativesExt=null,this._textureLodExt=null,this._maxAnisotropy=0,this._isGpuProfilingEnabled=!!e.enableGpuProfiling,this._timerExt=null,this._allQueryResultBuffers=new Set,this._timeQueryStack=[],this.FillIndexBufferData(this._indexData)}IsWebGL(){return!0}async InitState(){super.InitState();const t=this._gl,e=this.GetNumVertexComponents();this._lastColor.setRgba(1,1,1,1),this._lastTexture0=null,this._lastTexture1=null,this._vertexPtr=0,this._pointPtr=0,this._lastVertexPtr=8e3*e-4*e,C3.clearArray(this._batch),this._batchPtr=0,this._topOfBatch=0,this._lastProgram=null,this._currentRenderTarget=null,this._lastPointTexCoords.set(0,0,1,1),this._lastPointZ=0;const r=this._batchState;r.currentShader=null,r.currentFramebuffer=null,r.currentFramebufferNoDepth=null,vec4.set(r.currentColor,1,1,1,1),r.clearColor.setRgba(0,0,0,0),r.pointTexCoords.set(0,0,1,1),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),this._lastSrcBlend=t.ONE,this._lastDestBlend=t.ONE_MINUS_SRC_ALPHA,this._InitBlendModes(t),t.disable(t.CULL_FACE),t.disable(t.STENCIL_TEST),t.disable(t.DITHER),this._usesDepthBuffer?(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.depthFunc(t.LEQUAL)):(t.disable(t.DEPTH_TEST),t.depthMask(!1)),this._isDepthEnabled=this._usesDepthBuffer,this._isDepthSamplingEnabled=!1,this._pointBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._pointBuffer),t.bufferData(t.ARRAY_BUFFER,this._pointData.byteLength,t.DYNAMIC_DRAW),this._vertexBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this._vertexData.byteLength,t.DYNAMIC_DRAW),this._texcoordBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._texcoordBuffer),t.bufferData(t.ARRAY_BUFFER,this._texcoordData.byteLength,t.DYNAMIC_DRAW),this._indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this._indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this._indexData,t.STATIC_DRAW),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,null),this._maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE);const i=t.getParameter(t.ALIASED_POINT_SIZE_RANGE);this._minPointSize=i[0],this._maxPointSize=i[1],this._maxPointSize>2048&&(this._maxPointSize=2048),this._extensions=t.getSupportedExtensions();const s=t.getExtension("WEBGL_debug_renderer_info");if(s&&(this._unmaskedVendor=t.getParameter(s["UNMASKED_VENDOR_WEBGL"]),this._unmaskedRenderer=t.getParameter(s["UNMASKED_RENDERER_WEBGL"])),this._parallelShaderCompileExt=t.getExtension("KHR_parallel_shader_compile"),this._version>=2&&("Chromium"!==C3.Platform.BrowserEngine||C3.Platform.BrowserVersionNumber>=135)&&(this._conservativeDepthExt=t.getExtension("EXT_conservative_depth")),C3.isDebug&&(loseContextExtension=t.getExtension("WEBGL_lose_context")),this._isGpuProfilingEnabled&&(1===this.GetWebGLVersionNumber()?this._timerExt=t.getExtension("EXT_disjoint_timer_query"):this._timerExt=t.getExtension("EXT_disjoint_timer_query_webgl2")||t.getExtension("EXT_disjoint_timer_query")),this._anisotropicExt=t.getExtension("EXT_texture_filter_anisotropic"),this._anisotropicExt?this._maxAnisotropy=t.getParameter(this._anisotropicExt["MAX_TEXTURE_MAX_ANISOTROPY_EXT"]):this._maxAnisotropy=0,this.GetWebGLVersionNumber()<2&&this._usesDepthBuffer&&this._canSampleDepth&&(this._depthTextureExt=t.getExtension("WEBGL_depth_texture"),!this._depthTextureExt))throw new Error("no depth texture support");this.GetWebGLVersionNumber()<2&&(this._fragDepthExt=t.getExtension("EXT_frag_depth"),this._stdDerivativesExt=t.getExtension("OES_standard_derivatives"),this._textureLodExt=t.getExtension("EXT_shader_texture_lod"));const a=C3.Gfx.WebGLShaderProgram,h=a.GetDefaultVertexShaderSource(!1);let n=a.GetTextureFillFragmentShaderSource_WebGL1_NoFragDepth(),o=h,l=a.GetPointFragmentShaderSource_WebGL1_NoFragDepth(),_=a.GetPointVertexShaderSource_WebGL1(),u=a.GetTilemapFragmentShaderSource_WebGL1_NoFragDepth(),d=a.GetDefaultVertexShaderSource(!0),c=!1;this._usesDepthBuffer&&(this.GetWebGLVersionNumber()<2?this._fragDepthExt&&(n=a.GetTextureFillFragmentShaderSource_WebGL1_FragDepthEXT(),l=a.GetPointFragmentShaderSource_WebGL1_FragDepthEXT(),u=a.GetTilemapFragmentShaderSource_WebGL1_FragDepthEXT(),c=!0):(o=a.GetDefaultVertexShaderSource_WebGL2(),n=a.GetTextureFillFragmentShaderSource_WebGL2(this._SupportsConservativeDepth()),l=a.GetPointFragmentShaderSource_WebGL2(this._SupportsConservativeDepth()),_=a.GetPointVertexShaderSource_WebGL2(),u=a.GetTilemapFragmentShaderSource_WebGL2(this._SupportsConservativeDepth()),d=a.GetDefaultVertexShaderSource_WebGL2(!0)));const f=a.GetTileRandomizationFragmentShaderSource(this.GetWebGLVersionNumber(),c,this._stdDerivativesExt&&this._textureLodExt,this._SupportsConservativeDepth()),p=this.GetWebGLVersionNumber()>=2?a.GetDefaultVertexShaderSource_WebGL2():h,x=[[n,o,"<default>"],[n,o,"<default-device-transform>"],[l,_,"<point>"],[a.GetColorFillFragmentShaderSource(),h,"<fill>"],[a.GetLinearGradientFillFragmentShaderSource(),h,"<lineargradient>"],[a.GetPenumbraFillFragmentShaderSource(),h,"<penumbra>"],[a.GetHardEllipseFillFragmentShaderSource(),h,"<hardellipse>"],[a.GetHardEllipseOutlineFragmentShaderSource(),h,"<hardellipseoutline>"],[a.GetSmoothEllipseFillFragmentShaderSource(),h,"<smoothellipse>"],[a.GetSmoothEllipseOutlineFragmentShaderSource(),h,"<smoothellipseoutline>"],[a.GetSmoothLineFillFragmentShaderSource(),h,"<smoothline>"],[u,d,"<tilemap>"],[f,p,"<tilerandomization>"]],E=await Promise.all(x.map((t=>this.CreateShaderProgram({src:t[0],vertexSrc:t[1],name:t[2]}))));this._spTextureFill=E[0],this._spDeviceTransformTextureFill=E[1],this._spPoints=E[2],this._spColorFill=E[3],this._spLinearGradientFill=E[4],this._spPenumbraFill=E[5],this._spHardEllipseFill=E[6],this._spHardEllipseOutline=E[7],this._spSmoothEllipseFill=E[8],this._spSmoothEllipseOutline=E[9],this._spSmoothLineFill=E[10],this._spTilemapFill=E[11],this._spTileRandomization=E[12],this.SetTextureFillMode()}async CreateShaderProgram(t){const e=await C3.Gfx.WebGLShaderProgram.Create(this,t);return this._AddShaderProgram(e),e}ResetLastProgram(){this._lastProgram=null}SetSize(t,e,r){if(this._width===t&&this._height===e&&!r)return;this.EndBatch();const i=this._gl,s=this._batchState;this._width=t,this._height=e,this._SetViewport(0,0,t,e),this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,t/e),this.SetProjectionMatrix(this._bbProjectionMatrix),this._spDeviceTransformTextureFill&&(i.useProgram(this._spDeviceTransformTextureFill.GetShaderProgram()),this._spDeviceTransformTextureFill._UpdateDeviceTransformUniforms(this._matP),this._lastProgram=this._spDeviceTransformTextureFill,this._batchState.currentShader=this._spDeviceTransformTextureFill),i.bindTexture(i.TEXTURE_2D,null),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,null),i.activeTexture(i.TEXTURE0),this._lastTexture0=null,this._lastTexture1=null,this._usesDepthBuffer&&this._isAutoSizeDepthBuffer&&this._SetDepthBufferSize(this._width,this._height),this._currentRenderTarget&&this._currentRenderTarget._Resize(this._width,this._height),i.bindFramebuffer(i.FRAMEBUFFER,null),this._currentRenderTarget=null,s.currentFramebuffer=null,s.currentFramebufferNoDepth=null}_SetDepthBufferSize(t,e){const r=this._gl;this._depthBuffer&&this._depthBufferWidth===t&&this._depthBufferHeight===e||(this._canSampleDepth?(this._depthBuffer&&r.deleteTexture(this._depthBuffer),this._depthBuffer=r.createTexture(),r.bindTexture(r.TEXTURE_2D,this._depthBuffer),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),this.GetWebGLVersionNumber()>=2?r.texImage2D(r.TEXTURE_2D,0,r.DEPTH24_STENCIL8,t,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):this._depthTextureExt&&r.texImage2D(r.TEXTURE_2D,0,r.DEPTH_STENCIL,t,e,0,r.DEPTH_STENCIL,this._depthTextureExt["UNSIGNED_INT_24_8_WEBGL"],null),r.bindTexture(r.TEXTURE_2D,null)):(this._depthBuffer&&r.deleteRenderbuffer(this._depthBuffer),this._depthBuffer=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,this._depthBuffer),r.renderbufferStorage(r.RENDERBUFFER,this._version>=2?r.DEPTH24_STENCIL8:r.DEPTH_STENCIL,t,e),r.bindRenderbuffer(r.RENDERBUFFER,null)),this._depthBufferWidth=t,this._depthBufferHeight=e)}SetFixedSizeDepthBuffer(t,e){this._usesDepthBuffer&&(this._isAutoSizeDepthBuffer=!1,this._SetDepthBufferSize(t,e))}SetAutoSizeDepthBuffer(){this._usesDepthBuffer&&(this._isAutoSizeDepthBuffer=!0,this._SetDepthBufferSize(this._width,this._height))}_SetViewport(t,e,r,i){const s=this._viewport;if(s[0]===t&&s[1]===e&&s[2]===r&&s[3]===i)return;this.PushBatch().InitSetViewport(t,e,r,i),vec4.set(s,t,e,r,i),this._topOfBatch=0}SetFovY(t){super.SetFovY(t),this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetNearZ(t){super.SetNearZ(t),this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetFarZ(t){super.SetFarZ(t),this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetProjectionMatrix(t){if(mat4.exactEquals(this._matP,t))return;this.PushBatch().InitSetProjection(t),mat4.copy(this._matP,t),this._topOfBatch=0,this._didChangeTransform=!0}SetDefaultRenderTargetProjectionState(){let t,e,r;const i=this._currentRenderTarget;null===i?(t=this._bbProjectionMatrix,e=this.GetWidth(),r=this.GetHeight()):(t=i.GetProjectionMatrix(),e=i.GetWidth(),r=i.GetHeight()),this.SetProjectionMatrix(t),this._SetViewport(0,0,e,r)}SetModelViewMatrix(t){if(mat4.exactEquals(this._matMV,t))return;this.PushBatch().InitSetModelView(t),mat4.copy(this._matMV,t),this._topOfBatch=0,this._didChangeTransform=!0}ResetDidChangeTransformFlag(){this._didChangeTransform=!1}DidChangeTransform(){return this._didChangeTransform}GetBatchState(){return this._batchState}PushBatch(){const t=this._batch;return this._batchPtr===t.length&&t.push(new C3.Gfx.WebGLBatchJob(this._batchState)),t[this._batchPtr++]}EndBatch(){0!==this._batchPtr&&(this.IsContextLost()||(this._WriteBuffers(),this._ExecuteBatch(),this._batchPtr=0,this._vertexPtr=0,this._texPtr=0,this._pointPtr=0,this._topOfBatch=0))}_WriteBuffers(){const t=this._gl;this._pointPtr>0&&(t.bindBuffer(t.ARRAY_BUFFER,this._pointBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this._pointData.subarray(0,this._pointPtr))),this._vertexPtr>0&&(t.bindBuffer(t.ARRAY_BUFFER,this._vertexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this._vertexData.subarray(0,this._vertexPtr)),t.bindBuffer(t.ARRAY_BUFFER,this._texcoordBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this._texcoordData.subarray(0,this._texPtr)))}_ExecuteBatch(){const t=this._batch;for(let e=0,r=this._batchPtr;e<r;++e)t[e].Run()}GetOpacity(){return this._lastColor.getA()}SetColorRgba(t,e,r,i){const s=this._lastColor;if(s.equalsRgba(t,e,r,i))return;s.setRgba(t,e,r,i);this.PushBatch().InitSetColor(s),this._topOfBatch=0,this._currentStateGroup=null}SetOpacity(t){const e=this._lastColor;if(e.getA()===t)return;e.setA(t);this.PushBatch().InitSetColor(e),this._topOfBatch=0,this._currentStateGroup=null}SetColor(t){const e=this._lastColor;if(e.equals(t))return;e.set(t);this.PushBatch().InitSetColor(e),this._topOfBatch=0,this._currentStateGroup=null}ResetColor(){this.SetColorRgba(1,1,1,1)}GetColor(){return this._lastColor}SetTexture(t){if(t===this._lastTexture0)return;this.PushBatch().InitSetTexture(t),this._lastTexture0=t,this._topOfBatch=0}_ResetLastTexture(){this._lastTexture0=null}SetBlendMode(t){const e=this._GetBlendByIndex(t);this._SetBlend(e[0],e[1])}SetNamedBlendMode(t){const e=this.GetNamedBlend(t);this._SetBlend(e.srcBlend,e.destBlend)}_SetBlend(t,e){if(t===this._lastSrcBlend&&e===this._lastDestBlend)return;this.PushBatch().InitSetBlend(t,e),this._lastSrcBlend=t,this._lastDestBlend=e,this._topOfBatch=0,this._currentStateGroup=null}IsPremultipliedAlphaBlend(){return this._lastSrcBlend===this._gl.ONE&&this._lastDestBlend===this._gl.ONE_MINUS_SRC_ALPHA}SetAlphaBlend(){this._SetBlend(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA)}SetNoPremultiplyAlphaBlend(){this._SetBlend(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA)}SetCopyBlend(){this._SetBlend(this._gl.ONE,this._gl.ZERO)}Rect(t){this.Rect2(t.getLeft(),t.getTop(),t.getRight(),t.getBottom())}Rect2(t,e,r,i){this.Quad2(t,e,r,e,r,i,t,i)}_ExtendQuadBatch(){let t=this._vertexPtr;if(t>=this._lastVertexPtr&&(this.EndBatch(),t=0),1===this._topOfBatch)this._batch[this._batchPtr-1]._indexCount+=6;else{this.PushBatch().InitQuad(t,6),this._topOfBatch=1}}_WriteQuadToVertexBuffer(t){t.writeToTypedArray3D(this._vertexData,this._vertexPtr,this._baseZ+this._currentZ),this._vertexPtr+=12}Quad(t){this._ExtendQuadBatch(),this._WriteQuadToVertexBuffer(t),defaultTexCoordsQuad.writeToTypedArray(this._texcoordData,this._texPtr),this._texPtr+=8}Quad2(t,e,r,i,s,a,h,n){this._ExtendQuadBatch();const o=this._vertexData;let l=this._vertexPtr;const _=this._baseZ+this._currentZ;o[l++]=t,o[l++]=e,o[l++]=_,o[l++]=r,o[l++]=i,o[l++]=_,o[l++]=s,o[l++]=a,o[l++]=_,o[l++]=h,o[l++]=n,o[l++]=_,this._vertexPtr=l,defaultTexCoordsQuad.writeToTypedArray(this._texcoordData,this._texPtr),this._texPtr+=8}Quad3(t,e){this._ExtendQuadBatch(),this._WriteQuadToVertexBuffer(t),e.writeAsQuadToTypedArray(this._texcoordData,this._texPtr),this._texPtr+=8}Quad4(t,e){this._ExtendQuadBatch(),this._WriteQuadToVertexBuffer(t),e.writeToTypedArray(this._texcoordData,this._texPtr),this._texPtr+=8}Quad3D(t,e,r,i,s,a,h,n,o,l,_,u,d){this._ExtendQuadBatch();const c=this._vertexData;let f=this._vertexPtr;const p=this._baseZ+this._currentZ;c[f++]=t,c[f++]=e,c[f++]=p+r,c[f++]=i,c[f++]=s,c[f++]=p+a,c[f++]=h,c[f++]=n,c[f++]=p+o,c[f++]=l,c[f++]=_,c[f++]=p+u,this._vertexPtr=f,d.writeAsQuadToTypedArray(this._texcoordData,this._texPtr),this._texPtr+=8}Quad3D2(t,e,r,i,s,a,h,n,o,l,_,u,d){this._ExtendQuadBatch();const c=this._vertexData;let f=this._vertexPtr;const p=this._baseZ+this._currentZ;c[f++]=t,c[f++]=e,c[f++]=p+r,c[f++]=i,c[f++]=s,c[f++]=p+a,c[f++]=h,c[f++]=n,c[f++]=p+o,c[f++]=l,c[f++]=_,c[f++]=p+u,this._vertexPtr=f,d.writeToTypedArray(this._texcoordData,this._texPtr),this._texPtr+=8}DrawMesh(t,e,r){const i=this._vertexData,s=this._texcoordData;if(r.length%3!=0)throw new Error("invalid index buffer length");for(let a=0,h=r.length;a<h;){const h=r[a++],n=r[a++],o=r[a++],l=3*h,_=3*n,u=3*o,d=2*h,c=2*n,f=2*o;this._ExtendQuadBatch();let p=this._vertexPtr,x=this._texPtr;i[p++]=t[l+0],i[p++]=t[l+1],i[p++]=t[l+2],i[p++]=t[_+0],i[p++]=t[_+1],i[p++]=t[_+2],i[p++]=t[u+0],i[p++]=t[u+1],i[p++]=t[u+2],i[p++]=t[u+0],i[p++]=t[u+1],i[p++]=t[u+2],s[x++]=e[d+0],s[x++]=e[d+1],s[x++]=e[c+0],s[x++]=e[c+1],s[x++]=e[f+0],s[x++]=e[f+1],s[x++]=e[f+0],s[x++]=e[f+1],this._vertexPtr=p,this._texPtr=x}}FullscreenQuad(t,e){this.SetCurrentZ(0),mat4.copy(tmpProjection,this._matP),mat4.copy(tmpModelView,this._matMV),this.SetDefaultRenderTargetProjectionState();const[r,i]=this.GetRenderTargetSize(this._currentRenderTarget),s=this.CalculateLookAtModelView2(0,0,this.GetDefaultCameraZ(i),0,0,0,i);if(this.SetModelViewMatrix(s),"crop"===t&&this._currentRenderTarget&&e){const t=this._width/2,r=this._height/2,i=e.GetWidth(),s=e.GetHeight(),a=this._currentRenderTarget.GetWidth(),h=this._currentRenderTarget.GetHeight(),n=Math.min(a,i),o=Math.min(h,s),l=Math.max(s-h,0),_=Math.max(h-s,0);tmpRect.set(-t,r-_,-t+n,r-o-_),tmpQuad.setFromRect(tmpRect),tmpRect.set(0,l,n,o+l),tmpRect.divide(i,s),this.Quad3(tmpQuad,tmpRect)}else{const t=r/2,e=i/2;this.Rect2(-t,e,t,-e)}this.SetProjectionMatrix(tmpProjection),this.SetModelViewMatrix(tmpModelView)}StartRenderingPoints(t){if(this._lastPointTexCoords.equals(t))return;this._lastPointTexCoords.copy(t);this.PushBatch().InitSetPointTexCoords(t),this._topOfBatch=0}FinishRenderingPoints(){}Point(t,e,r,i){this._pointPtr>=7996&&this.EndBatch();let s=this._pointPtr;const a=this._baseZ+this._currentZ;if(2===this._topOfBatch&&this._lastPointZ===a)this._batch[this._batchPtr-1]._indexCount++;else{this.PushBatch().InitPoints(s,a),this._topOfBatch=2,this._lastPointZ=a}const h=this._pointData;h[s++]=t,h[s++]=e,h[s++]=r,h[s++]=i,this._pointPtr=s}SetProgram(t){if(this._lastProgram===t)return;this.PushBatch().InitSetProgram(t),this._lastProgram=t,this._topOfBatch=0,this._currentStateGroup=null}GetProgram(){return this._lastProgram}SetDeviceTransformTextureFillMode(){this.SetProgram(this._spDeviceTransformTextureFill)}SetGradientColor(t){this.PushBatch().InitSetGradientColor(t),this._topOfBatch=0}SetEllipseParams(t,e,r=1){this.PushBatch().InitSetEllipseParams(t,e,r),this._topOfBatch=0}SetTilemapInfo(t,e,r,i,s,a,h){if(this._lastProgram!==this._spTilemapFill)throw new Error("must set tilemap fill mode first");this.PushBatch().InitSetTilemapInfo(t,e,r,i,s,a,h),this._topOfBatch=0}SetTileRandomizationInfo(t,e,r,i,s,a,h){if(this._lastProgram!==this._spTileRandomization)throw new Error("must set tile randomization mode first");this.PushBatch().InitSetTileRandomizationInfo(t,e,r,i,s,a,h),this._topOfBatch=0}SetProgramParameters(t,e,r,i,s,a,h,n,o,l,_){const u=this._lastProgram;if(_%=10800,!u._hasAnyOptionalUniforms||u.AreOptionalUniformsAlreadySetInBatch(e,r,i,s,a,h,n,o,l,_))return;const d=this.PushBatch();d.InitSetProgramParameters(),u.SetOptionalUniformsInBatch(e,r,i,s,a,h,n,o,l,_);const c=d._mat4param;c[0]=a,c[1]=h,e.writeToTypedArray(c,2),c[6]=o,c[7]=l,r.writeToTypedArray(c,12);const f=d._colorParam;s.writeToTypedArray(f,0);const p=f[1];f[1]=f[3],f[3]=p,i.writeToTypedArray(d._srcOriginRect,0),d._startIndex=_,d._indexCount=n,u._uSamplerBack.IsUsed()?d._texParam=t?t.GetTexture():null:d._texParam=null,this._topOfBatch=0}SetProgramCustomParameters(t){const e=this._lastProgram;if(0===t.length||e.AreCustomParametersAlreadySetInBatch(t))return;const r=this.PushBatch();r.InitSetProgramCustomParameters(),e.SetCustomParametersInBatch(t),C3.shallowAssignArray(r._shaderParams,t),this._topOfBatch=0}ClearRgba(t,e,r,i){this.PushBatch().InitClearSurface2(t,e,r,i),this._topOfBatch=0}Clear(t){this.PushBatch().InitClearSurface(t),this._topOfBatch=0}Start(){}Finish(){super.Finish(),this._gl.flush()}ClearDepth(){if(!this._usesDepthBuffer||!this._currentRenderTarget||!this._currentRenderTarget.HasDepthBuffer())return;this.PushBatch().InitClearDepth(this._isDepthEnabled),this._topOfBatch=0}SetDepthEnabled(t){if(t=!!t,this._isDepthEnabled===t)return;if(!this._usesDepthBuffer)return;this._isDepthEnabled=t;this.PushBatch().InitSetDepthEnabled(t),this._topOfBatch=0}IsDepthEnabled(){return this._isDepthEnabled}_GetDepthBuffer(){return this._depthBuffer}_CanSampleDepth(){return this._canSampleDepth}SetDepthSamplingEnabled(t){if(t=!!t,!this._canSampleDepth)return;if(this._isDepthSamplingEnabled===t)return;if(t&&this.IsDepthEnabled())throw new Error("depth still enabled");this._isDepthSamplingEnabled=t;this.PushBatch().InitSetDepthSamplingEnabled(t),this._topOfBatch=0}SetScissorRect(t,e,r,i,s=0){if(t=Math.floor(t),e=Math.floor(e),r=Math.floor(r),i=Math.floor(i),this._lastScissorRect.equalsWH(t,e,r,i))return;this._lastScissorRect.setWH(t,e,r,i);e=(s||this.GetRenderTargetSize(this.GetRenderTarget())[1])-e-i;this.PushBatch().InitSetScissor(!0,t,e,r,i),this._topOfBatch=0}RemoveScissorRect(){if(-1===this._lastScissorRect.getRight())return;this._lastScissorRect.set(0,0,-1,-1);this.PushBatch().InitSetScissor(!1,0,0,0,0),this._topOfBatch=0}CheckForQueryResults(){for(const t of this._allQueryResultBuffers)t.CheckForResults(this._frameNumber)}IsContextLost(){return!this._gl||this._gl.isContextLost()||this._isInitialisingAfterContextRestored}OnContextLost(){super.OnDeviceOrContextLost(),C3.Gfx.WebGLRendererTexture.OnContextLost(),C3.Gfx.WebGLRenderTarget.OnContextLost(),C3.Gfx.RendererText.OnContextLost();for(const t of this._allQueryResultBuffers)t.Clear();this._extensions=[],this._timerExt=null,this._parallelShaderCompileExt=null,this._conservativeDepthExt=null,this._anisotropicExt=null,this._depthTextureExt=null,this._fragDepthExt=null,this._stdDerivativesExt=null,this._textureLodExt=null,this._maxAnisotropy=0,this._unmaskedVendor="(unavailable)",this._unmaskedRenderer="(unavailable)",this._lastProgram=null,this._spDeviceTransformTextureFill=null,this._depthBuffer=null;for(const t of this._stateGroups.values())t.OnContextLost()}async OnContextRestored(){this._isInitialisingAfterContextRestored=!0,await this.InitState(),this._isInitialisingAfterContextRestored=!1;for(const t of this._stateGroups.values())t.OnContextRestored(this);this.SetSize(this._width,this._height,!0)}CreateStaticTexture(t,e){if(this.IsContextLost())throw new Error("context lost");this.EndBatch();const r=C3.New(C3.Gfx.WebGLRendererTexture,this);return r._CreateStatic(t,e),r}async CreateStaticTextureAsync(t,e){if(this.IsContextLost())throw new Error("context lost");if(e=Object.assign({},e),C3.Supports.ImageBitmapOptions){let r=await createImageBitmap(t,{"premultiplyAlpha":"premultiply"});const i=e.wrapX&&"clamp-to-edge"!==e.wrapX||e.wrapY&&"clamp-to-edge"!==e.wrapY,s=C3.isPOT(r.width)&&C3.isPOT(r.height);return this.SupportsNPOTTextures()||s||!i?e.premultiplyAlpha=!1:C3.Supports.ImageBitmapOptionsResize?(r=await createImageBitmap(t,{"premultiplyAlpha":"premultiply","resizeWidth":C3.nextHighestPowerOfTwo(r.width),"resizeHeight":C3.nextHighestPowerOfTwo(r.height)}),e.premultiplyAlpha=!1):r=await createImageBitmap(t,{"premultiplyAlpha":"none"}),await C3.Asyncify((()=>this.CreateStaticTexture(r,e)))}if(t instanceof Blob){if("undefined"==typeof Image)throw new Error("texture upload variant not supported in worker");const e=await C3.BlobToImage(t);t=e}return await C3.Asyncify((()=>this.CreateStaticTexture(t,e)))}CreateDynamicTexture(t,e,r){this.EndBatch();const i=C3.New(C3.Gfx.WebGLRendererTexture,this);return i._CreateDynamic(t,e,r),i}UpdateTexture(t,e,r){this.EndBatch(),e._Update(t,r)}DeleteTexture(t){t&&(t.SubtractReference(),t.GetReferenceCount()>0||(this.EndBatch(),t===this._lastTexture0&&(this._gl.bindTexture(this._gl.TEXTURE_2D,null),this._lastTexture0=null),t===this._lastTexture1&&(this._gl.activeTexture(this._gl.TEXTURE1),this._gl.bindTexture(this._gl.TEXTURE_2D,null),this._gl.activeTexture(this._gl.TEXTURE0),this._lastTexture1=null),t._Delete()))}CreateRenderTarget(t){let e=this._width,r=this._height,i=!0;if(t&&("number"==typeof t.width&&(e=Math.floor(t.width),i=!1),"number"==typeof t.height&&(r=Math.floor(t.height),i=!1)),e<=0||r<=0)throw new Error("invalid size");this.EndBatch();const s=C3.New(C3.Gfx.WebGLRenderTarget,this);return s._Create(e,r,Object.assign({isDefaultSize:i},t)),this._currentRenderTarget=null,this._batchState.currentFramebuffer=null,this._batchState.currentFramebufferNoDepth=null,s}SetRenderTarget(t,e=!0){if(t===this._currentRenderTarget)return;t&&t.IsDefaultSize()&&t._Resize(this._width,this._height);this.PushBatch().InitSetRenderTarget(t),this._currentRenderTarget=t,this._topOfBatch=0,e&&this.SetDefaultRenderTargetProjectionState()}GetRenderTarget(){return this._currentRenderTarget}GetRenderTargetSize(t){return t?[t.GetWidth(),t.GetHeight()]:[this._width,this._height]}CopyRenderTarget(t,e="stretch"){if(this._version<2||this._currentRenderTarget&&this._currentRenderTarget.GetMultisampling()>0)this.SetCopyBlend(),this.ResetColor(),this.DrawRenderTarget(t,e);else{this.PushBatch().InitBlitFramebuffer(t,this._currentRenderTarget,e),this._topOfBatch=0}}DrawRenderTarget(t,e="stretch"){const r=t.GetTexture();if(!r)throw new Error("not a texture-backed render target");this.SetTexture(r),this.FullscreenQuad(e,r)}InvalidateRenderTarget(t){if(this._version<2)return;this.PushBatch().InitInvalidateFramebuffer(t._GetFramebuffer()),this._topOfBatch=0}DeleteRenderTarget(t){this.SetRenderTarget(null),this.EndBatch();const e=t.GetTexture();e===this._lastTexture0&&(this._gl.bindTexture(this._gl.TEXTURE_2D,null),this._lastTexture0=null),e===this._lastTexture1&&(this._gl.activeTexture(this._gl.TEXTURE1),this._gl.bindTexture(this._gl.TEXTURE_2D,null),this._gl.activeTexture(this._gl.TEXTURE0),this._lastTexture1=null),t._Delete()}async ReadBackRenderTargetToImageData(t,e,r){this.EndBatch();const i=this._currentRenderTarget;let s,a,h;t?(s=t.GetWidth(),a=t.GetHeight(),h=t._GetFramebuffer()):(s=this.GetWidth(),a=this.GetHeight(),h=null);let n=0,o=0,l=s,_=a;if(r){n=C3.clamp(Math.floor(r.getLeft()),0,s-1),o=C3.clamp(Math.floor(r.getTop()),0,a-1);let t=r.width();t=0===t?s-n:C3.clamp(Math.floor(t),0,s-n);let e=r.height();e=0===e?a-o:C3.clamp(Math.floor(e),0,a-o),l=t,_=e,o=a-(o+_)}const u=this._gl;u.bindFramebuffer(u.FRAMEBUFFER,h);const d=()=>{u.bindFramebuffer(u.FRAMEBUFFER,null),this._currentRenderTarget=null,this._batchState.currentFramebuffer=null,this._batchState.currentFramebufferNoDepth=null,this.SetRenderTarget(i)};let c;if(!e&&this.GetWebGLVersionNumber()>=2){u.bindFramebuffer(u.READ_FRAMEBUFFER,h);const t=u.createBuffer(),e=l*_*4,r=u["PIXEL_PACK_BUFFER"];u.bindBuffer(r,t),u.bufferData(r,e,u["STREAM_READ"]),u.readPixels(n,o,l,_,u.RGBA,u.UNSIGNED_BYTE,0),u.bindFramebuffer(u.READ_FRAMEBUFFER,null),u.bindBuffer(r,null),d();const i=u["fenceSync"](u["SYNC_GPU_COMMANDS_COMPLETE"],0);await this._WaitForObjectReady((()=>u["getSyncParameter"](i,u["SYNC_STATUS"])===u["SIGNALED"])),u["deleteSync"](i),c=new ImageData(l,_),u.bindBuffer(r,t),u["getBufferSubData"](r,0,new Uint8Array(c.data.buffer),0,e),u.bindBuffer(r,null),u.deleteBuffer(t)}else c=new ImageData(l,_),u.readPixels(n,o,l,_,u.RGBA,u.UNSIGNED_BYTE,new Uint8Array(c.data.buffer)),d();return c}CoplanarStartStencilPass(){this.SetDepthEnabled(!0);this.PushBatch().InitCoplanarStartStencilPass(),this._topOfBatch=0,this._coplanarMode=1}CoplanarStartColorPass(){this.SetDepthEnabled(!1);this.PushBatch().InitCoplanarStartColorPass(),this._topOfBatch=0,this._coplanarMode=2}IsCoplanarColorPass(){return 2===this._coplanarMode}CoplanarRestoreStandardRendering(){this.SetDepthEnabled(!0);this.PushBatch().InitCoplanarRestore(),this._topOfBatch=0,this._coplanarMode=0}StartQuery(t){if(!this.SupportsGPUProfiling())return;this.PushBatch().InitStartQuery(t),this._topOfBatch=0}EndQuery(t){if(!this.SupportsGPUProfiling())return;this.PushBatch().InitEndQuery(t),this._topOfBatch=0}_WaitForObjectReady(t){const e=new Promise((e=>pendingPolls.add({resolve:e,checkFunc:t})));return-1===pollRafId&&(pollRafId=self.requestAnimationFrame(CheckPendingPolls)),e}GetEstimatedBackBufferMemoryUsage(){return this._width*this._height*(this._attribs["alpha"]?4:3)}GetEstimatedRenderBufferMemoryUsage(){let t=0;for(const e of C3.Gfx.WebGLRenderTarget.allRenderTargets())e.GetTexture()||(t+=e.GetEstimatedMemoryUsage());return t}GetEstimatedTextureMemoryUsage(){let t=0;for(const e of C3.Gfx.WebGLRendererTexture.allTextures())t+=e.GetEstimatedMemoryUsage();return t}GetWebGLVersionString(){return this._versionString}GetWebGLVersionNumber(){return this._version}GetDisplayName(){return"webgl"+this.GetWebGLVersionNumber()}SupportsNPOTTextures(){return this.GetWebGLVersionNumber()>=2}GetMaxTextureSize(){return this._maxTextureSize}GetMinPointSize(){return this._minPointSize}GetMaxPointSize(){return this._maxPointSize}GetUnmaskedVendor(){return this._unmaskedVendor}GetUnmaskedRenderer(){return this._unmaskedRenderer}GetWebGLExtensionsAnalyticsString(){if(this.GetWebGLVersionNumber()>=2)return"webgl2";{const t=[];return this._fragDepthExt&&t.push("EXT_frag_depth"),this._stdDerivativesExt&&t.push("OES_standard_derivatives"),this._textureLodExt&&t.push("EXT_shader_texture_lod"),t.length>0?"webgl1:"+t.join(","):"webgl1:none"}}GetExtensions(){return this._extensions}SupportsGPUProfiling(){return!!this._timerExt}_GetDisjointTimerQueryExtension(){return this._timerExt}_GetParallelShaderCompileExtension(){return this._parallelShaderCompileExt}_SupportsConservativeDepth(){return!!this._conservativeDepthExt}_GetAnisotropicExtension(){return this._anisotropicExt}_GetMaxAnisotropy(){return this._maxAnisotropy}_AddQueryResultBuffer(t){this._allQueryResultBuffers.add(t)}_RemoveQueryResultBuffer(t){this._allQueryResultBuffers.delete(t)}_GetTimeQueryStack(){return this._timeQueryStack}GetContext(){return this._gl}_InitBlendModes(t){this._InitBlendModeData([["normal",t.ONE,t.ONE_MINUS_SRC_ALPHA],["additive",t.ONE,t.ONE],["xor",t.ONE,t.ONE_MINUS_SRC_ALPHA],["copy",t.ONE,t.ZERO],["destination-over",t.ONE_MINUS_DST_ALPHA,t.ONE],["source-in",t.DST_ALPHA,t.ZERO],["destination-in",t.ZERO,t.SRC_ALPHA],["source-out",t.ONE_MINUS_DST_ALPHA,t.ZERO],["destination-out",t.ZERO,t.ONE_MINUS_SRC_ALPHA],["source-atop",t.DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],["destination-atop",t.ONE_MINUS_DST_ALPHA,t.SRC_ALPHA]])}CreateWebGLText(){return this.CreateRendererText()}};
}

// ../lib/gfx/effectCompositor/effectChainManager.js
{
const C3=self.C3,DEFAULT_CTOR_OPTS={getDrawSize:null,getRenderTarget:null,releaseRenderTarget:null,getTime:null,redraw:null};C3.Gfx.EffectChainManager=class{constructor(e){e=Object.assign({},DEFAULT_CTOR_OPTS,e),this._cbGetDrawSize=e.getDrawSize,this._cbGetRenderTarget=e.getRenderTarget,this._cbReleaseRenderTarget=e.releaseRenderTarget,this._cbGetTime=e.getTime,this._cbRedraw=e.redraw,this._webgpuBackTexture=null,this._allEffectChains=new Set}_AddEffectChain(e){this._allEffectChains.add(e)}_RemoveEffectChain(e){this._allEffectChains.delete(e)}OnContextLost(){this._webgpuBackTexture=null;for(const e of this._allEffectChains)e.OnContextLost()}GetDrawSize(e){return this._cbGetDrawSize?this._cbGetDrawSize(e):[e.GetWidth(),e.GetHeight()]}GetRenderTarget(e){return this._cbGetRenderTarget(e)}ReleaseRenderTarget(e,t){this._cbReleaseRenderTarget(e,t)}GetTime(){return this._cbGetTime()}Redraw(e){this._cbRedraw(e)}_GetWebGPUBackTexture(e,t,r){return t=Math.floor(t),r=Math.floor(r),!this._webgpuBackTexture||this._webgpuBackTexture.GetWidth()===t&&this._webgpuBackTexture.GetHeight()===r||(e.DeleteTexture(this._webgpuBackTexture),this._webgpuBackTexture=null),null===this._webgpuBackTexture&&(this._webgpuBackTexture=e.CreateStaticTexture(null,{width:t,height:r,sampling:"nearest",mipMap:!1})),this._webgpuBackTexture}};
}

// ../lib/gfx/effectCompositor/effectChain.js
{
const C3=self.C3,assert=self.assert,glMatrix=self.glMatrix,mat4=glMatrix.mat4,tempRect=C3.New(C3.Rect),tempRect2=C3.New(C3.Rect),tempRect3=C3.New(C3.Rect),tempRect4=C3.New(C3.Rect),tempMat4a=mat4.create(),tempMat4b=mat4.create(),DEFAULT_CTOR_OPTS={drawContent:null,getSourceTextureInfo:null,getShaderParameters:null,invalidateRenderTargets:!1},DEFAULT_BUILDSTEPS_OPTS={indexMap:null,forcePreDraw:!1,forcePostDraw:!1,is3D:!1,isSourceTextureRotated:!1,isRotatedOrNegativeSizeInstance:!1,useFullSurface:!1};C3.Gfx.EffectChain=class{constructor(e,t){t=Object.assign({},DEFAULT_CTOR_OPTS,t),this._manager=e,this._cbDrawContent=t.drawContent,this._cbGetSourceTextureInfo=t.getSourceTextureInfo,this._cbGetShaderParameters=t.getShaderParameters,this._cbDrawContentHook=null,this._shaderProgramList=[],this._shaderProgramIndices=[],this._steps=[],this._needsRebuild=!1,this._blendMode=0,this._isAnyShaderAnimated=!1,this._isAnyShaderDepthSampling=!1,this._isAnyShaderBackgroundBlending=!1,this._isAnyShaderCrossSampling=!1,this._isAnyIsSrcTexRotated=!1,this._useCopyTextureBackgroundSampling=!1,this._didChangeTransform=!1,this._depthEnabledAtStart=!1,this._coplanarColorPassAtStart=!1,this._canUseFastPath=!1,this._useFullSurface=!1,this._isSourceTextureRotated=!1,this._numTempSurfacesRequired=0,this._renderTargets=[null,null,null],this._invalidateRenderTargets=!!t.invalidateRenderTargets,this._boxExtendHorizontal=0,this._boxExtendVertical=0,this._drawWidth=0,this._drawHeight=0,this._contentObject=null,this._contextObject=null,this._layoutRect=C3.New(C3.Rect),this._drawSurfaceRect=C3.New(C3.Rect),this._rcTexOriginal=C3.New(C3.Rect),this._rcTexBounce=C3.New(C3.Rect),this._rcTexDest=C3.New(C3.Rect),this._devicePixelRatio=1,this._layerScale=1,this._layerAngle=0,this._time=0,this._destRenderTarget=null,this._backTex=null,this._compositOffX=0,this._compositOffY=0,this._compositRtWidth=0,this._compositRtHeight=0,this._updateOwnProjection=!1,this._projectionMatrix=mat4.create(),this._modelViewMatrix=mat4.create(),this._manager._AddEffectChain(this)}Release(){this._manager._RemoveEffectChain(this),C3.clearArray(this._steps),C3.clearArray(this._shaderProgramList),C3.clearArray(this._shaderProgramIndices),this._contentObject=null,this._contextObject=null,this._cbDrawContent=null,this._cbGetSourceTextureInfo=null,this._cbGetShaderParameters=null}OnContextLost(){this._needsRebuild=!0,C3.clearArray(this._steps),C3.clearArray(this._shaderProgramList),C3.clearArray(this._shaderProgramIndices)}NeedsRebuild(){return this._needsRebuild}BuildSteps(e,t){if(t=Object.assign({},DEFAULT_BUILDSTEPS_OPTS,t),C3.clearArray(this._steps),this._boxExtendHorizontal=0,this._boxExtendVertical=0,this._isAnyShaderAnimated=!1,this._isAnyShaderDepthSampling=!1,this._isAnyShaderBackgroundBlending=!1,this._isAnyShaderCrossSampling=!1,this._isAnyIsSrcTexRotated=!1,this._useCopyTextureBackgroundSampling=!1,this._numTempSurfacesRequired=0,this._isSourceTextureRotated=!!t.isSourceTextureRotated,this._useFullSurface=!!t.useFullSurface,this._needsRebuild=!1,C3.shallowAssignArray(this._shaderProgramList,e),0===e.length)return;if(t.indexMap){if(t.indexMap.length!==e.length)throw new Error("incorrect indexMap length");C3.shallowAssignArray(this._shaderProgramIndices,t.indexMap)}else{C3.clearArray(this._shaderProgramIndices);for(let t=0,r=e.length;t<r;++t)this._shaderProgramIndices.push(t)}for(const t of e)this._boxExtendHorizontal+=t.GetBoxExtendHorizontal(),this._boxExtendVertical+=t.GetBoxExtendVertical(),t.IsAnimated()&&(this._isAnyShaderAnimated=!0),t.UsesDepth()&&(this._isAnyShaderDepthSampling=!0),t.BlendsBackground()&&(this._isAnyShaderBackgroundBlending=!0),t.UsesCrossSampling()&&(this._isAnyShaderCrossSampling=!0),t.UsesIsSrcTexRotated()&&(this._isAnyIsSrcTexRotated=!0);this._useCopyTextureBackgroundSampling=this._ShouldUseCopyTextureBackgroundSampling(e[0].GetRenderer());const r=this._ShouldPreDraw(e[0],t),s=this._ShouldPostDraw(e.at(-1),t);if(1===e.length&&!r&&!s)return void(this._canUseFastPath=!0);this._canUseFastPath=!1;let i=0;r&&(this._numTempSurfacesRequired=1,this._steps.push(C3.New(C3.Gfx.EffectChain.Step.PreDraw,this,-1,1)),i=1);for(let t=0,a=e.length;t<a;++t)if(0!==t||r){let e=1===i?2:1;t!==a-1||s||(e=0),this._numTempSurfacesRequired=Math.max(this._numTempSurfacesRequired,e),this._steps.push(C3.New(C3.Gfx.EffectChain.Step.Bounce,this,i,e,t)),i=e}else this._numTempSurfacesRequired=1,this._steps.push(C3.New(C3.Gfx.EffectChain.Step.FirstBounce,this,-1,1,t)),i=1;s&&this._steps.push(C3.New(C3.Gfx.EffectChain.Step.PostDraw,this,i,0))}_ShouldPreDraw(e,t){return!!(t.forcePreDraw||e.MustPreDraw()||t.is3D&&!e.Supports3DDirectRendering()||e.UsesDepth()&&!this._useFullSurface||0!==this._boxExtendHorizontal||0!==this._boxExtendVertical)||(e.GetRenderer().IsWebGL()?e.BlendsBackground()&&(t.isRotatedOrNegativeSizeInstance||t.isSourceTextureRotated)||e.UsesAnySrcRectOrPixelSize()&&t.isSourceTextureRotated:e.BlendsBackground()&&!this._useCopyTextureBackgroundSampling&&t.isRotatedOrNegativeSizeInstance)}_ShouldPostDraw(e,t){return!!t.forcePostDraw||(e.GetRenderer().IsWebGL()?e.BlendsBackground()||e.UsesCrossSampling():(e.BlendsBackground()||e.UsesCrossSampling())&&this._UseRenderTargetBackgroundSampling())}_ShouldUseCopyTextureBackgroundSampling(e){return e.IsWebGPU()&&this._isAnyShaderBackgroundBlending&&!this._isAnyShaderCrossSampling}Render(e,t,r){e.IsWebGPU()&&null===t&&(t=e.GetBackbufferRenderTarget()),this._destRenderTarget=t,this._contentObject=r.contentObject||null,this._contextObject=r.contextObject||null,this._blendMode=r.blendMode||0,this._devicePixelRatio=r.devicePixelRatio||1,this._layerScale=r.layerScale||1,this._layerAngle=r.layerAngle||0,this._time="number"==typeof r.time?r.time:this._manager.GetTime(),this._didChangeTransform=!1,e.ResetDidChangeTransformFlag(),this._isAnyShaderAnimated&&this._Redraw();let s=!1;if(this._UseCopyTextureBackgroundSampling()&&(this._CalculateDrawSizeAndRectangles(e,r),s=!0,this._backTex=this._manager._GetWebGPUBackTexture(e,this._drawWidth,this._drawHeight),tempRect.copy(this._drawSurfaceRect),tempRect.roundOuter(),e.IsWebGPU()&&e._MaybeDoPendingClearRenderPass(this._destRenderTarget),e.CopyTextureToTexture(this._destRenderTarget.GetTexture(),this._backTex,tempRect.getLeft(),tempRect.getTop(),tempRect.width(),tempRect.height())),this._canUseFastPath)this._Render_FastPath(e,r);else if(s||this._CalculateDrawSizeAndRectangles(e,r),0!==this._rcTexOriginal.width()||0!==this._rcTexOriginal.height()){e.SetAlphaBlend(),e.ResetColor(),e.SetBaseZ(0),e.SetCurrentZ(0),this._cbDrawContentHook=r.drawContentHook||null,this._compositOffX=r.compositOffX||0,this._compositOffY=r.compositOffY||0,this._compositRtWidth=r.compositRtWidth||0,this._compositRtHeight=r.compositRtHeight||0,this._updateOwnProjection=!!r.updateOwnProjection,this._OnBeforeStartEffectChain(e),this._renderTargets[0]=t,this._renderTargets[1]=this._numTempSurfacesRequired>=1?this._GetRenderTarget():null,this._renderTargets[2]=2===this._numTempSurfacesRequired?this._GetRenderTarget():null;for(const t of this._steps){const r=this._GetRenderTargetForId(t.GetSrcTargetId()),s=this._GetRenderTargetForId(t.GetDestTargetId());e.IsWebGPU()?t.Run_WebGPU(e,r,s):t.Run_WebGL(e,r,s)}e.SetTexture(null),this._renderTargets[1]&&this._ReleaseRenderTarget(this._renderTargets[1]),this._renderTargets[2]&&this._ReleaseRenderTarget(this._renderTargets[2]),this._renderTargets.fill(null),this._OnAfterEndEffectChain(e),this._destRenderTarget=null,this._backTex=null,this._contentObject=null,this._contextObject=null,this._cbDrawContentHook=null}}_CalculateDrawSizeAndRectangles(e,t){const[r,s]=this._manager.GetDrawSize(e);this._SetDrawSize(e,r,s),this._CalculateRectangles(t)}_SetDrawSize(e,t,r){if(t<=0||r<=0)throw new Error("invalid draw size");this._drawWidth===t&&this._drawHeight===r||this._CalculateDeviceTransformMatrices(e,t,r,0,0,this._projectionMatrix,this._modelViewMatrix),this._drawWidth=t,this._drawHeight=r}_CalculateDeviceTransformMatrices(e,t,r,s,i,a,n){const h=t/2+s,c=r/2+i;e.CalculatePerspectiveMatrix(a,t/r);const o=e.CalculateLookAtModelView2(h,c,e.GetDefaultCameraZ(r),h,c,0,r);mat4.copy(n,o)}_CalculateRectangles(e){this._layoutRect.copy(e.layoutRect),e.drawSurfaceRect?this._drawSurfaceRect.copy(e.drawSurfaceRect):this._drawSurfaceRect.set(0,0,this._drawWidth,this._drawHeight),this._rcTexOriginal.copy(this._drawSurfaceRect),this._rcTexOriginal.divide(this._drawWidth,this._drawHeight);const t=this._layerScale*this._devicePixelRatio;this._drawSurfaceRect.inflate(this._boxExtendHorizontal*t,this._boxExtendVertical*t),this._rcTexDest.copy(this._drawSurfaceRect),this._rcTexDest.divide(this._drawWidth,this._drawHeight),this._drawSurfaceRect.clampBoth(0,0,this._drawWidth,this._drawHeight),this._rcTexBounce.copy(this._drawSurfaceRect),this._rcTexBounce.divide(this._drawWidth,this._drawHeight)}_OnBeforeStartEffectChain(e){if(this._depthEnabledAtStart=e.IsDepthEnabled(),this._coplanarColorPassAtStart=e.IsCoplanarColorPass(),this._useFullSurface)e.SetDepthEnabled(!1),this._isAnyShaderDepthSampling&&e.SetDepthSamplingEnabled(!0);else{if(tempRect.copy(this._drawSurfaceRect),e.IsWebGL()){const e=this._layerScale*this._devicePixelRatio;tempRect.inflate(Math.max(this._boxExtendHorizontal,1)*e,Math.max(this._boxExtendVertical,1)*e),tempRect.roundOuter(),tempRect.clamp(0,0,this._drawWidth,this._drawHeight)}else tempRect.roundOuter();e.SetScissorRect(tempRect.getLeft(),tempRect.getTop(),tempRect.width(),tempRect.height(),this._drawHeight)}}_OnAfterEffectChainDrawContent(e){e.ResetColor(),this._useFullSurface||(this._coplanarColorPassAtStart&&e.CoplanarRestoreStandardRendering(),e.SetDepthEnabled(!1),this._isAnyShaderDepthSampling&&e.SetDepthSamplingEnabled(!0)),e.IsWebGPU()&&e.SetNormalizedCoordsProgramVariant(!0)}_OnAfterEndEffectChain(e){e.SetDepthSamplingEnabled(!1),this._coplanarColorPassAtStart&&e.CoplanarStartColorPass(),e.SetDepthEnabled(this._depthEnabledAtStart),this._useFullSurface||e.RemoveScissorRect(),e.IsWebGPU()&&e.SetNormalizedCoordsProgramVariant(!1),this._didChangeTransform=e.DidChangeTransform()}_ClampRcTexDest(){this._rcTexDest.clamp(0,0,1,1)}_GetRenderTargetForId(e){return e<0?null:this._renderTargets[e]}_GetRenderTarget(){return this._manager.GetRenderTarget(this)}_GetDestRenderTarget(){return this._destRenderTarget}_ReleaseRenderTarget(e){this._manager.ReleaseRenderTarget(e,this)}_GetShaderProgramAt(e){return this._shaderProgramList[e]}_DrawContent(e){this._cbDrawContentHook?this._cbDrawContentHook(this,e,(()=>this._cbDrawContent(e,this))):this._cbDrawContent(e,this),this._canUseFastPath||this._OnAfterEffectChainDrawContent(e)}_IsRenderTargetSameSizeAndOffset(e){if(this._useFullSurface)return!0;if(0!==this._compositOffX||0!==this._compositOffY||0!==this._compositRtWidth||0!==this._compositRtHeight)return!1;const[t,r]=e.GetRenderTargetSize(e.GetRenderTarget());return t===this._drawWidth&&r===this._drawHeight}_SetDeviceTransform(e,t){let r=this._projectionMatrix,s=this._modelViewMatrix;if(t&&!this._IsRenderTargetSameSizeAndOffset(e)){let t,i;r=tempMat4a,s=tempMat4b,0!==this._compositRtWidth&&0!==this._compositRtHeight?[t,i]=[this._compositRtWidth,this._compositRtHeight]:[t,i]=e.GetRenderTargetSize(e.GetRenderTarget()),this._CalculateDeviceTransformMatrices(e,t,i,this._compositOffX,this._compositOffY,r,s),this._useFullSurface||e.RemoveScissorRect()}e.SetProjectionMatrix(r),e.SetModelViewMatrix(s)}_Redraw(){this._manager.Redraw(this)}_GetShaderParameters(e,t){return this._cbGetShaderParameters(this._shaderProgramIndices[e],t)}_SetProgramParameters(e,t){let r=this._rcTexDest,s=this._rcTexBounce,i=this._rcTexOriginal;e.IsWebGL()&&(tempRect2.copy(r),tempRect2.flipAround(1),r=tempRect2,tempRect3.copy(s),tempRect3.flipAround(1),s=tempRect3,tempRect4.copy(i),tempRect4.flipAround(1),i=tempRect4),this._DoSetProgramParameters(e,t,s,i,r,1/this._drawWidth,1/this._drawHeight)}_SetFirstBounceProgramParameters(e,t){let r=this._rcTexBounce,s=this._rcTexOriginal,i=1/this._drawWidth,a=1/this._drawHeight;if(this._cbGetSourceTextureInfo){let{srcTexRect:e,srcWidth:t,srcHeight:n}=this._cbGetSourceTextureInfo(this._contentObject);e||(tempRect.set(0,0,0,0),e=tempRect),t||(t=this._drawWidth),n||(n=this._drawHeight),r=e,s=e,i=1/t,a=1/n}else e.IsWebGL()&&(tempRect3.copy(r),tempRect3.flipAround(1),r=tempRect3,tempRect4.copy(s),tempRect4.flipAround(1),s=tempRect4);let n=this._rcTexDest;e.IsWebGL()&&(n=tempRect2,n.copy(this._rcTexDest),n.flipAround(1)),this._DoSetProgramParameters(e,t,r,s,n,i,a),e.IsWebGPU()&&this._isAnyIsSrcTexRotated&&e.SetProgramParameter_IsSrcTexRotated(this._isSourceTextureRotated)}_GetBackTex(e){return this._isAnyShaderBackgroundBlending?e.IsWebGPU()?this._UseCopyTextureBackgroundSampling()?this._backTex:this._destRenderTarget.GetTexture():this._destRenderTarget:null}_DoSetProgramParameters(e,t,r,s,i,a,n){e.SetProgramParameters(this._GetBackTex(e),i,r,s,this._layoutRect,a,n,this._devicePixelRatio,this._layerScale,this._layerAngle,this._time),e.SetProgramCustomParameters(this._GetShaderParameters(t,e))}_Render_FastPath(e,t){const r=this._shaderProgramList[0],s=e.IsDepthEnabled(),i=r.UsesDepth();i&&(e.SetDepthEnabled(!1),e.SetDepthSamplingEnabled(!0),this._rcTexDest.set(0,0,1,1),this._rcTexOriginal.set(0,0,1,1)),e.SetProgram(r),e.SetBlendMode(this._blendMode),e.SetRenderTarget(this._destRenderTarget);let a=0,n=1;if(this._rcTexOriginal.set(0,0,1,1),r.UsesAnySrcRectOrPixelSize()&&this._cbGetSourceTextureInfo){const{srcTexRect:e,srcWidth:t,srcHeight:r}=this._cbGetSourceTextureInfo(this._contentObject);e&&this._rcTexOriginal.copy(e),a=Number.isFinite(t)?1/t:0,n=Number.isFinite(r)?1/r:0}else{const[t,r]=this._manager.GetDrawSize(e);a=1/t,n=1/r}t.layoutRect?this._layoutRect.copy(t.layoutRect):this._layoutRect.set(0,0,0,0),e.SetProgramParameters(this._GetBackTex(e),this._rcTexDest,this._rcTexOriginal,this._rcTexOriginal,this._layoutRect,a,n,this._devicePixelRatio,this._layerScale,this._layerAngle,this._time),e.SetProgramCustomParameters(this._GetShaderParameters(0,e)),e.IsWebGPU()&&this._isAnyIsSrcTexRotated&&e.SetProgramParameter_IsSrcTexRotated(this._isSourceTextureRotated),e.SetBaseZ(0),this._DrawContent(e),i&&(e.SetDepthSamplingEnabled(!1),e.SetDepthEnabled(s))}_UseCopyTextureBackgroundSampling(){return this._useCopyTextureBackgroundSampling}_UseRenderTargetBackgroundSampling(){return!this._useCopyTextureBackgroundSampling}IsAnyShaderBackgroundBlending(){return this._isAnyShaderBackgroundBlending}CanSkipCalculatingDrawSurfaceRect(){return!!this._canUseFastPath&&!this._UseCopyTextureBackgroundSampling()}UseFullSurface(){return this._useFullSurface}GetContentObject(){return this._contentObject}GetContextObject(){return this._contextObject}_GetBlendMode(){return this._blendMode}_UpdateOwnProjection(){return this._updateOwnProjection}DidChangeTransform(){return this._didChangeTransform}_GetDrawSurfaceRect(){return this._drawSurfaceRect}_GetRcTexBounce(){return this._rcTexBounce}_ShouldInvalidateRenderTargets(){return this._invalidateRenderTargets}async DebugLogRenderTargetContents(e,t,r){}};
}

// ../lib/gfx/effectCompositor/step.js
{
const C3=self.C3;C3.Gfx.EffectChain.Step=class{constructor(t,e,r,s=-1){this._effectChain=t,this._srcTargetId=e,this._destTargetId=r,this._index=s}GetEffectChain(){return this._effectChain}GetSrcTargetId(){return this._srcTargetId}GetDestTargetId(){return this._destTargetId}GetIndex(){return this._index}GetShaderProgram(){return this.GetEffectChain()._GetShaderProgramAt(this.GetIndex())}Run_WebGL(t,e,r){}Run_WebGPU(t,e,r){}};
}

// ../lib/gfx/effectCompositor/preDrawStep.js
{
const C3=self.C3;C3.Gfx.EffectChain.Step.PreDraw=class extends C3.Gfx.EffectChain.Step{constructor(e,t,n,a){super(e,t,n,a)}Run_WebGL(e,t,n){const a=this.GetEffectChain();e.SetAlphaBlend(),e.SetTextureFillMode(),e.SetRenderTarget(n,a._UpdateOwnProjection()),e.ClearRgba(0,0,0,0),a._DrawContent(e),a._ClampRcTexDest()}Run_WebGPU(e,t,n){const a=this.GetEffectChain();e.SetAlphaBlend(),e.SetTextureFillMode(),e.SetRenderTarget(n,!1),e.ClearRgba(0,0,0,0),a._DrawContent(e),a._ClampRcTexDest()}};
}

// ../lib/gfx/effectCompositor/postDrawStep.js
{
const C3=self.C3,tempRect=C3.New(C3.Rect),tempQuad=C3.New(C3.Quad);C3.Gfx.EffectChain.Step.PostDraw=class extends C3.Gfx.EffectChain.Step{constructor(e,t,r,a){super(e,t,r,a)}Run_WebGL(e,t,r){const a=this.GetEffectChain();e.SetTextureFillMode(),e.SetRenderTarget(r),a._SetDeviceTransform(e,!0),e.SetBlendMode(a._GetBlendMode()),e.SetTexture(t.GetTexture()),tempQuad.setFromRect(a._GetDrawSurfaceRect()),tempRect.copy(a._GetRcTexBounce()),tempRect.flipAround(1),e.Quad3(tempQuad,tempRect),a._ShouldInvalidateRenderTargets()&&e.InvalidateRenderTarget(t)}Run_WebGPU(e,t,r){const a=this.GetEffectChain();e.SetTextureFillMode(),e.SetRenderTarget(r,!1),a._IsRenderTargetSameSizeAndOffset(e)?tempQuad.setFromRect(a._GetRcTexBounce()):(e.SetNormalizedCoordsProgramVariant(!1),a._SetDeviceTransform(e,!0),tempQuad.setFromRect(a._GetDrawSurfaceRect())),e.SetBackTexture(null),e.SetBlendMode(a._GetBlendMode()),e.SetTexture(t.GetTexture()),a.UseFullSurface()?e.FullscreenQuad():e.Quad3(tempQuad,a._GetRcTexBounce())}};
}

// ../lib/gfx/effectCompositor/firstBounceStep.js
{
const C3=self.C3;C3.Gfx.EffectChain.Step.FirstBounce=class extends C3.Gfx.EffectChain.Step{constructor(e,t,r,a){super(e,t,r,a)}Run_WebGL(e,t,r){const a=this.GetEffectChain();e.SetRenderTarget(r,a._UpdateOwnProjection()),e.ClearRgba(0,0,0,0),e.SetCopyBlend(),e.SetProgram(this.GetShaderProgram()),a._SetFirstBounceProgramParameters(e,this.GetIndex()),a._DrawContent(e),a._ClampRcTexDest()}Run_WebGPU(e,t,r){const a=this.GetEffectChain();e.SetRenderTarget(r,!1),e.ClearRgba(0,0,0,0),e.SetCopyBlend(),e.SetProgram(this.GetShaderProgram()),a._SetFirstBounceProgramParameters(e,this.GetIndex()),a._DrawContent(e),a._ClampRcTexDest()}};
}

// ../lib/gfx/effectCompositor/bounceStep.js
{
const C3=self.C3,tempRect=C3.New(C3.Rect),tempQuad=C3.New(C3.Quad);C3.Gfx.EffectChain.Step.Bounce=class extends C3.Gfx.EffectChain.Step{constructor(e,t,r,a){super(e,t,r,a)}Run_WebGL(e,t,r){const a=this.GetEffectChain();e.SetRenderTarget(r);const d=0===this.GetDestTargetId();d?e.SetBlendMode(a._GetBlendMode()):(e.ClearRgba(0,0,0,0),e.SetCopyBlend()),e.SetProgram(this.GetShaderProgram()),a._SetProgramParameters(e,this.GetIndex()),e.SetTexture(t.GetTexture()),a._SetDeviceTransform(e,d),tempQuad.setFromRect(a._GetDrawSurfaceRect()),tempRect.copy(a._GetRcTexBounce()),tempRect.flipAround(1),e.Quad3(tempQuad,tempRect),a._ShouldInvalidateRenderTargets()&&e.InvalidateRenderTarget(t)}Run_WebGPU(e,t,r){const a=this.GetEffectChain();e.SetRenderTarget(r,!1);0===this.GetDestTargetId()?(e.SetBlendMode(a._GetBlendMode()),e.SetBackTexture(null),a._IsRenderTargetSameSizeAndOffset(e)?tempQuad.setFromRect(a._GetRcTexBounce()):(e.SetNormalizedCoordsProgramVariant(!1),a._SetDeviceTransform(e,!0),tempQuad.setFromRect(a._GetDrawSurfaceRect()))):(e.ClearRgba(0,0,0,0),e.SetCopyBlend(),tempQuad.setFromRect(a._GetRcTexBounce())),e.SetProgram(this.GetShaderProgram()),a._SetProgramParameters(e,this.GetIndex()),e.SetTexture(t.GetTexture()),a.UseFullSurface()?e.FullscreenQuad():e.Quad3(tempQuad,a._GetRcTexBounce())}};
}

// interfaces/IRuntime.js
{
const C3=self.C3,C3X=self.C3X;let runtime=null;const keysDownByKey=new Set;function SortZOrderList(e,t){const r=e[0]-t[0];if(0!==r)return r;return e[1]-t[1]}const tempZOrderList=[],tempInstances=[];let didWarnInAlertPolyfill=!1,didWarnFpsDeprecated=!1,didWarnCreateWorkerDeprecated=!1;const VALID_FRAMERATE_MODES=new Set(["vsync","unlimited-tick","unlimited-frame"]);self.IRuntime=class{constructor(e){runtime=e,Object.defineProperties(this,{assets:{value:runtime.GetAssetManager().GetIAssetManager(),writable:!1},collisions:{value:runtime.GetCollisionEngine().GetICollisionEngine(),writable:!1},objects:{value:{},writable:!1},globalVars:{value:{},writable:!1},projectName:{value:runtime.GetProjectName(),writable:!1},projectVersion:{value:runtime.GetProjectVersion(),writable:!1},projectId:{value:runtime.GetAppId(),writable:!1},projectUniqueId:{value:runtime.GetProjectUniqueId(),writable:!1},exportDate:{value:new Date(runtime.GetExportTimestamp()),writable:!1},storage:{value:new self.IStorage(runtime),writable:!1},isInWorker:{value:runtime.IsInWorker(),writable:!1},viewportWidth:{value:runtime.GetOriginalViewportWidth(),writable:!1},viewportHeight:{value:runtime.GetOriginalViewportHeight(),writable:!1},sampling:{value:runtime.GetSampling(),writable:!1},isPixelRoundingEnabled:{value:runtime.IsPixelRoundingEnabled(),writable:!1},platformInfo:{value:new self.IPlatformInfo(e),writable:!1},sdk:{value:new self.ISDKUtils(e),writable:!1}}),runtime.UserScriptDispatcher().addEventListener("keydown",(e=>{keysDownByKey.has(e["key"])?e.stopPropagation():keysDownByKey.add(e["key"])})),runtime.UserScriptDispatcher().addEventListener("keyup",(e=>keysDownByKey.delete(e["key"]))),runtime.Dispatcher().addEventListener("window-blur",(()=>keysDownByKey.clear())),runtime.IsInWorker()&&(self["alert"]=e=>(didWarnInAlertPolyfill||(didWarnInAlertPolyfill=!0,console.warn("[Construct] alert() was called from a Web Worker, because the project 'Use worker' setting is enabled. This method is not normally available in a Web Worker. Construct has implemented the alert for you, but note that other features may be missing in worker mode. You may wish to disable 'Use worker', or use a more convenient function like console.log(). For more information please refer to the scripting section of the manual.")),this.alert(e)))}_InitObjects(e){Object.defineProperties(this.objects,e)}_InitGlobalVars(e){Object.defineProperties(this.globalVars,e)}addEventListener(e,t){runtime.UserScriptDispatcher().addEventListener(e,t)}removeEventListener(e,t){runtime.UserScriptDispatcher().removeEventListener(e,t)}callFunction(e,...t){C3X.RequireString(e);const r=runtime.GetEventSheetManager(),n=r.GetFunctionBlockByName(e);if(!n)throw new Error(`cannot find function name '${e}'`);if(!n.IsEnabled())return n.GetDefaultReturnValue();if(t.length<n.GetFunctionParameterCount())throw new Error(`not enough function parameters passed for '${e}' (${t.length} passed, ${n.GetFunctionParameterCount()} expected)`);const i=n.GetEventBlock();let o=i.GetSolModifiersIncludingParents();const a=r.GetCurrentEvent();if(a){o=o.slice(0);const e=new Set(o);for(const t of a.GetSolModifiersIncludingParents())e.has(t)||(o.push(t),e.add(t));for(const t of r.GetDynamicSolModifiersSet())e.has(t)||(o.push(t),e.add(t))}return i.RunAsExpressionFunctionCall(o,n.IsCopyPicked(),n.GetReturnType(),n.GetDefaultReturnValue(),...t)}setReturnValue(e){const t=runtime.GetEventStack().GetCurrentExpFuncStackFrame();if(!t)throw new Error("not in a function which returns a value");switch(t.GetFunctionReturnType()){case 1:"number"==typeof e&&t.SetFunctionReturnValue(e);break;case 2:"string"==typeof e&&t.SetFunctionReturnValue(e);break;case 3:"number"!=typeof e&&"string"!=typeof e||t.SetFunctionReturnValue(e)}}signal(e){C3X.RequireString(e),runtime.GetEventSheetManager().Signal(e)}waitForSignal(e){return C3X.RequireString(e),runtime.GetEventSheetManager().WaitForSignal(e)}getViewportSize(){return[runtime.GetOriginalViewportWidth(),runtime.GetOriginalViewportHeight()]}get isSuspended(){return runtime.IsSuspended()}get dt(){return runtime.GetDt()}get dtRaw(){return runtime.GetDtRaw()}get gameTime(){return runtime.GetGameTime()}get tickCount(){return runtime.GetTickCount()}get wallTime(){return runtime.GetWallTime()}get timeScale(){return runtime.GetTimeScale()}set timeScale(e){C3X.RequireFiniteNumber(e),runtime.SetTimeScale(e)}get fps(){return didWarnFpsDeprecated||(console.warn("IRuntime.fps is deprecated. Use IRuntime.framesPerSecond instead."),didWarnFpsDeprecated=!0),runtime.GetFramesPerSecond()}get framesPerSecond(){return runtime.GetFramesPerSecond()}get ticksPerSecond(){return runtime.GetTicksPerSecond()}get cpuUtilisation(){return runtime.GetMainThreadTime()}get gpuUtilisation(){return runtime.GetGPUUtilisation()}get framerateMode(){return runtime.GetFramerateMode()}set framerateMode(e){if(!VALID_FRAMERATE_MODES.has(e))throw new Error("invalid framerate mode");runtime._SetFramerateMode(e)}get minDt(){return runtime.GetMinDt()}set minDt(e){C3X.RequireFiniteNumber(e),runtime.SetMinDt(e)}get maxDt(){return runtime.GetMaxDt()}set maxDt(e){runtime.SetMaxDt(e)}get loadingProgress(){return runtime.GetAssetManager().GetLoadProgress()}get imageLoadingProgress(){return runtime.GetAssetManager().GetImageLoadProgress()}random(){return runtime.Random()}get layout(){const e=runtime.GetMainRunningLayout();if(!e)throw new Error("no layout is running - make sure a layout is loaded before accessing");return e.GetILayout()}getLayout(e){const t=runtime.GetLayoutManager();let r=null;if("number"!=typeof e&&"string"!=typeof e)throw new TypeError("expected string or number");if(r=t.GetLayout(e),!r)throw new Error("invalid layout");return r.GetILayout()}getAllLayouts(){return runtime.GetLayoutManager().GetAllLayouts().map((e=>e.GetILayout()))}goToLayout(e){const t=runtime.GetLayoutManager();let r=null;if("number"!=typeof e&&"string"!=typeof e)throw new TypeError("expected string or number");if(r=t.GetLayout(e),!r)throw new Error("invalid layout");t.IsPendingChangeMainLayout()||t.ChangeMainLayout(r)}get keyboard(){const e=runtime._GetCommonScriptInterfaces().keyboard;if(!e)throw new Error("runtime.keyboard used but Keyboard object missing - add it to your project first");return e}get mouse(){const e=runtime._GetCommonScriptInterfaces().mouse;if(!e)throw new Error("runtime.mouse used but Mouse object missing - add it to your project first");return e}get touch(){const e=runtime._GetCommonScriptInterfaces().touch;if(!e)throw new Error("runtime.touch used but Touch object missing - add it to your project first");return e}get timelineController(){const e=runtime._GetCommonScriptInterfaces().timelineController;if(!e)throw new Error("runtime.timelineController used but Timeline Controller object missing - add it to your project first");return e}invokeDownload(e,t){C3X.RequireString(e),C3X.RequireString(t),runtime.InvokeDownload(e,t)}getInstanceByUid(e){C3X.RequireFiniteNumber(e);const t=runtime.GetInstanceByUID(e);return t?t.GetInterfaceClass():null}sortZOrder(e,t){C3X.RequireFunction(t);const r=runtime.GetCurrentLayout();for(const t of e){const e=runtime._UnwrapIWorldInstance(t),r=e.GetWorldInfo();tempZOrderList.push([r.GetLayer().GetIndex(),r.GetZIndex()]),tempInstances.push(e)}if(0===tempZOrderList.length)return;tempZOrderList.sort(SortZOrderList),tempInstances.sort(((e,r)=>t(e.GetInterfaceClass(),r.GetInterfaceClass())));let n=!1;for(let e=0,t=tempZOrderList.length;e<t;++e){const t=tempInstances[e],i=r.GetLayerByIndex(tempZOrderList[e][0]),o=tempZOrderList[e][1],a=i._GetInstances();a[o]!==t&&(a[o]=t,t.GetWorldInfo()._SetLayer(i,!0),i.SetZIndicesChanged(t),n=!0)}n&&runtime.UpdateRender(),C3.clearArray(tempZOrderList),C3.clearArray(tempInstances)}async createWorker(e,t){didWarnCreateWorkerDeprecated||(console.warn("IRuntime.createWorker() is deprecated. All modern browsers now support nested workers so this method is no longer needed."),didWarnCreateWorkerDeprecated=!0);const r=new MessageChannel,n=r.port1,i=r.port2;return await runtime.PostComponentMessageToDOMAsync("runtime","script-create-worker",{"url":e,"opts":t,"port2":i},[i]),n}alert(e){return runtime.PostComponentMessageToDOMAsync("runtime","alert",{"message":e+(runtime.IsInWorker()?" [via Web Worker]":"")})}getHTMLLayer(e){return C3X.RequireFiniteNumber(e),runtime._GetHTMLLayerWrapElement(e)}addLoadPromise(e){runtime.AddLoadPromise(e)}async saveCanvasImage(e,t,r){C3X.RequireOptionalString(e),C3X.RequireOptionalNumber(t),C3X.RequireOptionalInstanceOf(r,DOMRect),r||(r=new DOMRect(0,0,0,0));const n=runtime.GetCanvasManager();if(!n)return;runtime.UpdateRender();const i=await n.SnapshotCanvas(e||"image/png",t,r.x,r.y,r.width,r.height);return await runtime.TriggerAsync(C3.Plugins.System.Cnds.OnCanvasSnapshot,null),i}};
}

// interfaces/other/IAssetManager.js
{
const C3=self.C3,C3X=self.C3X;let assetManager=null;self.IAssetManager=class{constructor(e){assetManager=e,Object.defineProperties(this,{isWebMOpusSupported:{value:!0,writable:!1}})}loadImageAsset(e){const t=self.IImageInfo._Unwrap(e);if(!t)throw new Error("invalid IImageInfo");t.LoadAsset(assetManager.GetRuntime())}fetchText(e){return assetManager.FetchText(e)}fetchJson(e){return assetManager.FetchJson(e)}fetchBlob(e){return assetManager.FetchBlob(e)}fetchArrayBuffer(e){return assetManager.FetchArrayBuffer(e)}getProjectFileUrl(e){return assetManager.GetProjectFileUrl(e)}getMediaFileUrl(e){return"flat"===assetManager.GetFileStructure()&&C3.IsRelativeURL(e)&&(e=e.toLowerCase()),assetManager.GetMediaFileUrl(e)}get mediaFolder(){return assetManager.GetMediaSubfolder()}async decodeWebMOpus(e,t){throw new Error("decodeWebMOpus() is no longer supported - use Web Audio's decodeAudioData() directly as all supported platforms now support WebM Opus")}loadScripts(...e){return assetManager.LoadScripts(...e)}compileWebAssembly(e){return assetManager.CompileWebAssembly(e)}loadStyleSheet(e){return assetManager.LoadStyleSheet(e)}};
}

// interfaces/other/ICollisionEngine.js
{
const C3=self.C3,C3X=self.C3X;let collisionEngine=null;self.ICollisionEngine=class{constructor(n){collisionEngine=n,Object.defineProperties(this,{runtime:{value:collisionEngine.GetRuntime(),writable:!1}})}testOverlap(n,e){const l=collisionEngine.GetRuntime(),i=l._UnwrapIWorldInstance(n),t=l._UnwrapIWorldInstance(e);return collisionEngine.TestOverlap(i,t)}testOverlapAny(n,e){const l=collisionEngine.GetRuntime(),i=l._UnwrapIWorldInstance(n);for(const n of e){const e=l._UnwrapIWorldInstance(n);if(collisionEngine.TestOverlap(i,e))return n}return null}testOverlapSolid(n){const e=collisionEngine.GetRuntime()._UnwrapIWorldInstance(n),l=collisionEngine.TestOverlapSolid(e);return l?l.GetInterfaceClass():null}setCollisionCellSize(n,e){if(C3X.RequireFiniteNumber(n),C3X.RequireFiniteNumber(e),n=Math.floor(n),e=Math.floor(e),n<=0||e<=0)throw new Error("invalid cell size");collisionEngine.SetCollisionCellSize(n,e)}getCollisionCellSize(){return collisionEngine.GetCollisionCellSize()}getCollisionCandidates(n,e){const l=collisionEngine.GetRuntime();let i;i=Array.isArray(n)?n.map((n=>l._UnwrapIObjectClass(n))):[l._UnwrapIObjectClass(n)];const t=C3.Rect.FromObject(e),o=[];return collisionEngine.GetObjectClassesCollisionCandidates(null,i,t,o),o.map((n=>n.GetInterfaceClass()))}};
}

// interfaces/other/IPlatformInfo.js
{
const C3=self.C3,C3X=self.C3X;let runtime=null;const osMap=new Map([["Windows","windows"],["macOS","macos"],["Linux","linux"],["Chrome OS","chrome-os"],["Android","android"],["iOS","ios"]]),browserMap=new Map([["Chrome","chrome"],["Chromium","chromium"],["Edge","edge"],["Opera","opera"],["NW.js","nwjs"],["Firefox","firefox"],["Safari","safari"]]),browserEngineMap=new Map([["Chromium","chromium"],["Gecko","gecko"],["WebKit","webkit"]]);self.IPlatformInfo=class{constructor(e){runtime=e,Object.defineProperties(this,{isMobile:{value:C3.Platform.IsMobile,writable:!1},os:{value:osMap.get(C3.Platform.OS)||"unknown",writable:!1},osVersion:{value:C3.Platform.OSVersion,writable:!1},browser:{value:browserMap.get(C3.Platform.Browser)||"unknown",writable:!1},browserVersion:{value:C3.Platform.BrowserVersion,writable:!1},browserEngine:{value:browserEngineMap.get(C3.Platform.BrowserEngine)||"unknown",writable:!1}})}get exportType(){let e=runtime.GetExportType();return runtime.IsNWjs()?e="nwjs":runtime.IsWindowsWebView2()?e="windows-webview2":"cordova"===e?e="Android"===C3.Platform.OS?"cordova-android":"cordova-ios":"playable-ad-single-file"!==e&&"playable-ad-zip"!==e||(e="playable-ad"),e}get renderer(){return runtime.GetCanvasManager().GetRendererString()}get rendererDetail(){return runtime.GetCanvasManager().GetRendererDetailString()}get canvasClientX(){return runtime.GetCanvasManager().GetCanvasClientX()}get canvasClientY(){return runtime.GetCanvasManager().GetCanvasClientY()}get canvasCssWidth(){return runtime.GetCanvasManager().GetCssWidth()}get canvasCssHeight(){return runtime.GetCanvasManager().GetCssHeight()}get canvasDeviceWidth(){return runtime.GetCanvasManager().GetDeviceWidth()}get canvasDeviceHeight(){return runtime.GetCanvasManager().GetDeviceHeight()}get devicePixelRatio(){return runtime.GetDevicePixelRatio()}};
}

// interfaces/other/IStorage.js
{
const C3=self.C3,C3X=self.C3X;self.IStorage=class{constructor(e){this._storage=e._GetProjectStorage()}getItem(e){return C3X.RequireString(e),this._storage.getItem(e)}setItem(e,t){return C3X.RequireString(e),this._storage.setItem(e,t)}removeItem(e){return C3X.RequireString(e),this._storage.removeItem(e)}clear(){return this._storage.clear()}keys(){return this._storage.keys()}};
}

// interfaces/objects/IPlugin.js
{
const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.IPlugin=class{#e;constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e,Object.defineProperties(this,{runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},id:{value:e.GetID(),writable:!1},isSingleGlobal:{value:e.IsSingleGlobal(),writable:!1},isWorldType:{value:e.IsWorldType(),writable:!1},isHTMLElementType:{value:e.IsHTMLElementType(),writable:!1},isRotatable:{value:e.IsRotatable(),writable:!1},hasEffects:{value:e.HasEffects(),writable:!1},is3d:{value:e.Is3D(),writable:!1},supportsHierarchies:{value:e.SupportsSceneGraph(),writable:!1},supportsMesh:{value:e.SupportsMesh(),writable:!1}}),e.GetRuntime()._MapScriptInterface(this,e)}static getByConstructor(e){if(!e)return null;const t=C3.AddonManager.GetPluginByConstructorFunction(e);return t?t.GetIPlugin():null}getSingleGlobalObjectType(){return this.#e.GetSingleGlobalObjectClass().GetIObjectClass()}getSingleGlobalInstance(){return this.#e.GetSingleGlobalInstance().GetInterfaceClass()}};
}

// interfaces/objects/IObjectClass.js
{
const C3=globalThis.C3,C3X=globalThis.C3X,internalApiToken=C3._GetInternalAPIToken();globalThis.IObjectClass=class{#e;constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e,Object.defineProperties(this,{name:{value:e.GetName(),writable:!1},runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},plugin:{value:e.GetPlugin().GetIPlugin(),writable:!1}}),e.GetRuntime()._MapScriptInterface(this,e)}addEventListener(e,t){C3X.RequireString(e),C3X.RequireFunction(t),this.#e.UserScriptDispatcher().addEventListener(e,t)}removeEventListener(e,t){C3X.RequireString(e),C3X.RequireFunction(t),this.#e.UserScriptDispatcher().removeEventListener(e,t)}getAllInstances(){return[...this.instances()]}getFirstInstance(){return C3.first(this.instances())}getPickedInstances(){return[...this.pickedInstances()]}getFirstPickedInstance(){return C3.first(this.pickedInstances())}getPairedInstance(e){const t=this.#e,n=t.GetRuntime()._UnwrapIInstance(e),i=t.GetPairedInstance(n);return i?i.GetInterfaceClass():null}*instances(){for(const e of this.#e.instancesIncludingPendingCreate())yield e.GetInterfaceClass()}*pickedInstances(){for(const e of this.#e.GetCurrentSol().GetInstances())yield e.GetInterfaceClass()}};
}

// interfaces/objects/IObjectType.js
{
const C3=globalThis.C3,C3X=globalThis.C3X,internalApiToken=C3._GetInternalAPIToken();globalThis.IObjectType=class extends globalThis.IObjectClass{#e;constructor(){super();const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e}setInstanceClass(e){C3X.RequireFunction(e);const t=this.#e;if(t.GetInstanceCount()>0)throw new Error("setInstanceClass() called too late, because instances have already been created - call in runOnStartup");t._SetUserScriptInstanceClass(e)}createInstance(e,t,n,a,s){if(C3X.RequireNumber(t),C3X.RequireNumber(n),"number"!=typeof e&&"string"!=typeof e)throw new TypeError("invalid layer parameter");const r=this.#e,i=r.GetRuntime(),l=i.GetMainRunningLayout().GetLayer(e);if(!l)throw new Error("invalid layer");const c=i.CreateInstance(r,l,t,n,a,s);a&&l.SortAndAddInstancesByZIndex(c);const o=i.GetEventSheetManager();return o.BlockFlushingInstances(!0),c._TriggerOnCreatedOnSelfAndRelated(),o.BlockFlushingInstances(!1),o.IsInEventEngine()||i.GetLayoutManager().IsEndingLayout()||i.FlushPendingInstances(),c.GetInterfaceClass()}getAllFamilies(){return this.#e.GetFamilies().map((e=>e.GetIObjectClass()))}*families(){for(const e of this.#e.GetFamilies())yield e.GetIObjectClass()}isInFamily(e){return C3X.RequireInstanceOf(e,globalThis.IFamily),e.hasObjectType(this)}};
}

// interfaces/objects/IFamily.js
{
const C3=globalThis.C3,C3X=globalThis.C3X,IObjectType=globalThis.IObjectType,internalApiToken=C3._GetInternalAPIToken();globalThis.IFamily=class extends globalThis.IObjectClass{#e;constructor(){super();const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e}getAllObjectTypes(){return this.#e.GetFamilyMembers().map((e=>e.GetIObjectClass()))}*objectTypes(){for(const e of this.#e.GetFamilyMembers())yield e.GetIObjectClass()}hasObjectType(e){C3X.RequireInstanceOf(e,IObjectType);const t=this.#e,s=t.GetRuntime()._UnwrapIObjectClass(e);return t.FamilyHasMember(s)}};
}

// interfaces/layouts/ILayout.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap,VALID_WHERE_STRINGS=["above","below","top-sublayer","bottom-sublayer"];self.ILayout=class{constructor(e){map.set(this,e);const t=[],r=e.GetEffectList(),i=r.GetAllEffectTypes().length;for(let e=0;e<i;++e)t.push(new self.IEffectInstance(r,e));Object.defineProperties(this,{name:{value:e.GetName(),writable:!1},index:{value:e.GetIndex(),writable:!1},effects:{value:t,writable:!1}})}addEventListener(e,t){C3X.RequireString(e),C3X.RequireFunction(t),map.get(this).UserScriptDispatcher().addEventListener(e,t)}removeEventListener(e,t){C3X.RequireString(e),C3X.RequireFunction(t),map.get(this).UserScriptDispatcher().removeEventListener(e,t)}get width(){return map.get(this).GetWidth()}set width(e){C3X.RequireFiniteNumber(e),map.get(this).SetWidth(e)}get height(){return map.get(this).GetHeight()}set height(e){C3X.RequireFiniteNumber(e),map.get(this).SetHeight(e)}setSize(e,t){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(t);const r=map.get(this);r.SetWidth(e),r.SetHeight(t)}getSize(){const e=map.get(this);return[e.GetWidth(),e.GetHeight()]}set scale(e){C3X.RequireFiniteNumber(e),map.get(this).SetScale(e)}get scale(){return map.get(this).GetScale()}set angle(e){C3X.RequireFiniteNumber(e),map.get(this).SetAngle(e)}get angle(){return map.get(this).GetAngle()}set scrollX(e){C3X.RequireNumber(e),map.get(this).SetScrollX(e)}get scrollX(){return map.get(this).GetScrollX()}set scrollY(e){C3X.RequireNumber(e),map.get(this).SetScrollY(e)}get scrollY(){return map.get(this).GetScrollY()}scrollTo(e,t){C3X.RequireNumber(e),C3X.RequireNumber(t);const r=map.get(this);r.SetScrollX(e),r.SetScrollY(t)}getScrollPosition(){const e=map.get(this);return[e.GetScrollX(),e.GetScrollY()]}getLayer(e){const t=map.get(this);let r=null;if("number"!=typeof e&&"string"!=typeof e)throw new TypeError("expected string or number");return r=t.GetLayer(e),r?r.GetILayer():null}getAllLayers(){return map.get(this).GetLayers().map((e=>e.GetILayer()))}*allLayers(){for(const e of map.get(this).allLayers())yield e.GetILayer()}addLayer(e,t,r){const i=map.get(this),n=self.ILayer;C3X.RequireString(e),C3X.RequireOptionalInstanceOf(t,n);const s=t?i.GetRuntime()._UnwrapScriptInterface(t):null,a=VALID_WHERE_STRINGS.indexOf(r);if(a<0)throw new Error("invalid location");i.AddLayer(e,s,a)}moveLayer(e,t,r){const i=map.get(this),n=i.GetRuntime(),s=self.ILayer;C3X.RequireInstanceOf(e,s);const a=n._UnwrapScriptInterface(e);if(!a)throw new Error("invalid layer");C3X.RequireOptionalInstanceOf(t,s);const o=t?n._UnwrapScriptInterface(t):null,l=VALID_WHERE_STRINGS.indexOf(r);if(l<0)throw new Error("invalid location");i.MoveLayer(a,o,l)}removeLayer(e){const t=map.get(this),r=self.ILayer;C3X.RequireInstanceOf(e,r);const i=t.GetRuntime()._UnwrapScriptInterface(e);if(!i)throw new Error("invalid layer");const n=i.GetRuntime();t.RemoveLayer(i),n.GetEventSheetManager().IsInEventEngine()||n.FlushPendingInstances()}removeAllDynamicLayers(){const e=map.get(this),t=e.GetRuntime();e.RemoveAllDynamicLayers(),t.GetEventSheetManager().IsInEventEngine()||t.FlushPendingInstances()}setVanishingPoint(e,t){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(t),map.get(this).SetVanishingPointXY(e,t)}getVanishingPoint(){return map.get(this)._GetVanishingPoint()}set projection(e){C3X.RequireString(e);const t=map.get(this);if("perspective"===e)t.SetPerspectiveProjection();else{if("orthographic"!==e)throw new Error("invalid projection");t.SetOrthographicProjection()}}get projection(){return map.get(this).IsOrthographicProjection()?"orthographic":"perspective"}};
}

// interfaces/layouts/ILayer.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap,BLEND_MODE_TO_INDEX=new Map([["normal",0],["additive",1],["copy",3],["destination-over",4],["source-in",5],["destination-in",6],["source-out",7],["destination-out",8],["source-atop",9],["destination-atop",10]]),INDEX_TO_BLEND_MODE=new Map([...BLEND_MODE_TO_INDEX.entries()].map((e=>[e[1],e[0]]))),VALID_RENDERING_MODES=new Set(["2d","3d"]),tempColor=C3.New(C3.Color);self.ILayer=class{constructor(e){map.set(this,e);const t=[],r=e.GetEffectList(),a=r.GetAllEffectTypes().length;for(let e=0;e<a;++e)t.push(new self.IEffectInstance(r,e));Object.defineProperties(this,{name:{value:e.GetName(),writable:!1},layout:{value:e.GetLayout().GetILayout(),writable:!1},effects:{value:t,writable:!1}}),e.GetRuntime()._MapScriptInterface(this,e)}get parentLayer(){const e=map.get(this).GetParentLayer();return e?e.GetILayer():null}*parentLayers(){for(const e of map.get(this).parentLayers())yield e.GetILayer()}*subLayers(){for(const e of map.get(this).GetSubLayers())yield e.GetILayer()}*allSubLayers(){for(const e of map.get(this).GetSubLayers())for(const t of e.selfAndAllSubLayers())yield t.GetILayer()}get index(){return map.get(this).GetIndex()}get isVisible(){return map.get(this)._IsVisibleFlagSet()}set isVisible(e){map.get(this).SetVisible(e)}get isSelfAndParentsVisible(){return map.get(this).IsVisible()}get isInteractive(){return map.get(this).IsInteractive()}set isInteractive(e){map.get(this).SetInteractive(e)}get isHTMLElementsLayer(){return map.get(this).IsHTMLElementsLayer()}set isHTMLElementsLayer(e){map.get(this).SetIsHTMLElementsLayer(!!e)}get isSelfAndParentsInteractive(){return map.get(this).IsSelfAndParentsInteractive()}get opacity(){return map.get(this).GetOpacity()}set opacity(e){e=C3.clamp(+e,0,1),isNaN(e)||map.get(this).SetOpacity(e)}set scale(e){C3X.RequireFiniteNumber(e),map.get(this).SetOwnScale(e)}get scale(){return map.get(this).GetOwnScale()}set scaleRate(e){C3X.RequireFiniteNumber(e),map.get(this).SetScaleRate(e)}get scaleRate(){return map.get(this).GetScaleRate()}set angle(e){C3X.RequireFiniteNumber(e),map.get(this).SetAngle(e)}get angle(){return map.get(this).GetOwnAngle()}set parallaxX(e){C3X.RequireFiniteNumber(e),map.get(this).SetParallaxX(e)}get parallaxX(){return map.get(this).GetParallaxX()}set parallaxY(e){C3X.RequireFiniteNumber(e),map.get(this).SetParallaxY(e)}get parallaxY(){return map.get(this).GetParallaxY()}set zElevation(e){C3X.RequireFiniteNumber(e),map.get(this).SetZElevation(e)}get zElevation(){return map.get(this).GetZElevation()}set renderingMode(e){if(!VALID_RENDERING_MODES.has(e))throw TypeError("invalid rendering mode");map.get(this).SetRenderAs3D("3d"===e)}get renderingMode(){return map.get(this).IsRenderAs3D()?"3d":"2d"}set isTransparent(e){map.get(this).SetTransparent(e)}get isTransparent(){return map.get(this).IsTransparent()}set isForceOwnTexture(e){map.get(this).SetForceOwnTexture(e)}get isForceOwnTexture(){return map.get(this).IsForceOwnTexture()}set blendMode(e){C3X.RequireString(e);const t=BLEND_MODE_TO_INDEX.get(e);if("number"!=typeof t)throw new Error("invalid blend mode");map.get(this).SetBlendMode(t)}get blendMode(){return INDEX_TO_BLEND_MODE.get(map.get(this).GetBlendMode())}set backgroundColor(e){if(C3X.RequireArray(e),e.length<3)throw new Error("expected 3 elements");tempColor.setRgb(e[0],e[1],e[2]);const t=map.get(this),r=t.GetBackgroundColor();r.equalsIgnoringAlpha(tempColor)||(r.copyRgb(tempColor),t.GetRuntime().UpdateRender())}get backgroundColor(){const e=map.get(this).GetBackgroundColor();return[e.getR(),e.getG(),e.getB()]}set scrollX(e){C3X.RequireNumber(e);const t=map.get(this);t.SetOwnScrollPositionEnabled(!0),t.SetScrollX(e)}get scrollX(){return map.get(this).GetScrollX()}set scrollY(e){C3X.RequireNumber(e);const t=map.get(this);t.SetOwnScrollPositionEnabled(!0),t.SetScrollY(e)}get scrollY(){return map.get(this).GetScrollY()}scrollTo(e,t){C3X.RequireNumber(e),C3X.RequireNumber(t);const r=map.get(this);r.SetOwnScrollPositionEnabled(!0),r.SetScrollX(e),r.SetScrollY(t)}getScrollPosition(){const e=map.get(this);return[e.GetScrollX(),e.GetScrollY()]}restoreScrollPosition(){map.get(this).SetOwnScrollPositionEnabled(!1)}getViewport(){return map.get(this).GetViewport().toDOMRect()}cssPxToLayer(e,t,r=0){C3X.RequireNumber(e),C3X.RequireNumber(t),C3X.RequireNumber(r);const a=map.get(this),s=a.GetRuntime();return a.CanvasCssToLayer(e-s.GetCanvasClientX(),t-s.GetCanvasClientY(),r)}layerToCssPx(e,t,r=0){C3X.RequireNumber(e),C3X.RequireNumber(t),C3X.RequireNumber(r);const a=map.get(this),s=a.GetRuntime(),[i,n]=a.LayerToCanvasCss(e,t,r);return[i+s.GetCanvasClientX(),n+s.GetCanvasClientY()]}drawSurfaceToLayer(e,t,r=0){return C3X.RequireNumber(e),C3X.RequireNumber(t),C3X.RequireNumber(r),map.get(this).DrawSurfaceToLayer(e,t,r)}layerToDrawSurface(e,t,r=0){return C3X.RequireNumber(e),C3X.RequireNumber(t),C3X.RequireNumber(r),map.get(this).LayerToDrawSurface(e,t,r)}get renderScale(){return map.get(this).GetRenderScale()}};
}

// interfaces/objects/IInstance.js
{
const C3=self.C3,C3X=self.C3X,dispatchers=new WeakMap,internalApiToken=C3._GetInternalAPIToken();function GetDispatcher(e){let t=dispatchers.get(e);return t||(t=C3.New(C3.Event.Dispatcher),dispatchers.set(e,t),t)}self.IInstance=class{#e;constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e;const t={runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},objectType:{value:e.GetObjectClass().GetIObjectClass(),writable:!1},plugin:{value:e.GetPlugin().GetIPlugin(),writable:!1}};e._GetInstVarsScriptDescriptor(t),e._GetBehaviorsScriptDescriptor(t),Object.defineProperties(this,t),e.GetRuntime()._MapScriptInterface(this,e)}static _GetInitInst(){return C3.AddonManager._GetInitObject()}_release(){const e=dispatchers.get(this);e&&(e.Release(),dispatchers.delete(this))}addEventListener(e,t,i){C3X.RequireString(e),C3X.RequireFunction(t),GetDispatcher(this).addEventListener(e,t,i)}removeEventListener(e,t,i){C3X.RequireString(e),C3X.RequireFunction(t),GetDispatcher(this).removeEventListener(e,t,i)}dispatchEvent(e){GetDispatcher(this).dispatchEvent(e)}destroy(){const e=this.#e,t=e.GetRuntime();t.DestroyInstance(e),t.GetEventSheetManager().IsInEventEngine()||t.GetLayoutManager().IsEndingLayout()||t.GetEventSheetManager().IsFlushingBlocked()||t.FlushPendingInstances()}getOtherContainerInstances(){const e=this.#e.GetSiblings();return e?e.map((e=>e.GetInterfaceClass())):[]}*otherContainerInstances(){const e=this.#e;if(e.IsInContainer())for(const t of e.siblings())yield t.GetInterfaceClass()}get uid(){return this.#e.GetUID()}get iid(){return this.#e.GetIID()}get templateName(){return this.#e.GetTemplateName()}set timeScale(e){C3X.RequireFiniteNumber(e),this.#e.SetTimeScale(e)}get timeScale(){return this.#e.GetActiveTimeScale()}restoreTimeScale(){this.#e.RestoreTimeScale()}get dt(){const e=this.#e;return e.GetRuntime().GetDt(e)}hasTags(...e){C3X.RequireArray(e);const t=new Set(e),i=this.#e.GetTagsSet();return t.isSubsetOf(i)}setAllTags(e){C3X.RequireInstanceOf(e,Set),this.#e.SetTagsSet(e)}getAllTags(){return new Set(this.#e.GetTagsSet())}signal(e){C3X.RequireString(e);const t=this.#e;t.GetRuntime().GetEventSheetManager().InstanceSignal(t,e)}waitForSignal(e){C3X.RequireString(e);const t=this.#e;return t.GetRuntime().GetEventSheetManager().WaitForInstanceSignal(t,e)}};
}

// interfaces/sdk/ISDKInstanceBase.js
{
const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.ISDKInstanceBase=class extends self.IInstance{#e;#t=!1;#n=null;#i=!1;#r=null;#s;#o;constructor(e){super(),this.#e=C3.AddonManager._GetInitObject2(internalApiToken),this.#t=!1,this.#n=null,this.#i=!1,this.#r=null,this.#s=e?.domComponentId,this.#o=e?.wrapperComponentId}_release(){this._setTicking(!1),this._setTicking2(!1),super._release()}_getInitProperties(){return C3.AddonManager._GetInitProperties()}_trigger(e){const t=this.#e;t.GetRuntime().Trigger(e,t)}_triggerAsync(e){const t=this.#e;return t.GetRuntime().TriggerAsync(e,t)}_addDOMMessageHandler(e,t){if(C3X.RequireString(e),C3X.RequireFunction(t),!this.#s)throw new Error("no DOM component id set");this.#e.GetRuntime().AddDOMComponentMessageHandler(this.#s,e,t)}_addDOMMessageHandlers(e){C3X.RequireArray(e);for(const[t,n]of e)this._addDOMMessageHandler(t,n)}_postToDOM(e,t){if(C3X.RequireString(e),!this.#s)throw new Error("no DOM component id set");this.#e.GetRuntime().PostComponentMessageToDOM(this.#s,e,t)}_postToDOMAsync(e,t){if(C3X.RequireString(e),!this.#s)throw new Error("no DOM component id set");return this.#e.GetRuntime().PostComponentMessageToDOMAsync(this.#s,e,t)}_postToDOMMaybeSync(e,t){if(!this.#e.GetRuntime().IsInWorker())return window["c3_runtimeInterface"]["_OnMessageFromRuntime"]({"type":"event","component":this.#s,"handler":e,"data":t,"responseId":null});this._postToDOM(e,t)}_setTicking(e){if(e=!!e,this.#t===e)return;this.#t=e;const t=this.#e.GetRuntime();if(e){if(!this.#n)if(this.#e.GetRuntime().IsDebug()){const e=globalThis.C3Debugger,t=this.plugin;this.#n=()=>{const n=performance.now();this._tick(),e.AddIndividualPluginTickTime(t,performance.now()-n)}}else this.#n=()=>this._tick();t.Dispatcher().addEventListener("tick",this.#n)}else t.Dispatcher().removeEventListener("tick",this.#n)}_isTicking(){return this.#t}_tick(){}_setTicking2(e){if(e=!!e,this.#i===e)return;this.#i=e;const t=this.#e.GetRuntime();if(e){if(!this.#r)if(this.#e.GetRuntime().IsDebug()){const e=globalThis.C3Debugger,t=this.plugin;this.#r=()=>{const n=performance.now();this._tick2(),e.AddIndividualPluginTickTime(t,performance.now()-n)}}else this.#r=()=>this._tick2();t.Dispatcher().addEventListener("tick2",this.#r)}else t.Dispatcher().removeEventListener("tick2",this.#r)}_isTicking2(){return this.#i}_tick2(){}_getDebuggerProperties(){return[]}_saveToJson(){return null}_loadFromJson(e){}_isWrapperExtensionAvailable(){if(!this.#o)throw new Error("no wrapper component id set");return this.#e.GetRuntime().HasWrapperComponentId(this.#o)}_addWrapperExtensionMessageHandler(e,t){if(C3X.RequireString(e),C3X.RequireFunction(t),!this.#o)throw new Error("no wrapper component id set");this.#e.GetRuntime().AddWrapperExtensionMessageHandler(this.#o,e,t)}_addWrapperMessageHandlers(e){C3X.RequireArray(e);for(const[t,n]of e)this._addWrapperExtensionMessageHandler(t,n)}_sendWrapperExtensionMessage(e,t){if(!this.#o)throw new Error("no wrapper component id set");this.runtime.sdk.sendWrapperExtensionMessage(this.#o,e,t)}_sendWrapperExtensionMessageAsync(e,t){if(!this.#o)throw new Error("no wrapper component id set");return this.runtime.sdk.sendWrapperExtensionMessageAsync(this.#o,e,t)}};
}

// interfaces/objects/IWorldInstance.js
{
const C3=self.C3,C3X=self.C3X,IInstance=self.IInstance,ILayer=self.ILayer,tempRect=C3.New(C3.Rect),tempQuad=C3.New(C3.Quad),map=new WeakMap,internalApiToken=C3._GetInternalAPIToken(),BLEND_MODE_TO_INDEX=new Map([["normal",0],["additive",1],["copy",3],["destination-over",4],["source-in",5],["destination-in",6],["source-out",7],["destination-out",8],["source-atop",9],["destination-atop",10]]),INDEX_TO_BLEND_MODE=new Map([...BLEND_MODE_TO_INDEX.entries()].map((e=>[e[1],e[0]]))),tempColor=C3.New(C3.Color);function MakeIWorldInstanceClass(e){return class t extends e{#e;#t;constructor(e){super(e);const t=C3.AddonManager._GetInitObject2(internalApiToken),i=t.GetWorldInfo();this.#e=t,this.#t=i,map.set(this,t);const n=[],r=i.GetInstanceEffectList();if(r){const e=i.GetObjectClass().GetEffectList().GetAllEffectTypes().length;for(let t=0;t<e;++t)n.push(new self.IEffectInstance(r,t))}const s={effects:{value:n,writable:!1}};Object.defineProperties(this,s)}get layout(){return this.#t.GetLayout().GetILayout()}get layer(){return this.#t.GetLayer().GetILayer()}get x(){return this.#t.GetX()}set x(e){e=+e;const t=this.#t;isNaN(e)||t.GetX()===e||(t.SetX(e),t.SetBboxChanged())}get y(){return this.#t.GetY()}set y(e){e=+e;const t=this.#t;isNaN(e)||t.GetY()===e||(t.SetY(e),t.SetBboxChanged())}setPosition(e,t){e=+e,t=+t;const i=this.#t;isNaN(e)||isNaN(t)||i.GetX()===e&&i.GetY()===t||(i.SetXY(e,t),i.SetBboxChanged())}getPosition(){const e=this.#t;return[e.GetX(),e.GetY()]}offsetPosition(e,t){if(e=+e,t=+t,isNaN(e)||isNaN(t)||0===e&&0===t)return;const i=this.#t;i.OffsetXY(e,t),i.SetBboxChanged()}set originX(e){e=+e;const t=this.#t;isNaN(e)||t.GetOriginX()===e||(t.SetOriginX(e),t.SetBboxChanged())}get originX(){return this.#t.GetOriginX()}set originY(e){e=+e;const t=this.#t;isNaN(e)||t.GetOriginY()===e||(t.SetOriginY(e),t.SetBboxChanged())}get originY(){return this.#t.GetOriginY()}setOrigin(e,t){e=+e,t=+t;const i=this.#t;isNaN(e)||isNaN(t)||i.GetOriginX()===e&&i.GetOriginY()===t||(i.SetOriginX(e),i.SetOriginY(t),i.SetBboxChanged())}getOrigin(){const e=this.#t;return[e.GetOriginX(),e.GetOriginY()]}get zElevation(){return this.#t.GetZElevation()}set zElevation(e){e=+e;const t=this.#e,i=this.#t;isNaN(e)||i.GetZElevation()===e||(i.SetZElevation(e),t.GetRuntime().UpdateRender())}get totalZElevation(){return this.#t.GetTotalZElevation()}get width(){return this.#t.GetWidth()}set width(e){e=+e;const t=this.#t;isNaN(e)||t.GetWidth()===e||(t.SetWidth(e),t.SetBboxChanged())}get height(){return this.#t.GetHeight()}set height(e){e=+e;const t=this.#t;isNaN(e)||t.GetHeight()===e||(t.SetHeight(e),t.SetBboxChanged())}setSize(e,t){e=+e,t=+t;const i=this.#t;isNaN(e)||isNaN(t)||i.GetWidth()===e&&i.GetHeight()===t||(i.SetSize(e,t),i.SetBboxChanged())}getSize(){const e=this.#t;return[e.GetWidth(),e.GetHeight()]}get angle(){return this.#t.GetAngle()}set angle(e){e=C3.clampAngle(+e);const t=this.#t;isNaN(e)||t.GetAngle()===e||(t.SetAngle(e),t.SetBboxChanged())}get angleDegrees(){return C3.toDegrees(this.angle)}set angleDegrees(e){this.angle=C3.toRadians(e)}getBoundingBox(e){return e?(this.#t.CalculateBbox(tempRect,tempQuad,!1),tempRect.toDOMRect()):this.#t.GetBoundingBox().toDOMRect()}getBoundingQuad(e){return e?(this.#t.CalculateBbox(tempRect,tempQuad,!1),tempQuad.toDOMQuad()):this.#t.GetBoundingQuad().toDOMQuad()}isOnScreen(){return this.#t.IsInViewport2()}get isVisible(){return this.#t.IsVisible()}set isVisible(e){e=!!e;const t=this.#e,i=this.#t;i.IsVisible()!==e&&(i.SetVisible(e),t.GetRuntime().UpdateRender())}get opacity(){return this.#t.GetOpacity()}set opacity(e){e=C3.clamp(+e,0,1);const t=this.#e,i=this.#t;isNaN(e)||i.GetOpacity()===e||(i.SetOpacity(e),t.GetRuntime().UpdateRender())}set colorRgb(e){if(C3X.RequireArray(e),e.length<3)throw new Error("expected 3 elements");tempColor.setRgb(e[0],e[1],e[2]);const t=this.#e,i=this.#t;i.GetUnpremultipliedColor().equalsIgnoringAlpha(tempColor)||(i.SetUnpremultipliedColor(tempColor),t.GetRuntime().UpdateRender())}get colorRgb(){const e=this.#t.GetUnpremultipliedColor();return[e.getR(),e.getG(),e.getB()]}set blendMode(e){C3X.RequireString(e);const t=BLEND_MODE_TO_INDEX.get(e);if("number"!=typeof t)throw new Error("invalid blend mode");const i=this.#e;this.#t.SetBlendMode(t),i.GetRuntime().UpdateRender()}get blendMode(){return INDEX_TO_BLEND_MODE.get(this.#t.GetBlendMode())}moveToTop(){this.#t.ZOrderMoveToTop()}moveToBottom(){this.#t.ZOrderMoveToBottom()}moveToLayer(e){C3X.RequireInstanceOf(e,ILayer);const t=this.#e,i=t.GetRuntime()._UnwrapScriptInterface(e);if(!i)throw new Error("invalid layer");t.GetWorldInfo().ZOrderMoveToLayer(i)}moveAdjacentToInstance(e,i){C3X.RequireInstanceOf(e,t),this.#t.ZOrderMoveAdjacentToInstance(map.get(e),i)}get zIndex(){return this.#t.GetZIndex()}get isCollisionEnabled(){return this.#t.IsCollisionEnabled()}set isCollisionEnabled(e){this.#t.SetCollisionEnabled(!!e)}containsPoint(e,t){return C3X.RequireNumber(e),C3X.RequireNumber(t),this.#t.ContainsPoint(+e,+t)}testOverlap(e){C3X.RequireInstanceOf(e,t);const i=this.#e,n=map.get(e);return i.GetRuntime().GetCollisionEngine().TestOverlap(i,n)}testOverlapSolid(){const e=this.#e,t=e.GetRuntime().GetCollisionEngine().TestOverlapSolid(e);return t?t.GetInterfaceClass():null}getParent(){const e=this.#e.GetParent();return e?e.GetInterfaceClass():null}getTopParent(){const e=this.#e.GetTopParent();return e?e.GetInterfaceClass():null}*parents(){for(const e of this.#e.parents())yield e.GetInterfaceClass()}getChildCount(){return this.#e.GetChildCount()}getChildAt(e){const t=this.#e.GetChildAt(e);return t?t.GetInterfaceClass():null}*children(){for(const e of this.#e.children())yield e.GetInterfaceClass()}*allChildren(){for(const e of this.#e.allChildren())yield e.GetInterfaceClass()}addChild(e,i){C3X.RequireInstanceOf(e,t),C3X.RequireOptionalObject(i),i||(i={});const n=this.#e,r=map.get(e);n.AddChild(r,i)}removeChild(e){C3X.RequireInstanceOf(e,t);const i=this.#e,n=map.get(e);i.RemoveChild(n)}removeFromParent(){const e=this.#e;if(!e.HasParent())return;e.GetParent().RemoveChild(e)}getHierarchyOpts(){const e=this.#t;return{transformX:e.GetTransformWithParentX(),transformY:e.GetTransformWithParentY(),transformWidth:e.GetTransformWithParentWidth(),transformHeight:e.GetTransformWithParentHeight(),transformAngle:e.GetTransformWithParentAngle(),transformZElevation:e.GetTransformWithParentZElevation(),transformOpacity:e.GetTransformWithParentOpacity(),transformVisibility:e.GetTransformWithParentVisibility(),destroyWithParent:e.GetDestroyWithParent()}}createMesh(e,t){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(t),this.#t.CreateMesh(e,t)}releaseMesh(){const e=this.#t;e.ReleaseMesh(),e.SetBboxChanged()}setMeshPoint(e,t,i){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(t),C3X.RequireObject(i);const n=this.#t;n.SetMeshPoint(e,t,i)&&n.SetBboxChanged()}getMeshPoint(e,t){let i=NaN,n=NaN,r=NaN,s=NaN,a=NaN;const o=this.#t;if(o.HasMesh()){const l=o.GetSourceMesh().GetMeshPointAt(e,t);null!==l&&(i=l.GetX(),n=l.GetY(),r=l.GetZElevation(),s=l.GetU(),a=l.GetV())}return{x:i,y:n,zElevation:r,u:s,v:a}}getMeshSize(){const e=this.#t;if(!e.HasMesh())return[0,0];const t=e.GetSourceMesh();return[t.GetHSize(),t.GetVSize()]}}}self.IWorldInstance=MakeIWorldInstanceClass(self.IInstance),self.IWorldInstanceSDKBase=MakeIWorldInstanceClass(self.ISDKInstanceBase);
}

// interfaces/objects/IDOMInstance.js
{
const C3=self.C3,C3X=self.C3X;self.IDOMInstance=class extends self.IWorldInstance{#e;constructor(){super(),this.#e=self.IInstance._GetInitInst()}getElement(){return this.#e.GetSdkInstance()._GetElementInDOMMode()}focus(){this.#e.GetSdkInstance().FocusElement()}blur(){this.#e.GetSdkInstance().BlurElement()}setCssStyle(e,t){C3X.RequireString(e),this.#e.GetSdkInstance().SetElementCSSStyle(e,t)}};
}

// interfaces/objects/IBehaviorInstance.js
{
const C3=self.C3,C3X=self.C3X,dispatchers=new WeakMap,internalApiToken=C3._GetInternalAPIToken();function GetDispatcher(e){let t=dispatchers.get(e);return t||(t=C3.New(C3.Event.Dispatcher),dispatchers.set(e,t),t)}self.IBehaviorInstance=class{#e;constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e;const t={runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},behavior:{value:e.GetBehavior().GetIBehavior(),writable:!1},behaviorType:{value:e.GetBehaviorType().GetIBehaviorType(),writable:!1}};Object.defineProperties(this,t),e.GetRuntime()._MapScriptInterface(this,e)}static _GetInitInst(){return C3.AddonManager._GetInitObject()}get instance(){return this.#e.GetObjectInstance().GetInterfaceClass()}_release(){const e=dispatchers.get(this);e&&(e.Release(),dispatchers.delete(this))}addEventListener(e,t,i){C3X.RequireString(e),C3X.RequireFunction(t),GetDispatcher(this).addEventListener(e,t,i)}removeEventListener(e,t,i){C3X.RequireString(e),C3X.RequireFunction(t),GetDispatcher(this).removeEventListener(e,t,i)}dispatchEvent(e){GetDispatcher(this).dispatchEvent(e)}};
}

// interfaces/objects/IBehaviorType.js
{
const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.IBehaviorType=class{constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken),t={runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},behavior:{value:e.GetBehavior().GetIBehavior(),writable:!1},name:{value:e.GetName(),writable:!1}};Object.defineProperties(this,t)}};
}

// interfaces/objects/IBehavior.js
{
const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.IBehavior=class{#t;constructor(){const t=C3.AddonManager._GetInitObject2(internalApiToken);this.#t=t;const e={runtime:{value:t.GetRuntime().GetIRuntime(),writable:!1},id:{value:t.GetID(),writable:!1}};Object.defineProperties(this,e),t.GetRuntime()._MapScriptInterface(this,t)}getAllInstances(){return this.#t.GetInstances().map((t=>t.GetInterfaceClass()))}static getByConstructor(t){if(!t)return null;const e=C3.AddonManager.GetBehaviorByConstructorFunction(t);return e?e.GetIBehavior():null}};
}

// interfaces/objects/IEffectInstance.js
{
const C3=self.C3,C3X=self.C3X,tempColor=C3.New(C3.Color);self.IEffectInstance=class{#e;constructor(e,t){this.#e=e;const i={index:{value:t,writable:!1}};Object.defineProperties(this,i)}get name(){return this.#e.GetAllEffectTypes()[this.index].GetName()}get isActive(){return this.#e.IsEffectIndexActive(this.index)}set isActive(e){e=!!e;const t=this.#e;t.IsEffectIndexActive(this.index)!==e&&(t.SetEffectIndexActive(this.index,e),t.UpdateActiveEffects(),t.GetRuntime().UpdateRender())}setParameter(e,t){C3X.RequireFiniteNumber(e),e=Math.floor(+e);const i=this.#e,r=i.GetEffectParameter(this.index,e);if(null===r)throw new RangeError("invalid index");if(r instanceof C3.Color){if(!Array.isArray(t)||t.length<3)throw new TypeError("expected array with 3 elements");tempColor.setRgb(t[0],t[1],t[2]),t=tempColor}else if("number"!=typeof t)throw new TypeError("expected number");i.SetEffectParameter(this.index,e,t)&&i.IsEffectIndexActive(this.index)&&i.GetRuntime().UpdateRender()}getParameter(e){C3X.RequireFiniteNumber(e),e=Math.floor(+e);const t=this.#e.GetEffectParameter(this.index,e);if(null===t)throw new RangeError("invalid index");return t instanceof C3.Color?[t.getR(),t.getG(),t.getB()]:t}};
}

// interfaces/objects/IAnimation.js
{
const C3=self.C3,C3X=self.C3X;self.IAnimation=class{#e;constructor(e){this.#e=e,Object.defineProperties(this,{name:{value:e.GetName(),writable:!1}})}get speed(){return this.#e.GetSpeed()}get isLooping(){return this.#e.IsLooping()}get repeatCount(){return this.#e.GetRepeatCount()}get repeatTo(){return this.#e.GetRepeatTo()}get isPingPong(){return this.#e.IsPingPong()}get frameCount(){return this.#e.GetFrameCount()}getFrames(){return this.#e.GetFrames().map((e=>e.GetIAnimationFrame()))}*frames(){for(const e of this.#e.GetFrames())yield e.GetIAnimationFrame()}};
}

// interfaces/objects/IImageInfo.js
{
const C3=self.C3,C3X=self.C3X;self.IImageInfo=class{#t;constructor(t){this.#t=t}static _Unwrap(t){return t.#t}get width(){return this.#t.GetWidth()}get height(){return this.#t.GetHeight()}getSize(){const t=this.#t;return[t.GetWidth(),t.GetHeight()]}getTexture(t){return t.getTextureForImageInfo(this)}getTexRect(){return this.#t.GetTexRect().toDOMRect()}};
}

// interfaces/objects/IAnimationFrame.js
{
const C3=self.C3,C3X=self.C3X;self.IAnimationFrame=class extends self.IImageInfo{#t;constructor(t){super(t.GetImageInfo()),this.#t=t,Object.defineProperties(this,{duration:{value:t.GetDuration(),writable:!1},originX:{value:t.GetOriginX(),writable:!1},originY:{value:t.GetOriginY(),writable:!1}})}getOrigin(){const t=this.#t;return[t.GetOriginX(),t.GetOriginY()]}getImagePointCount(){return this.#t.GetImagePointCount()}getImagePointX(t){return this.getImagePoint(t)[0]}getImagePointY(t){return this.getImagePoint(t)[1]}getImagePoint(t){const e=this.#t;let i=null;if("number"==typeof t)i=e.GetImagePointByIndex(Math.floor(t));else{if("string"!=typeof t)throw new TypeError("expected string or number");i=e.GetImagePointByName(t)}return i?[i.GetX(),i.GetY()]:this.getOrigin()}getPolyPointCount(){const t=this.#t.GetCollisionPoly();return t?t.pointCount():0}getPolyPointX(t){return this.getPolyPoint(t)[0]}getPolyPointY(t){return this.getPolyPoint(t)[1]}getPolyPoint(t){C3X.RequireFiniteNumber(t),t=Math.floor(t);const e=this.#t.GetCollisionPoly();if(!e||t<0||t>=e.pointCount())return[0,0];const i=e.pointsArr();return[i[2*t],i[2*t+1]]}get tag(){return this.#t.GetTag()}};
}

// interfaces/other/ITimelineStateBase.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap;function GetTimelineState(e){const t=map.get(e);if(t.IsReleased())throw new Error("timeline/tween was released and is no longer valid");return t}self.ITimelineStateBase=class{constructor(e){map.set(this,e),e.GetRuntime()._MapScriptInterface(this,e)}pause(){GetTimelineState(this).Stop()}resume(){GetTimelineState(this).Resume()}stop(){GetTimelineState(this).Reset()}hasTags(e){return GetTimelineState(this).HasTags(e)}set time(e){C3X.RequireFiniteNumber(e),GetTimelineState(this).SetTime(e)}get time(){return GetTimelineState(this).GetTime()}set totalTime(e){C3X.RequireFiniteNumber(e),GetTimelineState(this).SetTotalTime(e)}get totalTime(){return GetTimelineState(this).GetTotalTime()}set isLooping(e){GetTimelineState(this).SetLoop(!!e)}get isLooping(){return GetTimelineState(this).GetLoop()}set isPingPong(e){GetTimelineState(this).SetPingPong(!!e)}get isPingPong(){return GetTimelineState(this).GetPingPong()}set playbackRate(e){C3X.RequireFiniteNumber(e),GetTimelineState(this).SetPlaybackRate(e)}get playbackRate(){return GetTimelineState(this).GetPlaybackRate()}get progress(){const e=GetTimelineState(this);return e.GetTime()/e.GetTotalTime()}get tags(){return GetTimelineState(this).GetTags()}get finished(){return GetTimelineState(this).GetPlayPromise()}get isPlaying(){return GetTimelineState(this).IsPlaying()}get isPaused(){return GetTimelineState(this).IsPaused()}get isReleased(){return map.get(this).IsReleased()}};
}

// interfaces/other/ITimelineState.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap;let easeToIndexFunc=null;function GetTimelineState(e){const t=map.get(e);if(t.IsReleased())throw new Error("timeline was released and is no longer valid");return t}self.ITimelineState=class extends self.ITimelineStateBase{constructor(e){super(e),map.set(this,e);const t={name:{value:e.GetName(),writable:!1}};Object.defineProperties(this,t)}};
}

// interfaces/other/ITweenState.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap,behInstMap=new WeakMap;let easeToIndexFunc=null;function GetTweenState(e){const t=map.get(e);if(t.IsReleased())throw new Error("tween was released and is no longer valid");return t}self.ITweenState=class extends self.ITimelineStateBase{constructor(e,t,n){super(e),easeToIndexFunc||(easeToIndexFunc=n.easeToIndexFunc),map.set(this,e),t&&behInstMap.set(this,t)}stop(){const e=GetTweenState(this);behInstMap.get(this).ReleaseTween(e)}setEase(e){C3X.RequireString(e);const t=self.Ease.GetEaseFromIndex(easeToIndexFunc(e));GetTweenState(this).SetEase(t)}get instance(){const e=GetTweenState(this).GetInstance();return e?e.GetInterfaceClass():null}get isDestroyOnComplete(){return GetTweenState(this).GetDestroyInstanceOnComplete()}set isDestroyOnComplete(e){GetTweenState(this).SetDestroyInstanceOnComplete(!!e)}get value(){const e=GetTweenState(this);if("value"!==e.GetId())throw new Error("not a value tween");return e.GetPropertyTrack("value").GetSourceAdapterValue()}};
}

// interfaces/sdk/ISDKPluginBase.js
{
const C3=self.C3,C3X=self.C3X;self.ISDKPluginBase=class extends self.IPlugin{constructor(){super()}};
}

// interfaces/sdk/ISDKDOMPluginBase.js
{
const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.ISDKDOMPluginBase=class extends self.ISDKPluginBase{#e;#n;#t=0;#s=new Map;constructor(e){if(super(),this.#e=C3.AddonManager._GetInitObject2(internalApiToken),!e?.domComponentId)throw new Error("no DOM component ID specified");this.#n=e.domComponentId,this._addElementMessageHandler("elem-focused",(e=>e._onElemFocused())),this._addElementMessageHandler("elem-blurred",(e=>{e&&e._onElemBlurred()}))}_addElement(e){const n=this.#t++;return this.#s.set(n,e),n}_removeElement(e){this.#s.delete(e)}_addElementMessageHandler(e,n){this.#e.GetRuntime().AddDOMComponentMessageHandler(this.#n,e,(e=>{const t=this.#s.get(e["elementId"]);n(t,e)}))}_addElementMessageHandlers(e){C3X.RequireArray(e);for(const[n,t]of e)this._addElementMessageHandlers(n,t)}};
}

// interfaces/sdk/ISDKObjectTypeBase.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap,internalApiToken=C3._GetInternalAPIToken();self.ISDKObjectTypeBase=class extends self.IObjectType{#e;constructor(){super(),this.#e=C3.AddonManager._GetInitObject2(internalApiToken)}_onCreate(){}getImageInfo(){return this.#e.GetImageInfo().GetIImageInfo()}_loadTextures(e){}_releaseTextures(e){}_onDynamicTextureLoadComplete(){}_preloadTexturesWithInstances(e){}};
}

// interfaces/sdk/ISDKWorldInstanceBase.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap,internalApiToken=C3._GetInternalAPIToken();self.ISDKWorldInstanceBase=class extends self.IWorldInstanceSDKBase{#e;#r=null;#t=null;constructor(e){super(e),this.#e=C3.AddonManager._GetInitObject2(internalApiToken)}_release(){if(super._release(),this.#r){const e=this.#e.GetRuntime().Dispatcher();e.removeEventListener("renderercontextlost",this.#r),e.removeEventListener("renderercontextrestored",this.#t),this.#r=null,this.#t=null}}_handleRendererContextLoss(){if(this.#r)return;this.#r=()=>this._onRendererContextLost(),this.#t=()=>this._onRendererContextRestored();const e=this.#e.GetRuntime().Dispatcher();e.addEventListener("renderercontextlost",this.#r),e.addEventListener("renderercontextrestored",this.#t)}_onRendererContextLost(){}_onRendererContextRestored(){}_draw(e){}};
}

// interfaces/sdk/ISDKDOMInstanceBase.js
{
const C3=self.C3,C3X=self.C3X,tempRect=C3.New(C3.Rect),map=new WeakMap,internalApiToken=C3._GetInternalAPIToken();self.ISDKDOMInstanceBase=class extends self.ISDKWorldInstanceBase{#e=-1;#t=!0;#s=!1;#i=!1;#n=-.2;#o=C3.New(C3.Rect,0,0,-1,-1);#l=0;#a=0;#h=-1;#d=-1;#m=!1;constructor(e){if(!e?.domComponentId)throw new Error("no DOM component ID specified");super(e);const t=C3.AddonManager._GetInitObject2(internalApiToken);map.set(this,t),this.#e=this.plugin._addElement(this);const s=t.GetRuntime().GetCanvasManager();this.#l=s.GetLastWidth(),this.#a=s.GetLastHeight(),this._setTicking(!0)}_release(){super._release(),this.plugin._removeElement(this.#e),this._postToDOMElement("destroy"),this.#e=-1,map.delete(this)}_getElementInDOMMode(){if(map.get(this).GetRuntime().IsInWorker())throw new Error("not valid in worker mode");return this._postToDOMElementMaybeSync("get-element")}_postToDOMElement(e,t){t||(t={}),t["elementId"]=this.#e,this._postToDOM(e,t)}_postToDOMElementMaybeSync(e,t){return t||(t={}),t["elementId"]=this.#e,this._postToDOMMaybeSync(e,t)}_postToDOMElementAsync(e,t){return t||(t={}),t["elementId"]=this.#e,this._postToDOMAsync(e,t)}_createElement(e){e||(e={});const t=map.get(this).GetWorldInfo();e["elementId"]=this.#e,e["isVisible"]=t.IsVisible(),e["htmlIndex"]=t.GetLayer().GetHTMLIndex(),e["htmlZIndex"]=t.GetHTMLZIndex(),Object.assign(e,this._getElementState()),this.#t=!!e["isVisible"],this._postToDOMMaybeSync("create",e),this._updatePosition(!0)}setElementVisible(e){e=!!e,this.#t!==e&&(this.#t=e,this._postToDOMElement("set-visible",{"isVisible":e}))}_tick(){this._updatePosition(!1)}_shouldPreserveElement(){const e=map.get(this).GetRuntime().GetCanvasManager().GetFullscreenMode();return"Android"===C3.Platform.OS&&("scale-inner"===e||"scale-outer"===e||"crop"===e)}_updatePosition(e){const t=map.get(this);if(t.IsDestroyed())return;const s=t.GetWorldInfo(),i=s.GetLayer(),n=s.GetBoundingBox();let[o,l]=i.LayerToCanvasCss(n.getLeft(),n.getTop()),[a,h]=i.LayerToCanvasCss(n.getRight(),n.getBottom());const d=t.GetRuntime().GetCanvasManager(),m=d.GetCssWidth(),r=d.GetCssHeight();if(!s.IsVisible()||!i.IsVisible())return void this.setElementVisible(!1);if(!this._shouldPreserveElement()&&(a<=0||h<=0||o>=m||l>=r))return void this.setElementVisible(!1);tempRect.set(o,l,a,h);const c=d.GetLastWidth(),p=d.GetLastHeight(),u=i.GetHTMLIndex(),M=s.GetHTMLZIndex();if(!e&&tempRect.equals(this.#o)&&this.#l===c&&this.#a===p&&this.#h===u&&this.#d===M)return void this.setElementVisible(!0);this.#o.copy(tempRect),this.#l=c,this.#a=p,this.#h=u,this.#d=M,this.setElementVisible(!0);let I=null;this.#i&&(I=i.GetDisplayScale()+this.#n),this._postToDOMElement("update-position",{"left":Math.round(this.#o.getLeft()),"top":Math.round(this.#o.getTop()),"width":Math.round(this.#o.width()),"height":Math.round(this.#o.height()),"htmlIndex":u,"htmlZIndex":M,"fontSize":I})}focusElement(){this._postToDOMElementMaybeSync("focus",{"focus":!0})}blurElement(){this._postToDOMElementMaybeSync("focus",{"focus":!1})}_onElemFocused(){this.#s=!0}_onElemBlurred(){this.#s=!1}isElementFocused(){return this.#s}setElementCSSStyle(e,t){this.postToDOMElement("set-css-style",{"prop":C3.CSSToCamelCase(e),"val":t})}setElementAttribute(e,t){this.postToDOMElement("set-attribute",{"name":e,"val":t})}removeElementAttribute(e){this.postToDOMElement("remove-attribute",{"name":e})}_updateElementState(){this.#m||(this.#m=!0,Promise.resolve().then((()=>{this.#m=!1,this._postToDOMElement("update-state",this._getElementState())})))}_getElementState(){}_getElementId(){return this.#e}};
}

// interfaces/sdk/ISDKBehaviorBase.js
{
const C3=self.C3,C3X=self.C3X;self.ISDKBehaviorBase=class extends self.IBehavior{constructor(){super()}};
}

// interfaces/sdk/ISDKBehaviorTypeBase.js
{
const C3=self.C3,C3X=self.C3X;self.ISDKBehaviorTypeBase=class extends globalThis.IBehaviorType{constructor(){super()}_onCreate(){}};
}

// interfaces/sdk/ISDKBehaviorInstanceBase.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap,internalApiToken=C3._GetInternalAPIToken();self.ISDKBehaviorInstanceBase=class extends self.IBehaviorInstance{#i=!1;#t=!1;#e=!1;constructor(){super(),map.set(this,C3.AddonManager._GetInitObject2(internalApiToken))}_release(){super._release(),this._setTicking(!1),this._setTicking2(!1),this._setPostTicking(!1),map.delete(this)}_getInitProperties(){return C3.AddonManager._GetInitProperties()}_postCreate(){}_trigger(i){const t=map.get(this);t.GetRuntime().Trigger(i,t.GetObjectInstance(),t.GetBehaviorType())}_triggerAsync(i){const t=map.get(this);return t.GetRuntime().TriggerAsync(i,t.GetObjectInstance(),t.GetBehaviorType())}_setTicking(i){if(i=!!i,this.#i===i)return;this.#i=i;const t=map.get(this).GetRuntime();i?t._AddBehInstToTick(this):t._RemoveBehInstToTick(this)}_isTicking(){return this.#i}_tick(){}_setTicking2(i){if(i=!!i,this.#t===i)return;this.#t=i;const t=map.get(this).GetRuntime();i?t._AddBehInstToTick2(this):t._RemoveBehInstToTick2(this)}_isTicking2(){return this.#t}_tick2(){}_setPostTicking(i){if(i=!!i,this.#e===i)return;this.#e=i;const t=map.get(this).GetRuntime();i?t._AddBehInstToPostTick(this):t._RemoveBehInstToPostTick(this)}_isPostTicking(){return this.#e}_postTick(){}_getDebuggerProperties(){return[]}_saveToJson(){return null}_loadFromJson(i){}};
}

// interfaces/sdk/ISDKUtils.js
{
const C3=self.C3,C3X=self.C3X;let runtime=null;self.ISDKUtils=class{constructor(e){runtime=e}addLoadPromise(e){runtime.AddLoadPromise(e)}sendWrapperExtensionMessage(e,n,t){C3X.RequireString(e),C3X.RequireString(n),C3X.RequireOptionalArray(t),runtime.SendWrapperExtensionMessage(e,n,t)}sendWrapperExtensionMessageAsync(e,n,t){return C3X.RequireString(e),C3X.RequireString(n),C3X.RequireOptionalArray(t),runtime.SendWrapperExtensionMessageAsync(e,n,t)}createLoopingConditionContext(e){return C3X.RequireOptionalString(e),new self.ILoopingConditionContext(runtime,e)}set isAutoSuspendEnabled(e){runtime._SetAutoSuspendEnabled(!!e)}get isAutoSuspendEnabled(){return runtime._IsAutoSuspendEnabled()}setSuspended(e){runtime.SetSuspended(!!e)}getObjectClassBySid(e){C3X.RequireNumber(e);const n=runtime.GetObjectClassBySID(e);return n?n.GetIObjectClass():null}};
}

// interfaces/sdk/ILoopingConditionContext.js
{
const C3=self.C3,C3X=self.C3X;self.ILoopingConditionContext=class{#e;#t;#o;#n;#s;#r;constructor(e,t){this.#e=e;const o=e.GetEventSheetManager(),n=e.GetCurrentEvent();this.#t=n,this.#o=n.GetSolModifiers();const s=e.GetEventStack();this.#n=s.GetCurrentStackFrame(),this.#s=s.Push(n);const r=o.GetLoopStack().Push();this.#r=r,t&&r.SetName(t),e.SetDebuggingEnabled(!1)}retrigger(){const e=this.#e.GetEventSheetManager(),t=this.#o,o=this.#r;e.PushCopySol(t),this.#t.Retrigger(this.#n,this.#s),e.PopSol(t),o.SetIndex(o.GetIndex()+1)}get isStopped(){return this.#r.IsStopped()}release(){const e=this.#e,t=e.GetEventStack(),o=e.GetEventSheetManager().GetLoopStack();e.SetDebuggingEnabled(!0),o.Pop(),t.Pop()}};
}

// interfaces/gfx/IRenderer.js
{
const C3=self.C3,C3X=self.C3X;let renderer=null,runtime=null;self.IRenderer=class{constructor(e,r){runtime=e,renderer=r}setAlphaBlendMode(){renderer.SetAlphaBlend()}setBlendMode(e){renderer.SetNamedBlendMode(e)}setColorFillMode(){renderer.SetColorFillMode()}setTextureFillMode(){renderer.SetTextureFillMode()}setSmoothLineFillMode(){renderer.SetSmoothLineFillMode()}setColor(e){renderer.SetColorRgba(e[0],e[1],e[2],e[3])}setColorRgba(e,r,n,t){renderer.SetColorRgba(e,r,n,t)}resetColor(){renderer.ResetColor()}setOpacity(e){renderer.SetOpacity(e)}setCurrentZ(e){renderer.SetCurrentZ(e)}getCurrentZ(){renderer.GetCurrentZ()}rect(e){renderer.Rect2(e.left,e.top,e.right,e.bottom)}rect2(e,r,n,t){renderer.Rect2(e,r,n,t)}quad(e){renderer.Quad(C3.Quad.fromDOMQuad(e))}quad2(e,r,n,t,a,d,o,i){renderer.Quad2(e,r,n,t,a,d,o,i)}quad3(e,r){renderer.Quad3(C3.Quad.fromDOMQuad(e),C3.Rect.fromDOMRect(r))}quad4(e,r){renderer.Quad4(C3.Quad.fromDOMQuad(e),C3.Quad.fromDOMQuad(r))}quad3D(e,r,n,t,a,d,o,i,u,l,p,s,c){renderer.Quad3D(e,r,n,t,a,d,o,i,u,l,p,s,C3.Rect.fromDOMRect(c))}quad3D2(e,r,n,t,a,d,o,i,u,l,p,s,c){renderer.Quad3D2(e,r,n,t,a,d,o,i,u,l,p,s,C3.Quad.fromDOMQuad(c))}drawMesh(e,r,n){renderer.DrawMesh(e,r,n)}convexPoly(e){renderer.ConvexPoly(e)}line(e,r,n,t){renderer.Line(e,r,n,t)}texturedLine(e,r,n,t,a,d){renderer.TexturedLine(e,r,n,t,a,d)}lineRect(e,r,n,t){renderer.LineRect(e,r,n,t)}lineRect2(e){renderer.LineRect2(C3.Rect.fromDOMRect(e))}lineQuad(e){renderer.LineQuad(C3.Quad.fromDOMQuad(e))}pushLineWidth(e){renderer.PushLineWidth(e)}popLineWidth(){renderer.PopLineWidth()}pushLineCap(e){renderer.PushLineCap(e)}popLineCap(){renderer.PopLineCap()}setTexture(e){C3X.RequireOptionalInstanceOf(e,self.ITexture);const r=e?runtime._UnwrapScriptInterface(e):null;renderer.SetTexture(r)}loadTextureForImageInfo(e,r){const n=self.IImageInfo._Unwrap(e);if(!n)throw new Error("invalid IImageInfo");return n.LoadStaticTexture(renderer,{wrapX:r?.wrapX??"clamp-to-edge",wrapY:r?.wrapY??"clamp-to-edge",sampling:r?.sampling??"trilinear",mipMap:r?.mipMap??!0})}releaseTextureForImageInfo(e){const r=self.IImageInfo._Unwrap(e);if(!r)throw new Error("invalid IImageInfo");r.ReleaseTexture()}getTextureForImageInfo(e){const r=self.IImageInfo._Unwrap(e);if(!r)throw new Error("invalid IImageInfo");const n=r.GetTexture();return self.ITexture.GetInterface(runtime,n)}createDynamicTexture(e,r,n){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(r);const t=renderer.CreateDynamicTexture(e,r,{wrapX:n?.wrapX??"clamp-to-edge",wrapY:n?.wrapY??"clamp-to-edge",sampling:n?.sampling??"trilinear",mipMap:n?.mipMap??!0});return self.ITexture.GetInterface(runtime,t)}updateTexture(e,r,n){C3X.RequireInstanceOf(r,self.ITexture);const t=runtime._UnwrapScriptInterface(r);renderer.UpdateTexture(e,t,{premultiplyAlpha:n?.premultiplyAlpha??!0})}deleteTexture(e){C3X.RequireInstanceOf(e,self.ITexture);const r=runtime._UnwrapScriptInterface(e);renderer.DeleteTexture(r)}createRendererText(){const e=renderer.CreateRendererText();return new self.IRendererText(runtime,e)}setDeviceTransform(){runtime.GetCanvasManager().SetDeviceTransform(renderer)}setLayerTransform(e){C3X.RequireInstanceOf(e,globalThis.ILayer);runtime._UnwrapScriptInterface(e)._SetTransform(renderer)}};
}

// interfaces/gfx/ITexture.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap,reverseMap=new WeakMap;self.ITexture=class{constructor(e,t){map.set(this,{runtime:e,texture:t}),reverseMap.set(t,this),e._MapScriptInterface(this,t),Object.defineProperties(this,{width:{value:t.GetWidth(),writable:!1},height:{value:t.GetHeight(),writable:!1}})}static GetInterface(e,t){if(!t)return null;const r=reverseMap.get(t);return r||new self.ITexture(e,t)}};
}

// interfaces/gfx/IRendererText.js
{
const C3=self.C3,C3X=self.C3X,map=new WeakMap;function getActual(t){return map.get(t).rendererText}self.IRendererText=class{constructor(t,e){map.set(this,{runtime:t,rendererText:e}),t._MapScriptInterface(this,e)}release(){getActual(this).Release()}set fontFace(t){C3X.RequireString(t),getActual(this).SetFontName(t)}get fontFace(){return getActual(this).GetFontName()}set sizePt(t){C3X.RequireFiniteNumber(t),getActual(this).SetFontSize(t)}get sizePt(){return getActual(this).GetFontSize()}set lineHeight(t){C3X.RequireFiniteNumber(t),getActual(this).SetLineHeight(t)}get lineHeight(){return getActual(this).GetLineHeight()}set isBold(t){getActual(this).SetBold(t)}get isBold(){return getActual(this).IsBold()}set isItalic(t){getActual(this).SetItalic(t)}get isItalic(){return getActual(this).IsItalic()}setColor(t){C3X.RequireArray(t),this.setColorRgb(t[0],t[1],t[2])}setColorRgb(t,e,i){getActual(this).SetColorRgb(t,e,i)}setCssColor(t){C3X.RequireString(t),getActual(this).SetColor(t)}set horizontalAlign(t){getActual(this).SetHorizontalAlignment(t)}get horizontalAlign(){return getActual(this).GetHorizontalAlignment()}set verticalAlign(t){getActual(this).SetVerticalAlignment(t)}get verticalAlign(){return getActual(this).GetVerticalAlignment()}set wordWrapMode(t){getActual(this).SetWordWrapMode(t)}get wordWrapMode(){return getActual(this).GetWordWrapMode()}set textDirection(t){getActual(this).SetTextDirection(t)}get textDirection(){return getActual(this).GetTextDirection()}set text(t){C3X.RequireString(t),getActual(this).SetText(t)}get text(){return getActual(this).GetText()}setSize(t,e,i){C3X.RequireFiniteNumber(t),C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(i),getActual(this).SetSize(t,e,i)}getTexture(){const{runtime:t,rendererText:e}=map.get(this),i=e.GetTexture();return self.ITexture.GetInterface(t,i)}getTexRect(){return getActual(this).GetTexRect().toDOMRect()}setTextureUpdateCallback(t){C3X.RequireFunction(t),getActual(this).ontextureupdate=t}releaseTexture(){getActual(this).ReleaseTexture()}get textWidth(){return getActual(this).GetTextWidth()}get textHeight(){return getActual(this).GetTextHeight()}};
}

// assets/assetManager.js
{
const C3=self.C3,VALID_LOAD_POLICIES=new Set(["local","remote"]),EXT_TO_TYPE=new Map([["mp4","video/mp4"],["webm","video/webm"],["m4a","audio/mp4"],["mp3","audio/mpeg"],["js","application/javascript"],["wasm","application/wasm"],["svg","image/svg+xml"],["html","text/html"]]);function GetTypeFromFileExtension(e){if(!e)return"";const t=e.split(".");if(t.length<2)return"";const i=t.at(-1).toLowerCase();return EXT_TO_TYPE.get(i)||""}function AddScript(e){return new Promise(((t,i)=>{const s=document.createElement("script");s.onload=t,s.onerror=i,s.async=!1,s.type="module",s.src=e,document.head.appendChild(s)}))}C3.AssetManager=class extends C3.DefendedBase{constructor(e,t){super();const i=t["exportType"];this._runtime=e,this._fileStructure="folders",this._cordovaBlobUrlCache=new Map,this._isCordova="cordova"===i,this._isiOSCordova=!!t["isiOSCordova"],this._isFileProtocol=!!t["isFileProtocol"],this._swClientId=t["swClientId"],this._supportedAudioFormats=t["supportedAudioFormats"]||{},this._audioFiles=new Map,this._preloadSounds=!1,this._scriptSubfolder=t["scriptFolder"],this._mediaSubfolder="",this._fontsSubfolder="",this._iconsSubfolder="",this._fileMap=t["fileMap"]||new Map,this._fileMapBlobUrls=new Map;const s="html5"===i||"scirra-arcade"===i||"instant-games"===i;this._defaultLoadPolicy=s?"remote":"local",this._imageAssetsMap=new Map,this._webFonts=[],this._loadPromises=[],this._hasFinishedInitialLoad=!1,this._totalAssetSizeToLoad=0,this._assetSizeLoaded=0,this._lastLoadProgress=0,this._hasHadErrorLoading=!1,this._loadingRateLimiter=C3.New(C3.RateLimiter,(()=>this._FireLoadingProgressEvent()),50),this._localPromiseThrottle=C3.New(C3.PromiseThrottle,Math.max(C3.hardwareConcurrency,8)),this._remotePromiseThrottle=C3.New(C3.PromiseThrottle,20),this._iAssetManager=new self.IAssetManager(this)}Release(){for(const e of this._imageAssetsMap.values())e.Release();this._imageAssetsMap.clear(),C3.clearArray(this._loadPromises),this._runtime=null}GetRuntime(){return this._runtime}_SetFileStructure(e){this._fileStructure=e}GetFileStructure(){return this._fileStructure}GetScriptSubfolder(){return this._scriptSubfolder}_SetMediaSubfolder(e){this._mediaSubfolder=e}GetMediaSubfolder(){return this._mediaSubfolder}_SetFontsSubfolder(e){this._fontsSubfolder=e}GetFontsSubfolder(){return this._fontsSubfolder}_SetIconsSubfolder(e){this._iconsSubfolder=e}GetIconsSubfolder(){return this._iconsSubfolder}IsFileProtocol(){return this._isFileProtocol}FetchBlob(e,t){return t=t||this._defaultLoadPolicy,C3.IsRelativeURL(e)?("flat"===this._fileStructure&&(e=e.toLowerCase()),this._isCordova&&this._isFileProtocol?this.CordovaFetchLocalFileAsBlob(e):"playable-ad-single-file"===this._runtime.GetExportType()?self["c3_runtimeInterface"]["_PlayableAdFetchBlob"](e):"local"===t?this._localPromiseThrottle.Add((()=>C3.FetchBlob(e))):this._remotePromiseThrottle.Add((()=>C3.FetchBlob(e)))):C3.FetchBlob(e)}FetchArrayBuffer(e){return C3.IsRelativeURL(e)?("flat"===this._fileStructure&&(e=e.toLowerCase()),this._isCordova&&this._isFileProtocol?this.CordovaFetchLocalFileAsArrayBuffer(e):"playable-ad-single-file"===this._runtime.GetExportType()?C3.BlobToArrayBuffer(self["c3_runtimeInterface"]["_PlayableAdFetchBlob"](e)):"local"===this._defaultLoadPolicy?this._localPromiseThrottle.Add((()=>C3.FetchArrayBuffer(e))):this._remotePromiseThrottle.Add((()=>C3.FetchArrayBuffer(e)))):C3.FetchArrayBuffer(e)}FetchText(e){return C3.IsRelativeURL(e)?("flat"===this._fileStructure&&(e=e.toLowerCase()),this._isCordova&&this._isFileProtocol?this.CordovaFetchLocalFileAsText(e):"playable-ad-single-file"===this._runtime.GetExportType()?C3.BlobToString(self["c3_runtimeInterface"]["_PlayableAdFetchBlob"](e)):"local"===this._defaultLoadPolicy?this._localPromiseThrottle.Add((()=>C3.FetchText(e))):this._remotePromiseThrottle.Add((()=>C3.FetchText(e)))):C3.FetchText(e)}async FetchJson(e){const t=await this.FetchText(e);return JSON.parse(t)}_CordovaFetchLocalFileAs(e,t){return"flat"===this._fileStructure&&(e=e.toLowerCase()),this._runtime.PostComponentMessageToDOMAsync("runtime","cordova-fetch-local-file",{"filename":e,"as":t})}CordovaFetchLocalFileAsText(e){return this._CordovaFetchLocalFileAs(e,"text")}async CordovaFetchLocalFileAsBlob(e){const t=await this._CordovaFetchLocalFileAs(e,"buffer"),i=GetTypeFromFileExtension(e);return new Blob([t],{"type":i})}async CordovaFetchLocalFileAsBlobURL(e){"flat"===this._fileStructure&&(e=e.toLowerCase());let t=this._cordovaBlobUrlCache.get(e);if(t)return t;const i=await this.CordovaFetchLocalFileAsBlob(e);return t=URL.createObjectURL(i),this._cordovaBlobUrlCache.set(e,t),t}CordovaFetchLocalFileAsArrayBuffer(e){return this._CordovaFetchLocalFileAs(e,"buffer")}GetMediaFileUrl(e){"flat"===this._fileStructure&&(e=e.toLowerCase());let t=this._mediaSubfolder+e;return"Gecko"===C3.Platform.BrowserEngine&&"preview"===this._runtime.GetExportType()&&(t=this._GetLocalBlobURLFromFileMap(t)),t}GetProjectFileUrl(e){return C3.IsAbsoluteURL(e)?Promise.resolve(e):this._isCordova&&this._isFileProtocol?this.CordovaFetchLocalFileAsBlobURL(e):"playable-ad-single-file"===this._runtime.GetExportType()?URL.createObjectURL(self["c3_runtimeInterface"]["_PlayableAdFetchBlob"](e)):("flat"===this._fileStructure&&(e=e.toLowerCase()),Promise.resolve(e))}GetProjectFileIframeUrl(e){if(C3.IsAbsoluteURL(e)||"preview"!==this._runtime.GetExportType()||!this._swClientId||!e)return e;try{const t=new URL(e,location.href);return t.searchParams.set("__c3_client_id",this._swClientId),t.toString()}catch(t){return console.warn("Invalid iframe URL: "+e),e}}LoadProjectFileUrl(e){return this.GetProjectFileUrl(e)}_GetImageAssetKey(e,t){return(t?"true":"false")+"|"+e}LoadImage(e){const t=!!e.isTiled;if(e.loadPolicy&&!VALID_LOAD_POLICIES.has(e.loadPolicy))throw new Error("invalid load policy");const i=this._GetImageAssetKey(e.url,t);let s=this._imageAssetsMap.get(i);return s||(s=C3.New(C3.ImageAsset,this,{url:e.url,size:e.size||0,loadPolicy:e.loadPolicy||this._defaultLoadPolicy,isTiled:t}),this._imageAssetsMap.set(i,s),this._hasFinishedInitialLoad||(this._totalAssetSizeToLoad+=s.GetSize(),this._loadPromises.push(s.Load().then((()=>this._AddLoadedSize(s.GetSize()))))),s)}_ReleaseImageAsset(e){const t=this._GetImageAssetKey(e.GetURL(),e.IsTiled());this._imageAssetsMap.delete(t)}async WaitForAllToLoad(){try{await Promise.all(this._loadPromises),this._lastLoadProgress=1}catch(e){console.error("Error loading: ",e),this._hasHadErrorLoading=!0,this._FireLoadingProgressEvent()}}SetInitialLoadFinished(){this._hasFinishedInitialLoad=!0}HasHadErrorLoading(){return this._hasHadErrorLoading}_AddLoadedSize(e){this._assetSizeLoaded+=e,this._loadingRateLimiter.Call()}_FireLoadingProgressEvent(){const e=C3.New(C3.Event,"loadingprogress");this._lastLoadProgress=C3.clamp(this._assetSizeLoaded/this._totalAssetSizeToLoad,0,1),e.progress=this._lastLoadProgress,this._runtime.Dispatcher().dispatchEvent(e),this._runtime.DispatchUserScriptEvent(C3.New(C3.Event,"loadingprogress"))}GetLoadProgress(){return this._lastLoadProgress}GetImageLoadProgress(){return this._runtime.GetSystemPlugin().GetImageLoadingProgress()}_SetWebFonts(e){C3.shallowAssignArray(this._webFonts,e),this._webFonts.length&&this._loadPromises.push(this._LoadWebFonts())}async _LoadWebFonts(){const e=[],t=[];for(const[i,s,o]of this._webFonts)this._totalAssetSizeToLoad+=o,e.push(this._LoadWebFont(i,s,t).then((()=>this._AddLoadedSize(o))));await Promise.all(e),this._runtime.IsInWorker()&&t.length>0&&await this._runtime.PostComponentMessageToDOMAsync("runtime","load-webfonts",{"webfonts":t})}async _LoadWebFont(e,t,i){try{let s=await this.GetProjectFileUrl(t);"Gecko"===C3.Platform.BrowserEngine&&(e=`'${e}'`),("Gecko"===C3.Platform.BrowserEngine&&"preview"===this._runtime.GetExportType()||"playable-ad-single-file"===this._runtime.GetExportType())&&(s=this._GetLocalBlobURLFromFileMap(s));const o=new FontFace(e,`url('${s}')`);this._runtime.IsInWorker()?self.fonts.add(o):document.fonts.add(o),await o.load(),this._runtime.IsInWorker()&&i.push({name:e,url:s})}catch(t){console.warn(`[C3 runtime] Failed to load web font '${e}': `,t)}}IsAudioFormatSupported(e){return!!this._supportedAudioFormats[e]}_SetAudioFiles(e,t){this._preloadSounds=!!t;for(const[t,i,s]of e)this._audioFiles.set(t,{fileName:t,formats:i.map((e=>({type:e[0],fileExtension:e[1],fullName:t+e[1],fileSize:e[2]}))),isMusic:s})}GetPreferredAudioFile(e){"flat"===this._fileStructure&&(e=e.toLowerCase());const t=this._audioFiles.get(e);if(!t)return null;let i=null;for(const e of t.formats)if(i||"audio/webm; codecs=opus"!==e.type||(i=e),this.IsAudioFormatSupported(e.type))return e;return i}GetProjectAudioFileUrl(e){const t=this.GetPreferredAudioFile(e);return t?{url:this.GetMediaFileUrl(t.fullName),type:t.type}:null}GetAudioToPreload(){if(this._preloadSounds){const e=[];for(const t of this._audioFiles.values()){if(t.isMusic)continue;const i=this.GetPreferredAudioFile(t.fileName);i&&e.push({originalUrl:t.fileName,url:this.GetMediaFileUrl(i.fullName),type:i.type,fileSize:i.fileSize})}return e}return[]}_GetLocalBlobFromFileMap(e){return"preview"===this._runtime.GetExportType()&&(e=new URL(e,location.href).toString()),this._fileMap.get(e)||null}_GetLocalBlobURLFromFileMap(e){let t=this._fileMapBlobUrls.get(e);if(t)return t;const i=this._GetLocalBlobFromFileMap(e);return i?(t=URL.createObjectURL(i),this._fileMapBlobUrls.set(e,t),t):e}GetIAssetManager(){return this._iAssetManager}async LoadScripts(...e){const t=await Promise.all(e.map((e=>this.GetProjectFileUrl(e))));if(this._runtime.IsInWorker())if(1===e.length){const t=e[0];await import((C3.IsRelativeURL(t)?"./":"")+t)}else{const t=e.map((e=>`import "${C3.IsRelativeURL(e)?"./":""}${e}";`)).join("\n"),i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));await import(i)}else await Promise.all(t.map((e=>AddScript(e))))}async CompileWebAssembly(e){if(WebAssembly.compileStreaming){const t=await this.GetProjectFileUrl(e);return await WebAssembly.compileStreaming(fetch(t))}{const t=await C3.FetchArrayBuffer(e);return await WebAssembly.compile(t)}}async LoadStyleSheet(e){const t=await this.GetProjectFileUrl(e);return await this._runtime.PostComponentMessageToDOMAsync("runtime","add-stylesheet",{"url":t})}};
}

// assets/asset.js
{
const C3=self.C3;C3.Asset=class extends C3.DefendedBase{constructor(s,i){super(),this._assetManager=s,this._runtime=s.GetRuntime(),this._url=i.url||"",this._size=i.size,this._loadPolicy=i.loadPolicy,this._blob=i.blob||null,this._isLoaded=!!this._blob,this._loadPromise=null}Release(){this._loadPromise=null,this._assetManager=null,this._runtime=null,this._blob=null}GetURL(){return this._url}GetSize(){return this._size}Load(){return"local"===this._loadPolicy||this._blob?(this._isLoaded=!0,Promise.resolve()):(this._loadPromise||(this._loadPromise=this._assetManager.FetchBlob(this._url,this._loadPolicy).then((s=>(this._isLoaded=!0,this._loadPromise=null,this._blob=s,s))).catch((s=>{console.error("Error loading resource: ",s),this._loadPromise=null}))),this._loadPromise)}IsLoaded(){return this._isLoaded}GetBlob(){return this._blob?Promise.resolve(this._blob):this._loadPromise?this._loadPromise:this._assetManager.FetchBlob(this._url,this._loadPolicy)}};
}

// assets/imageAsset.js
{
const C3=self.C3,promiseThrottle=new C3.PromiseThrottle,allImageAssets=new Set;C3.ImageAsset=class extends C3.Asset{constructor(e,t){super(e,t),this._texturePromise=null,this._webglTexture=null,this._refCount=0,this._imageWidth=-1,this._imageHeight=-1,this._isTiled=!!t.isTiled,allImageAssets.add(this)}Release(){if(0!==this._refCount)throw new Error("released image asset which still has texture references");this._assetManager._ReleaseImageAsset(this),this._texturePromise=null,allImageAssets.delete(this),super.Release()}static OnRendererContextLost(){for(const e of allImageAssets)e._texturePromise=null,e._webglTexture=null,e._refCount=0}LoadStaticTexture(e,t){return t=t||{},this._refCount++,this._webglTexture?Promise.resolve(this._webglTexture):(this._texturePromise||(t.anisotropy=this._runtime.GetCanvasManager().GetTextureAnisotropy(),this._texturePromise=this._DoLoadStaticTexture(e,t)),this._texturePromise)}async _DoLoadStaticTexture(e,t){try{const s=await this.GetBlob();return 0===this._refCount?(this._texturePromise=null,null):await promiseThrottle.Add((async()=>{const r=await e.CreateStaticTextureAsync(s,t);return this._texturePromise=null,0===this._refCount?(e.DeleteTexture(r),null):(this._webglTexture=r,this._imageWidth=r.GetWidth(),this._imageHeight=r.GetHeight(),this._webglTexture)}))}catch(e){throw console.error("Failed to load texture: ",e),e}}ReleaseTexture(){if(this._refCount<=0)throw new Error("texture released too many times");if(this._refCount--,0===this._refCount&&this._webglTexture){this._webglTexture.GetRenderer().DeleteTexture(this._webglTexture),this._webglTexture=null}}GetRefCount(){return this._refCount}GetTexture(){return this._webglTexture}GetWidth(){return this._imageWidth}GetHeight(){return this._imageHeight}IsTiled(){return this._isTiled}async LoadToDrawable(){const e=await this.GetBlob();return C3.Supports.ImageBitmap?await createImageBitmap(e):await C3.BlobToImage(e)}};
}

// layouts/renderCell.js
{
const C3=self.C3,assert=self.assert;function SortByInstLastCachedZIndex(e,s){return e.GetWorldInfo()._GetLastCachedZIndex()-s.GetWorldInfo()._GetLastCachedZIndex()}C3.RenderCell=class extends C3.DefendedBase{constructor(e,s,n){super(),this._grid=e,this._x=s,this._y=n,this._instances=[],this._isSorted=!0,this._pendingRemoval=new Set,this._isAnyPendingRemoval=!1}Release(){C3.clearArray(this._instances),this._pendingRemoval.clear(),this._grid=null}Reset(){C3.clearArray(this._instances),this._isSorted=!0,this._pendingRemoval.clear(),this._isAnyPendingRemoval=!1}SetChanged(){this._isSorted=!1}IsEmpty(){return!this._instances.length||!(this._instances.length>this._pendingRemoval.size)&&(this._FlushPending(),!0)}Insert(e){if(this._pendingRemoval.has(e))return this._pendingRemoval.delete(e),void(0===this._pendingRemoval.size&&(this._isAnyPendingRemoval=!1));this._instances.push(e),this._isSorted=1===this._instances.length}Remove(e){this._pendingRemoval.add(e),this._isAnyPendingRemoval=!0,this._pendingRemoval.size>=50&&this._FlushPending()}_FlushPending(){this._isAnyPendingRemoval&&(this._instances.length!==this._pendingRemoval.size?(C3.arrayRemoveAllInSet(this._instances,this._pendingRemoval),this._pendingRemoval.clear(),this._isAnyPendingRemoval=!1):this.Reset())}_EnsureSorted(){this._isSorted||(this._instances.sort(SortByInstLastCachedZIndex),this._isSorted=!0)}Dump(e){this._FlushPending(),this._EnsureSorted(),this._instances.length&&e.push(this._instances)}};
}

// layouts/renderGrid.js
{
const C3=self.C3;C3.RenderGrid=class extends C3.DefendedBase{constructor(e,t){super(),this._cellWidth=e,this._cellHeight=t,this._cells=C3.New(C3.PairMap)}Release(){this._cells.Release(),this._cells=null}GetCell(e,t,l){let o=this._cells.Get(e,t);return o||(l?(o=C3.New(C3.RenderCell,this,e,t),this._cells.Set(e,t,o),o):null)}XToCell(e){return Math.floor(e/this._cellWidth)}YToCell(e){return Math.floor(e/this._cellHeight)}Update(e,t,l){if(t)for(let o=t.getLeft(),s=t.getRight();o<=s;++o)for(let s=t.getTop(),i=t.getBottom();s<=i;++s){if(l&&l.containsPoint(o,s))continue;const t=this.GetCell(o,s,!1);t&&(t.Remove(e),t.IsEmpty()&&this._cells.Delete(o,s))}if(l)for(let o=l.getLeft(),s=l.getRight();o<=s;++o)for(let s=l.getTop(),i=l.getBottom();s<=i;++s)t&&t.containsPoint(o,s)||this.GetCell(o,s,!0).Insert(e)}QueryRange(e,t){let l=this.XToCell(e.getLeft());const o=this.YToCell(e.getTop()),s=this.XToCell(e.getRight()),i=this.YToCell(e.getBottom());for(;l<=s;++l)for(let e=o;e<=i;++e){const o=this.GetCell(l,e,!1);o&&o.Dump(t)}}MarkRangeChanged(e){let t=e.getLeft();const l=e.getTop(),o=e.getRight(),s=e.getBottom();for(;t<=o;++t)for(let e=l;e<=s;++e){const l=this.GetCell(t,e,!1);l&&l.SetChanged()}}};
}

// layouts/layer.js
{
const C3=self.C3,assert=self.assert,tmpRect=new C3.Rect,tmpQuad=new C3.Quad,renderCellArr=[],tmpDestRect=new C3.Rect,tmpSrcRect=new C3.Rect,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,mat4=glMatrix.mat4,tempMat4=mat4.create(),tempVec3=vec3.create(),tempVec4=vec4.create(),camVector=vec3.create(),lookVector=vec3.create(),upVector=vec3.create(),tempVec2=C3.New(C3.Vector2),tempRect=C3.New(C3.Rect);function SortByInstLastCachedZIndex(e,t){return e.GetWorldInfo()._GetLastCachedZIndex()-t.GetWorldInfo()._GetLastCachedZIndex()}function SortByInstZElevation(e,t){return e.GetWorldInfo().GetZElevation()-t.GetWorldInfo().GetZElevation()}const tempInstanceList1=[],tempInstanceList2=[],tempInstancesByCameraDist=[],DEFAULT_LAYER_OPTIONS={name:"",sid:-1,isDynamic:!1,isVisible:!0,isInteractive:!0,isHTMLElementsLayer:!1,backgroundColor:[1,1,1,1],isTransparent:!0,parallax:[1,1],opacity:1,isForceOwnTexture:!1,renderAs3d:!1,useCameraDistanceDrawOrder:!1,useRenderCells:!1,scaleRate:1,blendMode:0,zElevation:0,initialInstancesData:[],effectListData:[],subLayersData:[]};C3.Layer=class extends C3.DefendedBase{constructor(e,t,s){super(),s=Object.assign({},DEFAULT_LAYER_OPTIONS,s),this._layout=e,this._runtime=e.GetRuntime(),this._parentLayer=t,this._name=s.name,this._index=-1,this._isHTMLElementsLayer=!!s.isHTMLElementsLayer,this._htmlIndex=-1,this._sid=s.sid,this._isDynamic=!!s.isDynamic,this._isVisible=!!s.isVisible,this._isInteractive=!!s.isInteractive,this._backgroundColor=C3.New(C3.Color),this._backgroundColor.setFromJSON(s.backgroundColor),this._isTransparent=!!s.isTransparent,this._parallaxX=s.parallax[0],this._parallaxY=s.parallax[1],this._color=C3.New(C3.Color,1,1,1,s.opacity),this._premultipliedColor=C3.New(C3.Color),this._isForceOwnTexture=!!s.isForceOwnTexture,this._renderAs3d=!!s.renderAs3d,this._useCameraDistanceDrawOrder=!!s.useCameraDistanceDrawOrder,this._useRenderCells=!!s.useRenderCells,this._scaleRate=s.scaleRate,this._blendMode=s.blendMode,this._curRenderTarget=null,this._scale=1,this._zElevation=s.zElevation,this._angle=0,this._scrollX=0,this._scrollY=0,this._hasOwnScrollPosition=!1,this._viewport=C3.New(C3.Rect),this._viewportZ0=C3.New(C3.Rect),this._viewport3D=C3.New(C3.Rect),this._isViewportChanged=!0,this._projectionMatrix=mat4.create(),this._isProjectionMatrixChanged=!0,this._modelViewMatrix=mat4.create(),this._isMVMatrixChanged=!0,this._viewFrustum=C3.New(C3.Gfx.ViewFrustum),this._isViewFrustumChanged=!0,this._startupInitialInstances=[],this._initialInstancesData=s.initialInstancesData,this._initialInstances=[],this._createdGlobalUids=[],this._initialUIDsToInstanceData=new Map,this._instances=[],this._zIndicesUpToDate=!1,this._htmlZIndicesUpToDate=!1,this._anyInstanceZElevated=!1;const a=this._runtime.GetCanvasManager();this._effectList=C3.New(C3.EffectList,this,s.effectListData),this._effectChain=C3.New(C3.Gfx.EffectChain,a.GetEffectChainManager(),{drawContent:(e,t)=>{const s=t.GetContentObject(),i=s.GetRenderTarget();e.SetColor(s.GetPremultipliedColor()),e.DrawRenderTarget(i),e.InvalidateRenderTarget(i),a.ReleaseAdditionalRenderTarget(i)},getShaderParameters:e=>this.GetEffectList()._GetEffectChainShaderParametersForIndex(e)}),this._needsRebuildEffectChainSteps=!0,this._wasDefaultColor=!0,this._renderGrid=null,this._lastRenderList=[],this._isRenderListUpToDate=!1,this._lastRenderCells=C3.New(C3.Rect,0,0,-1,-1),this._curRenderCells=C3.New(C3.Rect,0,0,-1,-1),this._iLayer=new self.ILayer(this),this._UpdatePremultipliedColor(),this.UsesRenderCells()&&(this._renderGrid=C3.New(C3.RenderGrid,this._runtime.GetOriginalViewportWidth(),this._runtime.GetOriginalViewportHeight())),this._subLayers=s.subLayersData.map((e=>C3.Layer.CreateFromExportData(this._layout,this,e)))}_InitInitialInstances(){for(const e of this._initialInstancesData){const t=this._runtime.GetObjectClassByIndex(e[1]);this._layout._AddInitialObjectClass(t),t.GetDefaultInstanceData()||(t.SetDefaultInstanceData(e),t._SetDefaultLayerIndex(this._index)),this._initialInstances.push(e),this._initialUIDsToInstanceData.set(e[2],e)}C3.shallowAssignArray(this._startupInitialInstances,this._initialInstances),this._initialInstancesData=null}static CreateFromExportData(e,t,s){return C3.New(C3.Layer,e,t,{name:s[0],sid:s[2],isVisible:s[3],isInteractive:s[13],isHTMLElementsLayer:s[19],backgroundColor:s[4].map((e=>e/255)),isTransparent:s[5],parallax:[s[6],s[7]],opacity:s[8],isForceOwnTexture:s[9],renderAs3d:s[17],useCameraDistanceDrawOrder:s[18],useRenderCells:s[10],scaleRate:s[11],blendMode:s[12],zElevation:s[16],initialInstancesData:s[14],effectListData:s[15],subLayersData:s[20]})}Release(){for(const e of this._subLayers)e.Release();C3.clearArray(this._subLayers);for(const e of this._instances)this._runtime.DestroyInstance(e);C3.clearArray(this._instances),this._effectList.Release(),this._effectList=null,this._effectChain.Release(),this._effectChain=null,this._iLayer=null,this._parentLayer=null,this._layout=null,this._runtime=null}WasReleased(){return!this._layout}GetInitialInstanceData(e){return this._initialUIDsToInstanceData.get(e)}CreateInitialInstances(e){const t=this._layout.IsFirstVisit(),s=this._initialInstances;let a=0;for(let i=0,r=s.length;i<r;++i){const r=s[i],n=this._runtime.GetObjectClassByIndex(r[1]);let l=!0;if(!n.HasPersistBehavior()||t){const t=this._runtime.CreateInstanceFromData(r,this,!0);e.push(t),n.IsGlobal()&&(l=!1,this._createdGlobalUids.push(t.GetUID()))}l&&(s[a]=s[i],++a)}C3.truncateArray(s,a),this._runtime.FlushPendingInstances(),this.SetZIndicesChanged()}_AddInstance(e,t){if(!e.GetPlugin().IsWorldType())throw new Error("instance is not of world type");const s=e.GetWorldInfo();if(s.GetLayer()!==this)throw new Error("instance added to wrong layer");this._instances.push(e),0!==s.GetZElevation()&&(this._anyInstanceZElevated=!0),t&&this.UsesRenderCells()&&e.GetWorldInfo().SetBboxChanged(),this.SetZIndicesChanged(e)}_MaybeAddInstance(e){this._instances.includes(e)||(this._instances.push(e),0!==e.GetWorldInfo().GetZElevation()&&(this._anyInstanceZElevated=!0),this.SetZIndicesChanged(e))}_PrependInstance(e,t){const s=e.GetWorldInfo();if(s.GetLayer()!==this)throw new Error("instance added to wrong layer");this._instances.unshift(e),0!==s.GetZElevation()&&(this._anyInstanceZElevated=!0),this.SetZIndicesChanged(e),t&&this.UsesRenderCells()&&e.GetWorldInfo().SetBboxChanged()}_RemoveInstance(e,t){const s=this._instances.indexOf(e);s<0||(t&&this.UsesRenderCells()&&e.GetWorldInfo()._RemoveFromRenderCells(),this._instances.splice(s,1),this.SetZIndicesChanged(e),this._MaybeResetAnyInstanceZElevatedFlag())}_SetAnyInstanceZElevated(){this._anyInstanceZElevated=!0}_MaybeResetAnyInstanceZElevatedFlag(){0===this._instances.length&&(this._anyInstanceZElevated=!1)}_SortInstancesByLastCachedZIndex(e){if(e){const e=new Set;for(const t of this._instances){const s=t.GetWorldInfo()._GetLastCachedZIndex();s>=0&&e.add(s)}let t=-1;for(const s of this._instances){const a=s.GetWorldInfo();if(!(a._GetLastCachedZIndex()>=0)){for(++t;e.has(t);)++t;a._SetZIndex(t)}}}this._instances.sort(SortByInstLastCachedZIndex)}_Start(){}_End(){for(const e of this._instances)e.GetObjectClass().IsGlobal()||this._runtime.DestroyInstance(e);this._runtime.FlushPendingInstances(),C3.clearArray(this._instances),this._anyInstanceZElevated=!1,this.SetZIndicesChanged()}RecreateInitialObjects(e,t,s,a,i,r){const n=this._runtime.GetEventSheetManager(),l=this._runtime.GetAllObjectClasses(),o=e.IsFamily(),h=[];for(const c of this._initialInstances){const d=c[0],_=d[0],u=d[1];if(!t.containsPoint(_,u))continue;const G=l[c[1]];if(G!==e){if(!o)continue;if(!e.FamilyHasMember(G))continue}let f=i;if(!f){const e=this._runtime.GetCurrentLayout();this.GetLayout()===e?f=this:(f=e.GetLayerByName(this.GetName()),f||(f=e.GetLayerByIndex(this.GetIndex())))}const p=this._runtime.CreateInstanceFromData(c,f,!1,void 0,void 0,!1,r);f.SortAndAddInstancesByZIndex(p);const I=p.GetWorldInfo();I.OffsetXY(s,a),I.SetBboxChanged(),n.BlockFlushingInstances(!0),p._TriggerOnCreatedOnSelfAndRelated(),n.BlockFlushingInstances(!1),h.push(p)}return h}GetInstanceCount(){return this._instances.length}GetLayout(){return this._layout}GetName(){return this._name}_SetIndex(e){this._index=e}GetIndex(){return this._index}_SetHTMLIndex(e){this._htmlIndex=e}GetHTMLIndex(){return this._htmlIndex}IsHTMLElementsLayer(){return this._isHTMLElementsLayer}SetIsHTMLElementsLayer(e){e=!!e,this._isHTMLElementsLayer!==e&&(this._isHTMLElementsLayer=e,this._layout._ReindexAndUpdateAllLayers(),this._runtime.UpdateRender())}_GetSiblingIndex(){let e=-1;const t=this.GetParentLayer();return e=t?t.GetSubLayers().indexOf(this):this.GetLayout()._GetRootLayers().indexOf(this),e}GetSID(){return this._sid}GetRuntime(){return this._runtime}IsDynamic(){return this._isDynamic}HasAnyDynamicParentLayer(){for(const e of this.parentLayers())if(e.IsDynamic())return!0;return!1}GetDevicePixelRatio(){return this._runtime.GetDevicePixelRatio()}GetEffectList(){return this._effectList}GetEffectChain(){return this._MaybeRebuildEffectChainSteps(),this._effectChain}_MaybeRebuildEffectChainSteps(){const e=this.HasDefaultColor();if(!this._needsRebuildEffectChainSteps&&e===this._wasDefaultColor&&!this._effectChain.NeedsRebuild())return;const t=this.GetEffectList().GetActiveEffectTypes();this._effectChain.BuildSteps(t.map((e=>e.GetShaderProgram())),{indexMap:t.map((e=>e.GetIndex())),forcePreDraw:!e,useFullSurface:!0}),this._needsRebuildEffectChainSteps=!1,this._wasDefaultColor=e}UpdateActiveEffects(){this.GetEffectList().UpdateActiveEffects(),this._needsRebuildEffectChainSteps=!0}UsesRenderCells(){return this._useRenderCells&&!this._useCameraDistanceDrawOrder}GetRenderGrid(){return this._renderGrid}SetRenderListStale(){this._isRenderListUpToDate=!1}IsVisible(){for(const e of this.selfAndParentLayers())if(!e._IsVisibleFlagSet())return!1;return!0}_IsVisibleFlagSet(){return this._isVisible}SetVisible(e){e=!!e,this._isVisible!==e&&(this._isVisible=e,this._runtime.UpdateRender())}SetInteractive(e){this._isInteractive=!!e}IsInteractive(){return this._isInteractive}IsSelfAndParentsInteractive(){for(const e of this.selfAndParentLayers())if(!e.IsInteractive())return!1;return!0}SetOwnScrollPositionEnabled(e){if(e=!!e,this._hasOwnScrollPosition!==e){if(this._hasOwnScrollPosition=e,e){const e=this.GetLayout();this._scrollX=e.GetScrollX(),this._scrollY=e.GetScrollY()}this._SetMVMatrixChanged(),this._runtime.UpdateRender()}}IsOwnScrollPositionEnabled(){return this._hasOwnScrollPosition}SetScrollX(e){const t=this.GetLayout(),s=t.GetScrollLeftBound(),a=t.GetScrollRightBound();e>a&&(e=a),e<s&&(e=s),this._scrollX!==e&&(this._scrollX=e,this.IsOwnScrollPositionEnabled()&&(this._SetMVMatrixChanged(),this._runtime.UpdateRender()))}SetScrollY(e){const t=this.GetLayout(),s=t.GetScrollTopBound(),a=t.GetScrollBottomBound();e>a&&(e=a),e<s&&(e=s),this._scrollY!==e&&(this._scrollY=e,this.IsOwnScrollPositionEnabled()&&(this._SetMVMatrixChanged(),this._runtime.UpdateRender()))}GetScrollX(){return this.IsOwnScrollPositionEnabled()?this._scrollX:this.GetLayout().GetScrollX()}GetScrollY(){return this.IsOwnScrollPositionEnabled()?this._scrollY:this.GetLayout().GetScrollY()}GetViewport(){return this._MaybeUpdateViewport(),this._viewport}_GetViewportZ0(){return this._MaybeUpdateViewport(),this._viewportZ0}GetViewport3D(){return this._MaybeUpdateViewport(),this._viewport3D}_GetVanishingPoint(){const e=this.GetLayout();return[e.GetVanishingPointX(),e.GetVanishingPointY()]}GetDefaultCameraZ(e){return this._runtime.GetDefaultCameraZ(e)}GetViewportForZ(e,t){const s=this._GetViewportZ0();if(0===e)t.copy(s);else{let a=s.midX(),i=s.midY();const r=this.Get2DScaleFactorToZ(e),n=s.width()/r,l=s.height()/r,[o,h]=this._GetVanishingPoint();if(.5!==o||.5!==h){const t=this.Get2DCameraZ(),s=this._runtime,r=this.GetDefaultCameraZ()/t;let n=(o-.5)*s.GetViewportWidth()/r,l=(h-.5)*s.GetViewportHeight()/r;const c=this.GetAngle();0!==c&&(tempVec2.set(n,l),tempVec2.rotate(c),n=tempVec2.getX(),l=tempVec2.getY());const d=C3.unlerp(t,0,e);a+=C3.lerp(n,0,d),i+=C3.lerp(l,0,d)}t.set(a-n/2,i-l/2,a+n/2,i+l/2)}}GetOpacity(){return this._color.getA()}SetOpacity(e){e=C3.clamp(e,0,1),this._color.getA()!==e&&(this._color.setA(e),this._UpdatePremultipliedColor(),this._runtime.UpdateRender())}_UpdatePremultipliedColor(){this._premultipliedColor.copy(this._color),this._premultipliedColor.premultiply()}GetPremultipliedColor(){return this._premultipliedColor}HasDefaultColor(){return this._color.equalsRgba(1,1,1,1)}GetScaleRate(){return this._scaleRate}SetScaleRate(e){this._scaleRate!==e&&(this._scaleRate=e,this._SetMVMatrixChanged(),this._runtime.UpdateRender())}GetParallaxX(){return this._parallaxX}GetParallaxY(){return this._parallaxY}SetParallax(e,t){this._parallaxX===e&&this._parallaxY===t||(this._parallaxX=e,this._parallaxY=t,this._SetMVMatrixChanged(),this._runtime.UpdateRender())}SetParallaxX(e){this.SetParallax(e,this.GetParallaxY())}SetParallaxY(e){this.SetParallax(this.GetParallaxX(),e)}SetZElevation(e){this._zElevation!==e&&(this._zElevation=e,this._runtime.UpdateRender())}GetZElevation(){return this._zElevation}SetAngle(e){e=C3.clampAngle(e),this._angle!==e&&(this._angle=e,this._SetMVMatrixChanged(),this._runtime.UpdateRender())}GetAngle(){return C3.clampAngle(this._layout.GetAngle()+this._angle)}GetOwnAngle(){return this._angle}HasInstances(){return this._instances.length>0}_GetInstances(){return this._instances}_GetInstancesInDrawOrder(){return this.RendersIn3DMode()&&this._useCameraDistanceDrawOrder?(C3.shallowAssignArray(tempInstancesByCameraDist,this._GetInstances()),tempInstancesByCameraDist.sort(((e,t)=>this._SortInstancesByCameraDistance(e,t))),tempInstancesByCameraDist):this._GetInstances()}_AppendAllInstancesIncludingSubLayersInDrawOrder(e){C3.appendArray(e,this._GetInstancesInDrawOrder());for(const t of this._subLayers)t.IsVisible()&&t.GetOpacity()>0&&t._AppendAllInstancesIncludingSubLayersInDrawOrder(e)}_SortInstancesByCameraDistance(e,t){const s=this.GetLayout().Get3DCameraPosition(),a=s[0],i=s[1],r=s[2],n=e.GetWorldInfo(),l=t.GetWorldInfo(),o=n.GetX()-a,h=n.GetY()-i,c=n.GetZElevation()-r,d=l.GetX()-a,_=l.GetY()-i,u=l.GetZElevation()-r;return d*d+_*_+u*u-(o*o+h*h+c*c)}GetBackgroundColor(){return this._backgroundColor}IsTransparent(){return this._isTransparent}SetTransparent(e){e=!!e,this._isTransparent!==e&&(this._isTransparent=e,this._runtime.UpdateRender())}IsForceOwnTexture(){return this._isForceOwnTexture}SetForceOwnTexture(e){e=!!e,this._isForceOwnTexture!==e&&(this._isForceOwnTexture=e,this._runtime.UpdateRender())}SetRenderAs3D(e){e=!!e,this._renderAs3d!==e&&(this._renderAs3d=e,this._SetMVMatrixChanged(),this._runtime.UpdateRender())}IsRenderAs3D(){return this._renderAs3d}RendersIn2DMode(){return!this.GetRuntime().Uses3DFeatures()||!this._renderAs3d}RendersIn3DMode(){return!this.RendersIn2DMode()}Has3DCamera(){return this.RendersIn3DMode()&&this.GetLayout().Is3DCameraEnabled()}SelfAndAllSubLayersHave3DCamera(){if(!this.Has3DCamera())return!1;for(const e of this._subLayers)if(!e.SelfAndAllSubLayersHave3DCamera())return!1;return!0}SetBlendMode(e){this._blendMode!==e&&(this._blendMode=e,this._runtime.UpdateRender())}GetBlendMode(){return this._blendMode}IsRootLayer(){return!this._parentLayer}GetParentLayer(){return this._parentLayer}_SetParentLayer(e){this._parentLayer=e}GetSubLayers(){return this._subLayers}HasAnySubLayers(){return this._subLayers.length>0}_AddSubLayer(e,t=!0){t?this._subLayers.push(e):this._subLayers.unshift(e)}_InsertSubLayer(e,t,s){let a=this._subLayers.indexOf(t);if(-1===a)throw new Error("cannot find layer to insert by");s&&++a,this._subLayers.splice(a,0,e)}_RemoveSubLayer(e){const t=this._subLayers.indexOf(e);if(-1===t)throw new Error("cannot find layer to remove");this._subLayers.splice(t,1)}HasAnyVisibleSubLayer(){for(const e of this._subLayers)if(e.ShouldDraw())return!0;return!1}*selfAndAllSubLayers(){for(const e of this._subLayers)yield*e.selfAndAllSubLayers();yield this}*parentLayers(){let e=this.GetParentLayer();for(;e;)yield e,e=e.GetParentLayer()}*selfAndParentLayers(){yield this,yield*this.parentLayers()}HasParentLayer(e){for(const t of this.parentLayers())if(t===e)return!0;return!1}IsTransformCompatibleWith(e){return this===e||this._parallaxX===e._parallaxX&&this._parallaxY===e._parallaxY&&this._scale===e._scale&&this._scaleRate===e._scaleRate&&this._angle===e._angle&&this.GetScrollX()===e.GetScrollX()&&this.GetScrollY()===e.GetScrollY()}SaveTransform(){return{"parallaxX":this.GetParallaxX(),"parallaxY":this.GetParallaxY(),"scale":this.GetOwnScale(),"scaleRate":this.GetScaleRate(),"angle":this.GetOwnAngle(),"hasOwnScroll":this.IsOwnScrollPositionEnabled(),"scrollX":this.GetScrollX(),"scrollY":this.GetScrollY()}}RestoreTransform(e){this.SetParallax(e["parallaxX"],e["parallaxY"]),this.SetOwnScale(e["scale"]),this.SetScaleRate(e["scaleRate"]),this.SetAngle(e["angle"]),this.SetOwnScrollPositionEnabled(e["hasOwnScroll"]),this.SetScrollX(e["scrollX"]),this.SetScrollY(e["scrollY"]),this._MaybeUpdateViewport()}_RemoveAllInstancesInSet(e){if(0===e.size)return;C3.arrayRemoveAllInSet(this._instances,e)>0&&(this._MaybeResetAnyInstanceZElevatedFlag(),this.SetZIndicesChanged())}SetZIndicesChanged(e){this._zIndicesUpToDate=!1,this._isRenderListUpToDate=!1,e&&!e.GetObjectClass().GetPlugin().IsHTMLElementType()||(this._htmlZIndicesUpToDate=!1)}_UpdateZIndices(){if(!this._zIndicesUpToDate){if(this._instances.sort(SortByInstZElevation),this.UsesRenderCells())for(let e=0,t=this._instances.length;e<t;++e){const t=this._instances[e].GetWorldInfo();t._SetZIndex(e),this._renderGrid.MarkRangeChanged(t.GetRenderCellRange())}else for(let e=0,t=this._instances.length;e<t;++e)this._instances[e].GetWorldInfo()._SetZIndex(e);this._zIndicesUpToDate=!0}}_UpdateHTMLZIndices(){if(this._htmlZIndicesUpToDate)return;const e=this._layout.GetRootLayersForHTMLLayer(this.GetHTMLIndex()).map((e=>[...e.selfAndAllSubLayers()])).flat();let t=0;for(const s of e){for(const e of s._GetInstances())e.GetObjectClass().GetPlugin().IsHTMLElementType()&&e.GetWorldInfo()._SetHTMLZIndex(t++);s._SetHTMLZIndicesUpToDate()}}_SetHTMLZIndicesUpToDate(){this._htmlZIndicesUpToDate=!0}_GetHTMLLayerDOMState(){return{"isVisible":this.IsVisible(),"opacity":this.GetOpacity(),"isInteractive":this.IsInteractive()}}MoveInstanceAdjacent(e,t,s){const a=e.GetWorldInfo(),i=t.GetWorldInfo();if(a.GetLayer()!==this||i.GetLayer()!==this)throw new Error("can't arrange Z order unless both objects on this layer");const r=a.GetZIndex();let n=i.GetZIndex();return r!==n+(s?1:-1)&&(C3.arrayRemove(this._instances,r),r<n&&n--,s&&n++,n===this._instances.length?this._instances.push(e):this._instances.splice(n,0,e),this.SetZIndicesChanged(e),!0)}_MergeSortedZArrays(e,t){const s=[];let a=0,i=0,r=e.length,n=t.length;for(;a<r&&i<n;){const r=e[a],n=t[i];r.GetWorldInfo()._GetLastCachedZIndex()<n.GetWorldInfo()._GetLastCachedZIndex()?(s.push(r),++a):(s.push(n),++i)}for(;a<r;++a)s.push(e[a]);for(;i<n;++i)s.push(t[i]);return s}_MergeAllSortedZArrays_pass(e){const t=[],s=e.length;for(let a=0;a<s-1;a+=2){const s=e[a],i=e[a+1];t.push(this._MergeSortedZArrays(s,i))}return s%2==1&&t.push(e[s-1]),t}_MergeAllSortedZArrays(e){for(;e.length>1;)e=this._MergeAllSortedZArrays_pass(e);return e[0]}_GetRenderCellInstancesToDraw(){return this._UpdateZIndices(),C3.clearArray(renderCellArr),this._renderGrid.QueryRange(this.GetViewport(),renderCellArr),renderCellArr.length?1===renderCellArr.length?renderCellArr[0]:this._MergeAllSortedZArrays(renderCellArr):[]}ShouldDraw(){return this.IsVisible()&&this.GetOpacity()>0&&this._DrawsAnyContentInSelfOrSubLayers()}_DrawsAnyContentInSelfOrSubLayers(){if(this.HasInstances()||!this.IsTransparent())return!0;for(const e of this._subLayers)if(e._DrawsAnyContentInSelfOrSubLayers())return!0;return!1}UsesOwnTexture(){return this.IsForceOwnTexture()||!this.HasDefaultColor()||0!==this.GetBlendMode()||this._effectList.HasAnyActiveEffect()}SelfOrAnySubLayerUsesOwnTexture(){if(this.UsesOwnTexture())return!0;for(const e of this._subLayers)if(e.SelfOrAnySubLayerUsesOwnTexture())return!0;return!1}GetRenderTarget(){return this._curRenderTarget}Get2DScaleFactorToZ(e){if(this._layout.IsOrthographicProjection())return 1;{const t=this.Get3DCameraZ();return t/(t-e)}}GetResolutionScaleFactorToZ(e){const t=this._runtime.GetRenderScale();if(this._layout.IsOrthographicProjection())return t;{const s=this.Get3DCameraZ();return this.GetDefaultCameraZ()/Math.abs(s-e)*t}}_SetMVMatrixChanged(){this._isMVMatrixChanged=!0,this._isViewFrustumChanged=!0,this._isViewportChanged=!0}_GetModelViewMatrix(e){return this._isMVMatrixChanged&&(this._CalculateModelViewMatrix(e,this._modelViewMatrix,0,0,null),this._isMVMatrixChanged=!1),this._modelViewMatrix}Get2DCameraZ(e){return this.GetDefaultCameraZ(e)/this.GetNormalScale()}Get3DCameraZ(){return this.Has3DCamera()?this.GetLayout().Get3DCameraPosition()[2]:this.Get2DCameraZ()}GetCameraPosition(){if(this.Has3DCamera()){const e=this.GetLayout().Get3DCameraPosition();return[e[0],e[1],e[2]]}return this._Get2DCameraPosition()}_Get2DCameraPosition(e=0,t=0,s=0){const a=this._runtime,i=this.GetLayout(),r=a.GetParallaxXOrigin(),n=a.GetParallaxYOrigin();let l=(this.GetScrollX()-r)*this._parallaxX+r,o=(this.GetScrollY()-n)*this._parallaxY+n;a.IsPixelRoundingEnabled()&&(l=Math.round(l),o=Math.round(o));let h=l+e,c=o+t;const d=i.IsOrthographicProjection()?this.GetDefaultCameraZ(s):this.Get2DCameraZ(s),[_,u]=this._GetVanishingPoint();if(.5!==_||.5!==u){const e=this.GetDefaultCameraZ(s)/d;let t=(_-.5)*a.GetViewportWidth()/e,i=(u-.5)*a.GetViewportHeight()/e;const r=this.GetAngle();0!==r&&(tempVec2.set(t,i),tempVec2.rotate(r),t=tempVec2.getX(),i=tempVec2.getY()),h+=t,c+=i}return[h,c,d]}_CalculateModelViewMatrix(e,t,s,a,i){const r=this._runtime,n=this.GetLayout();if(this.Has3DCamera()){vec3.copy(camVector,n.Get3DCameraPosition()),vec3.copy(lookVector,n.Get3DCameraLookAt()),vec3.copy(upVector,n.Get3DCameraUpVector());const e=r.GetParallaxXOrigin(),t=r.GetParallaxYOrigin(),s=lookVector[0]-camVector[0],a=lookVector[1]-camVector[1],i=lookVector[2]-camVector[2];camVector[0]=(camVector[0]-e)*this._parallaxX+e,camVector[1]=(camVector[1]-t)*this._parallaxY+t,camVector[2]*=Math.max(this._parallaxX,this._parallaxY),lookVector[0]=camVector[0]+s,lookVector[1]=camVector[1]+a,lookVector[2]=camVector[2]+i}else{const[e,t,r]=this._Get2DCameraPosition(s,a,i);vec3.set(camVector,e,t,r),vec3.set(lookVector,e,t,r-100);const n=this.GetAngle();0===n?vec3.set(upVector,0,1,0):vec3.set(upVector,Math.sin(n),Math.cos(n),0)}e.CalculateLookAtModelView(t,camVector,lookVector,upVector,i||r.GetViewportHeight())}_SetProjectionMatrixChanged(){this._isProjectionMatrixChanged=!0,this._isViewFrustumChanged=!0,this._isViewportChanged=!0}_GetProjectionMatrix(e){return this._isProjectionMatrixChanged&&(this._CalculateProjectionMatrix(e),this._isProjectionMatrixChanged=!1),this._projectionMatrix}_CalculateProjectionMatrix(e){const t=this._runtime.GetCanvasManager(),[s,a]=this._GetVanishingPoint();if(this._layout.IsOrthographicProjection())e.CalculateOrthographicMatrix(this._projectionMatrix,t.GetDrawWidth(),t.GetDrawHeight());else if(.5===s&&.5===a)mat4.copy(this._projectionMatrix,t.GetDefaultProjectionMatrix());else{const i=t.GetDrawWidth(),r=t.GetDrawHeight();e.CalculatePerspectiveMatrix(this._projectionMatrix,i/r,s,a)}}_SetTransform(e,t=!0,s=0,a=0,i=0){t&&e.SetProjectionMatrix(this._GetProjectionMatrix(e));let r=null;0===s&&0===a&&0===i?r=this._GetModelViewMatrix(e):(this._CalculateModelViewMatrix(e,tempMat4,s,a,i),r=tempMat4),e.SetModelViewMatrix(r)}PrepareForDraw(e){this._SetTransform(e),e.SetBaseZ(this.GetZElevation())}_MaybeStartWebGLProfiling(e){let t=null;if(e.IsWebGL()&&this._runtime.IsGPUProfiling()){const s=this._runtime.GetCanvasManager().GetLayerTimingsBuffer(this);s&&(t=s.AddTimeElapsedQuery(),e.StartQuery(t))}return t}_MaybeStartWebGPUProfiling(e){if(e.IsWebGPU()&&this._runtime.IsGPUProfiling()){const t=2*(this.GetIndex()+1);e.StartMeasuringRenderPassTime(t,t+1)}}Draw(e,t,s){const a=this._runtime.GetCanvasManager(),i=this.UsesOwnTexture();let r=null;const n=this._MaybeStartWebGLProfiling(e);if(this._MaybeStartWebGPUProfiling(e),i){const t={sampling:this._runtime.GetSampling(),isSampled:!0,canReadPixels:!!e.IsWebGPU()&&this._runtime.UsesAnyBackgroundBlending()};"low"===a.GetCurrentFullscreenScalingQuality()&&(t.width=a.GetDrawWidth(),t.height=a.GetDrawHeight()),r=this._runtime.GetAdditionalRenderTarget(t),this._curRenderTarget=r,e.SetRenderTarget(r),this.IsTransparent()&&e.ClearRgba(0,0,0,0)}else this._curRenderTarget=t,e.SetRenderTarget(t);if(this.IsTransparent()||e.Clear(this._backgroundColor),this._layout._DrawLayerList(e,this._curRenderTarget,this._subLayers,i&&this.IsTransparent()),this._MaybeStartWebGPUProfiling(e),this._SetTransform(e),e.SetBaseZ(this.GetZElevation()),e.SetDepthEnabled(this.RendersIn3DMode()),this.GetNormalScale()>Number.EPSILON){this._UpdateZIndices();const t=this.UsesRenderCells()&&0===this.GetZElevation()&&!this._anyInstanceZElevated;this.Has3DCamera()?this._DrawInstances_3DCamera(e):t?this._DrawInstances_RenderCells(e):this._DrawInstances(e,this._GetInstancesInDrawOrder())}e.SetBaseZ(0),e.SetCurrentZ(0),i&&(e.SetDepthEnabled(!1),this._DrawLayerOwnTextureToRenderTarget(e,r,t,s)),n&&e.EndQuery(n),this._curRenderTarget=null}_DrawInstances(e,t){const s=this.GetViewport(),a=this._curRenderTarget,i=this.GetLayout().IsOrthographicProjection(),r=this.GetLayout().HasVanishingPointOutsideViewport();let n=null;for(let l=0,o=t.length;l<o;++l){const o=t[l];if(o===n)continue;n=o;const h=o.GetWorldInfo();h.IsVisible()&&h.IsInViewport(s,r,i)&&this._DrawInstanceMaybeWithEffects(o,h,e,a)}}_DrawInstances_3DCamera(e){const t=this._curRenderTarget,s=this._GetViewFrustum(),a=tempInstanceList1,i=tempInstanceList2,r=this._GetInstancesInDrawOrder();for(let n=0,l=r.length;n<l;){const o=r[n],h=o.GetWorldInfo();if(!h.IsVisible()||!h.IsInViewport3D(s)){++n;continue}(!o.RendersToOwnZPlane()||h.GetDepth()>0)&&i.push(o);const c=o.GetWorldInfo().GetTotalZElevation();a.push(o);let d=n+1;for(;d<l;++d){const e=r[d],t=e.GetWorldInfo();if(t.IsVisible()&&t.IsInViewport3D(s)){if(t.GetTotalZElevation()!==c)break;e.RendersToOwnZPlane()?(t.GetDepth()>0&&i.push(e),a.push(e)):i.push(e)}}if(1!==a.length||a[0].MustMitigateZFighting()){this._DrawCoplanarInstances_3DCamera(e,a);for(let s=0,a=i.length;s<a;++s){const a=i[s],r=a.GetWorldInfo();r._SetDrawNonBackFacesOnly(!0),this._DrawInstanceMaybeWithEffects(a,r,e,t),r._SetDrawNonBackFacesOnly(!1)}}else{this._DrawInstanceMaybeWithEffects(o,h,e,t);for(let s=0,a=i.length;s<a;++s){const a=i[s];if(a===o)continue;const r=a.GetWorldInfo();r.GetLayer()._DrawInstanceMaybeWithEffects(a,r,e,t)}}n=d,C3.clearArray(a),C3.clearArray(i)}}_DrawCoplanarInstances_3DCamera(e,t){const s=this._curRenderTarget;e.CoplanarStartStencilPass();for(let s=0,a=t.length;s<a;++s){const a=t[s],i=a.GetWorldInfo();i._SetDrawBackFaceOnly(!0),this._DrawInstance(a,i,e)}e.CoplanarStartColorPass();for(let a=0,i=t.length;a<i;++a){const i=t[a],r=i.GetWorldInfo();this._DrawInstanceMaybeWithEffects(i,r,e,s),r._SetDrawBackFaceOnly(!1)}e.CoplanarRestoreStandardRendering()}_DrawInstances_RenderCells(e){const t=this._renderGrid,s=this._curRenderCells,a=this._lastRenderCells,i=this.GetViewport();let r;s.set(t.XToCell(i.getLeft()),t.YToCell(i.getTop()),t.XToCell(i.getRight()),t.YToCell(i.getBottom())),this._isRenderListUpToDate&&s.equals(a)?r=this._lastRenderList:(r=this._GetRenderCellInstancesToDraw(),this._isRenderListUpToDate=!0,a.copy(s)),this._DrawInstances(e,r),r!==this._lastRenderList&&C3.shallowAssignArray(this._lastRenderList,r)}_DrawInstanceMaybeWithEffects(e,t,s,a){t.HasAnyActiveEffect()?this._DrawInstanceWithEffectsAndRestore(e,t,s,a):this._DrawInstance(e,t,s)}_DrawInstance(e,t,s){const a=t.GetRendererStateGroup();s.GetCurrentStateGroup()!==a&&a.Apply(),e.Draw(s)}_DrawInstanceWithEffectsAndRestore(e,t,s,a){this._DrawInstanceWithEffects(e,t,s,a,null)&&this._SetTransform(s)}_DrawInstanceWithEffects(e,t,s,a,i){const r=t.GetInstanceEffectList().GetEffectChain();return r.Render(s,a,{contentObject:e,blendMode:t.GetBlendMode(),devicePixelRatio:this._runtime.GetEffectDevicePixelRatioParam(),time:e.GetInstanceGameTime(),layerScale:this._runtime.GetEffectLayerScaleParam()*this.GetNormalScale(),layerAngle:this.GetAngle(),layoutRect:t.GetBoundingBox(),drawSurfaceRect:r.CanSkipCalculatingDrawSurfaceRect()?null:this._InstanceBoxToDrawSurface(t),drawContentHook:i&&i.drawContentHook,compositOffX:i&&i.compositOffX,compositOffY:i&&i.compositOffY,compositRtWidth:i&&i.compositRtWidth,compositRtHeight:i&&i.compositRtHeight,updateOwnProjection:i&&i.updateOwnProjection}),s.SetBaseZ(this.GetZElevation()),r.DidChangeTransform()}_DrawLayerOwnTextureToRenderTarget(e,t,s,a){const i=this._effectList.GetActiveEffectTypes(),r=this._runtime;0===i.length?(e.SetRenderTarget(s),e.SetTextureFillMode(),a&&0===this._blendMode&&this.HasDefaultColor()?e.CopyRenderTarget(t):(e.SetBlendMode(this._blendMode),e.SetColor(this._premultipliedColor),e.DrawRenderTarget(t)),e.InvalidateRenderTarget(t),r.ReleaseAdditionalRenderTarget(t)):this.GetEffectChain().Render(e,s,{contentObject:this,blendMode:this.GetBlendMode(),devicePixelRatio:r.GetEffectDevicePixelRatioParam(),layerScale:r.GetEffectLayerScaleParam()*this.GetNormalScale(),layerAngle:this.GetAngle(),layoutRect:this.GetViewport(),drawSurfaceRect:null,invalidateRenderTargets:!0})}GetOwnScale(){return this._scale}SetOwnScale(e){this._scale!==e&&(this._scale=e,this._layout.BoundScrolling(),this._SetMVMatrixChanged(),this._runtime.UpdateRender())}GetRenderScale(){return this.GetNormalScale()*this._runtime.GetRenderScale()}GetDisplayScale(){return this.GetNormalScale()*this._runtime.GetDisplayScale()}GetNormalScale(){return(this._scale*this._layout.GetScale()-1)*this._scaleRate+1}_MaybeUpdateViewport(){if(!this._isViewportChanged)return;this._isViewportChanged=!1;const e=this._runtime.GetParallaxXOrigin(),t=this._runtime.GetParallaxYOrigin(),s=(this.GetScrollX()-e)*this._parallaxX+e,a=(this.GetScrollY()-t)*this._parallaxY+t,i=this.GetNormalScale(),r=this._runtime.GetViewportWidth()/i,n=this._runtime.GetViewportHeight()/i;let l=s-r/2,o=a-n/2;this._runtime.IsPixelRoundingEnabled()&&(l=Math.round(l),o=Math.round(o));const h=this._viewportZ0;h.set(l,o,l+r,o+n);const c=this.GetAngle();0!==c&&(tmpRect.copy(h),tmpRect.offset(-h.midX(),-h.midY()),tmpQuad.setFromRotatedRect(tmpRect,c),tmpQuad.getBoundingBox(tmpRect),tmpRect.offset(h.midX(),h.midY()),h.copy(tmpRect));const d=this._zElevation;this.GetViewportForZ(d,this._viewport),this.Has3DCamera()?this.CalculateViewport3D(d,this._viewport3D):this._viewport3D.copy(this._viewport)}CalculateViewport3D(e,t){const s=this._runtime.GetCanvasManager(),a=s.GetCssWidth(),i=s.GetCssHeight(),[r,n]=this.CanvasCssToLayer(0,0,e),[l,o]=this.CanvasCssToLayer(a,0,e),[h,c]=this.CanvasCssToLayer(a,i,e),[d,_]=this.CanvasCssToLayer(0,i,e);let u=Math.min(r,l,h,d),G=Math.min(n,o,c,_),f=Math.max(r,l,h,d),p=Math.max(n,o,c,_);isFinite(u)||(u=-1/0),isFinite(G)||(G=-1/0),isFinite(f)||(f=1/0),isFinite(p)||(p=1/0),t.set(u,G,f,p)}CanvasCssToLayer(e,t,s=0){return this._CanvasToLayer(e,t,s,this.GetDisplayScale())}DrawSurfaceToLayer(e,t,s=0){return this._CanvasToLayer(e,t,s,this.GetRenderScale()*this.GetDevicePixelRatio())}_CanvasToLayer(e,t,s,a){const i=this._runtime,r=i.GetRenderer(),n=this.GetNormalScale(),l=i.GetViewportWidth()/n,o=i.GetViewportHeight()/n,h=tempVec4;vec4.set(h,0,0,l,o),e/=a,t=h[3]-t/a;const c=this._GetProjectionMatrix(r),d=this._GetModelViewMatrix(r),_=tempVec3;return C3.Gfx.UnprojectScreenToWorldZ(e,t,s,d,c,h,_)?[_[0],_[1]]:[NaN,NaN]}CanvasCssToLayer_DefaultTransform(e,t){const s=this._scale,a=this._scaleRate,i=this._parallaxX,r=this._parallaxY,n=this._angle;this._scale=1,this._scaleRate=1,this._parallaxX=1,this._parallaxY=1,this._angle=0,this._SetMVMatrixChanged();const l=this.CanvasCssToLayer(e,t);return this._scale=s,this._scaleRate=a,this._parallaxX=i,this._parallaxY=r,this._angle=n,this._SetMVMatrixChanged(),l}LayerToCanvasCss(e,t,s=0){return this._LayerToCanvas(e,t,s,this.GetDisplayScale())}LayerToDrawSurface(e,t,s=0){return this._LayerToCanvas(e,t,s,this.GetRenderScale()*this.GetDevicePixelRatio())}_LayerToCanvas(e,t,s,a){const i=this._runtime,r=i.GetRenderer(),n=this.GetNormalScale(),l=i.GetViewportWidth()/n,o=i.GetViewportHeight()/n,h=tempVec4;vec4.set(h,0,0,l,o);const c=this._GetProjectionMatrix(r),d=this._GetModelViewMatrix(r),_=tempVec3;return C3.Gfx.Project(e,t,s,d,c,h,_)?[_[0]*a,(h[3]-_[1])*a]:[NaN,NaN]}_GetLayerToDrawSurfaceScale(e,t){return e*=this.GetRenderScale()*this.GetDevicePixelRatio(),0!==t&&(e*=this.Get2DScaleFactorToZ(t)),e}_InstanceBoxToDrawSurface(e){const t=e.GetBoundingBox(),s=e.GetTotalZElevation(),a=e.GetDepth(),i=s+a,r=t.getLeft(),n=t.getTop(),l=t.getRight(),o=t.getBottom();if(this.Has3DCamera()){if(this._IsPointBehindNearPlane(r,n,s)||this._IsPointBehindNearPlane(l,n,s)||this._IsPointBehindNearPlane(l,o,s)||this._IsPointBehindNearPlane(r,o,s))return null;if(a>0&&(this._IsPointBehindNearPlane(r,n,i)||this._IsPointBehindNearPlane(l,n,i)||this._IsPointBehindNearPlane(l,o,i)||this._IsPointBehindNearPlane(r,o,i)))return null}else if(i>=this.Get2DCameraZ())return null;let[h,c]=this.LayerToDrawSurface(r,n,s),[d,_]=this.LayerToDrawSurface(l,o,s);if(0!==this.GetAngle()||a>0||this.Has3DCamera()){const[e,t]=this.LayerToDrawSurface(l,n,s),[u,G]=this.LayerToDrawSurface(r,o,s);if(a>0){const[s,a]=this.LayerToDrawSurface(r,n,i),[f,p]=this.LayerToDrawSurface(l,n,i),[I,m]=this.LayerToDrawSurface(l,o,i),[C,y]=this.LayerToDrawSurface(r,o,i);let S=Math.min(h,d,e,u,s,f,I,C);d=Math.max(h,d,e,u,s,f,I,C),h=S,S=Math.min(c,_,t,G,a,p,m,y),_=Math.max(c,_,t,G,a,p,m,y),c=S}else{let s=Math.min(h,d,e,u);d=Math.max(h,d,e,u),h=s,s=Math.min(c,_,t,G),_=Math.max(c,_,t,G),c=s}}return tmpRect.set(h,c,d,_),tmpRect}_GetViewFrustum(){return this._isViewFrustumChanged&&(this._UpdateViewFrustum(),this._isViewFrustumChanged=!1),this._viewFrustum}_UpdateViewFrustum(){const e=this._runtime.GetRenderer(),t=this._GetProjectionMatrix(e),s=this._GetModelViewMatrix(e);this._viewFrustum.CalculatePlanes(s,t)}_IsPointBehindNearPlane(e,t,s){return this._GetViewFrustum().IsBehindNearPlane(e,t,s)}_SaveToJson(){return{"d":this.IsDynamic(),"s":this.GetOwnScale(),"a":this.GetOwnAngle(),"v":this._IsVisibleFlagSet(),"i":this.IsInteractive(),"html":this.IsHTMLElementsLayer(),"bc":this._backgroundColor.toJSON(),"t":this.IsTransparent(),"sx":this._scrollX,"sy":this._scrollY,"hosp":this._hasOwnScrollPosition,"px":this.GetParallaxX(),"py":this.GetParallaxY(),"c":this._color.toJSON(),"sr":this.GetScaleRate(),"fx":this._effectList.SaveToJson(),"cg":this._createdGlobalUids}}_LoadFromJson(e){this._isDynamic=!!e["d"],this._scale=e["s"],this._angle=e["a"],this._isVisible=!!e["v"],this._isInteractive=!e.hasOwnProperty("i")||e["i"],this._isHTMLElementsLayer=!!e["html"],this._backgroundColor.setFromJSON(e["bc"]),this._isTransparent=!!e["t"],e.hasOwnProperty("sx")&&(this._scrollX=e["sx"]),e.hasOwnProperty("sy")&&(this._scrollY=e["sy"]),e.hasOwnProperty("hosp")&&(this._hasOwnScrollPosition=!!e["hosp"]),this._parallaxX=e["px"],this._parallaxY=e["py"],this._color.setFromJSON(e["c"]),this._UpdatePremultipliedColor(),this._scaleRate=e["sr"],C3.shallowAssignArray(this._createdGlobalUids,e["cg"]),C3.shallowAssignArray(this._initialInstances,this._startupInitialInstances);const t=new Set(this._createdGlobalUids);let s=0;for(let e=0,a=this._initialInstances.length;e<a;++e)t.has(this._initialInstances[e][2])||(this._initialInstances[s]=this._initialInstances[e],++s);C3.truncateArray(this._initialInstances,s),this._effectList.LoadFromJson(e["fx"]),this._needsRebuildEffectChainSteps=!0}_LoadFromJsonAfterInstances(){this._SortInstancesByLastCachedZIndex(!1),this.SetZIndicesChanged(),this._SetMVMatrixChanged(),this._SetProjectionMatrixChanged()}GetILayer(){return this._iLayer}SortAndAddInstancesByZIndex(e,t=!1,s=!1){if(this._instances.includes(e))return t&&this._instances.sort(((e,t)=>(e.GetWorldInfo().GetSceneGraphZIndex()??0)-(t.GetWorldInfo().GetSceneGraphZIndex()??0))),void(s&&this._instances.forEach(((e,t)=>e.GetWorldInfo()._SetZIndex(t))));if(e.HasChildren()){const t=[...e.allChildren()];t.push(e),t.sort(((e,t)=>(e.GetWorldInfo().GetSceneGraphZIndex()??0)-(t.GetWorldInfo().GetSceneGraphZIndex()??0)));for(const e of t)if(e.IsInContainer())for(const s of e.siblings()){if(t.includes(s))continue;const e=[...s.allChildren()];e.push(s),e.sort(((e,t)=>(e.GetWorldInfo().GetSceneGraphZIndex()??0)-(t.GetWorldInfo().GetSceneGraphZIndex()??0))),e&&e.length&&t.splice(t.length,0,...e)}for(const e of t)e.GetPlugin().IsWorldType()&&this._AddInstance(e,!0);s&&this._instances.forEach(((e,t)=>e.GetWorldInfo()._SetZIndex(t)))}else{if(e.GetPlugin().IsWorldType()&&this._AddInstance(e,!0),!e.IsInContainer())return void(s&&this._instances.forEach(((e,t)=>e.GetWorldInfo()._SetZIndex(t))));for(const t of e.siblings()){const e=[...t.allChildren()];if(e.push(t),e.sort(((e,t)=>(e.GetWorldInfo().GetSceneGraphZIndex()??0)-(t.GetWorldInfo().GetSceneGraphZIndex()??0))),e&&e.length)for(const t of e)t.GetPlugin().IsWorldType()&&this._AddInstance(t,!0)}s&&this._instances.forEach(((e,t)=>e.GetWorldInfo()._SetZIndex(t)))}}};
}

// layouts/layout.js
{
const C3=self.C3,C3Debugger=self.C3Debugger,assert=self.assert,tempDestRect=C3.New(C3.Rect),tempSrcRect=C3.New(C3.Rect),tempLayoutRect=C3.New(C3.Rect),tempColor=C3.New(C3.Color),glMatrix=self.glMatrix,vec3=glMatrix.vec3,tempRender3dList=[],tempInstanceList1=[],tempInstanceList2=[],tempInstanceList3=[];function vec3EqualsXYZ(e,t,s,r){return e[0]===Math.fround(t)&&e[1]===Math.fround(s)&&e[2]===Math.fround(r)}let lastLayerPreparedForDrawing=null;function MaybePrepareLayerDraw(e,t){lastLayerPreparedForDrawing!==e&&(e.PrepareForDraw(t),lastLayerPreparedForDrawing=e)}C3.Layout=class extends C3.DefendedBase{constructor(e,t,s){super(),this._layoutManager=e,this._runtime=e.GetRuntime(),this._name=s[0],this._originalWidth=s[1],this._originalHeight=s[2],this._width=s[1],this._height=s[2],this._isUnboundedScrolling=!!s[3],this._isOrthographicProjection=!!s[4],this._vanishingPointX=s[5],this._vanishingPointY=s[6],this._eventSheetName=s[7],this._eventSheet=null,this._sid=s[8],this._index=t,this._scrollX=0,this._scrollY=0,this._scale=1,this._angle=0,this._initialObjectClasses=new Set,this._textureLoadedTypes=new Set,this._textureLoadPendingPromises=new Set,this._createdInstances=[],this._createdPersistedInstances=[],this._createdPersistedInstancesToDataMap=new Map,this._createdPersistedIndexToInstanceMap=new Map,this._initialNonWorld=[],this._is3dCameraEnabled=!1,this._cam3dposition=vec3.create(),this._cam3dlook=vec3.create(),this._cam3dup=vec3.create(),this._rootLayers=[],this._allLayersFlat=[],this._layersByName=new Map,this._layersBySid=new Map,this._pendingSetHTMLLayerCount=-1;const r=this._runtime.GetCanvasManager();this._effectList=C3.New(C3.EffectList,this,s[11]),this._effectChain=C3.New(C3.Gfx.EffectChain,r.GetEffectChainManager(),{drawContent:(e,t)=>{const s=t.GetContentObject().GetRenderTarget();e.ResetColor(),e.DrawRenderTarget(s),e.InvalidateRenderTarget(s),r.ReleaseAdditionalRenderTarget(s)},getShaderParameters:e=>this.GetEffectList()._GetEffectChainShaderParametersForIndex(e)}),this._needsRebuildEffectChainSteps=!0,this._wasFullScreenQualityLow=!1,this._curRenderTarget=null,this._persistData={},this._persistedIntances=new Map,this._isFirstVisit=!0,this._iLayout=new self.ILayout(this),this._userScriptDispatcher=C3.New(C3.Event.Dispatcher);for(const e of s[9])this._rootLayers.push(C3.Layer.CreateFromExportData(this,null,e));this._ReindexLayers();for(const e of this.allLayers())e._InitInitialInstances();for(const e of s[10]){const t=this._runtime.GetObjectClassByIndex(e[1]);if(!t)throw new Error("missing nonworld object class");t.GetDefaultInstanceData()||t.SetDefaultInstanceData(e),this._initialNonWorld.push(e),this._AddInitialObjectClass(t)}}Release(){for(const e of this._allLayersFlat)e.Release();C3.clearArray(this._allLayersFlat),this._textureLoadPendingPromises.clear(),this._eventSheet=null,this._layoutManager=null,this._runtime=null}GetRuntime(){return this._runtime}GetName(){return this._name}GetSID(){return this._sid}GetIndex(){return this._index}GetEffectList(){return this._effectList}GetEffectChain(){return this._MaybeRebuildEffectChainSteps(),this._effectChain}_MaybeRebuildEffectChainSteps(){const e="low"===this._runtime.GetCanvasManager().GetCurrentFullscreenScalingQuality();if(!this._needsRebuildEffectChainSteps&&this._wasFullScreenQualityLow===e&&!this._effectChain.NeedsRebuild())return;const t=this.GetEffectList().GetActiveEffectTypes();this._effectChain.BuildSteps(t.map((e=>e.GetShaderProgram())),{indexMap:t.map((e=>e.GetIndex())),forcePostDraw:e,useFullSurface:!0}),this._needsRebuildEffectChainSteps=!1,this._wasFullScreenQualityLow=e}UpdateActiveEffects(){this.GetEffectList().UpdateActiveEffects(),this._needsRebuildEffectChainSteps=!0}GetMinLayerScale(){let e=this._allLayersFlat[0].GetNormalScale();for(let t=1,s=this._allLayersFlat.length;t<s;++t){const s=this._allLayersFlat[t];0===s.GetParallaxX()&&0===s.GetParallaxY()||(e=Math.min(e,s.GetNormalScale()))}return e}_GetScrollBoundMarginHorizontal(){return.5*this._runtime.GetViewportWidth()/this.GetMinLayerScale()}_GetScrollBoundMarginVertical(){return.5*this._runtime.GetViewportHeight()/this.GetMinLayerScale()}GetScrollLeftBound(){return this.IsUnboundedScrolling()?-1/0:this._GetScrollBoundMarginHorizontal()}GetScrollRightBound(){return this.IsUnboundedScrolling()?1/0:this.GetWidth()-this._GetScrollBoundMarginHorizontal()}GetScrollTopBound(){return this.IsUnboundedScrolling()?-1/0:this._GetScrollBoundMarginVertical()}GetScrollBottomBound(){return this.IsUnboundedScrolling()?1/0:this.GetHeight()-this._GetScrollBoundMarginVertical()}SetScrollX(e){const t=this.GetScrollLeftBound(),s=this.GetScrollRightBound();e>s&&(e=s),e<t&&(e=t),this._scrollX!==e&&(this._scrollX=e,this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}GetScrollX(){return this._scrollX}SetScrollY(e){const t=this.GetScrollTopBound(),s=this.GetScrollBottomBound();e>s&&(e=s),e<t&&(e=t),this._scrollY!==e&&(this._scrollY=e,this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}GetScrollY(){return this._scrollY}IsUnboundedScrolling(){return this._isUnboundedScrolling}BoundScrolling(){this.SetScrollX(this.GetScrollX()),this.SetScrollY(this.GetScrollY());for(const e of this._allLayersFlat)e.IsOwnScrollPositionEnabled()&&(e.SetScrollX(e.GetScrollX()),e.SetScrollY(e.GetScrollY()))}SetVanishingPointXY(e,t){this._vanishingPointX===e&&this._vanishingPointY===t||(this._vanishingPointX=e,this._vanishingPointY=t,this.IsPerspectiveProjection()&&(this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged(),this._runtime.UpdateRender()))}GetVanishingPointX(){return this.IsOrthographicProjection()?.5:this._vanishingPointX}GetVanishingPointY(){return this.IsOrthographicProjection()?.5:this._vanishingPointY}HasVanishingPointOutsideViewport(){const e=this.GetVanishingPointX(),t=this.GetVanishingPointY();return e<0||e>1||t<0||t>1}SetPerspectiveProjection(){this._isOrthographicProjection&&(this._isOrthographicProjection=!1,this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}SetOrthographicProjection(){this._isOrthographicProjection||(this._isOrthographicProjection=!0,this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}IsOrthographicProjection(){return this._isOrthographicProjection}IsPerspectiveProjection(){return!this.IsOrthographicProjection()}Set3DCameraEnabled(e){e=!!e,this._is3dCameraEnabled!==e&&(this._is3dCameraEnabled=e,this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}Is3DCameraEnabled(){return this._is3dCameraEnabled}Set3DCameraOrientation(e,t,s,r,a,n,i,o,l){vec3EqualsXYZ(this._cam3dposition,e,t,s)&&vec3EqualsXYZ(this._cam3dlook,r,a,n)&&vec3EqualsXYZ(this._cam3dup,i,o,l)||(vec3.set(this._cam3dposition,e,t,s),vec3.set(this._cam3dlook,r,a,n),vec3.set(this._cam3dup,i,o,l),this.Set3DCameraChanged())}Set3DCameraChanged(){this._SetAllLayersMVChanged(),this._runtime.UpdateRender()}Get3DCameraPosition(){return this._cam3dposition}Get3DCameraLookAt(){return this._cam3dlook}Get3DCameraUpVector(){return this._cam3dup}GetScale(){return this._scale}SetScale(e){this._scale!==e&&(this._scale=e,this._SetAllLayersMVChanged(),this.BoundScrolling(),this._runtime.UpdateRender())}SetAngle(e){e=C3.clampAngle(e),this._angle!==e&&(this._angle=e,this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}GetAngle(){return this._angle}GetWidth(){return this._width}SetWidth(e){!isFinite(e)||e<1||(this._width=e)}GetHeight(){return this._height}SetHeight(e){!isFinite(e)||e<1||(this._height=e)}GetEventSheet(){return this._eventSheet}_GetRootLayers(){return this._rootLayers}*allLayers(){for(const e of this._rootLayers)yield*e.selfAndAllSubLayers()}GetLayers(){return this._allLayersFlat}GetLayerCount(){return this._allLayersFlat.length}GetLayer(e){return"number"==typeof e?this.GetLayerByIndex(e):this.GetLayerByName(e.toString())}GetLayerByIndex(e){return e=C3.clamp(Math.floor(e),0,this._allLayersFlat.length-1),this._allLayersFlat[e]}GetLayerByName(e){return this._layersByName.get(e.toLowerCase())||null}HasLayerByName(e){return!!this.GetLayerByName(e)}GetLayerBySID(e){return this._layersBySid.get(e)||null}_SetAllLayersProjectionChanged(){for(const e of this._allLayersFlat)e._SetProjectionMatrixChanged()}_SetAllLayersMVChanged(){for(const e of this._allLayersFlat)e._SetMVMatrixChanged()}AddLayer(e,t,s){if(this.HasLayerByName(e))throw new Error(`layer name '${e}' already in use`);if(!t&&s<2)throw new Error("invalid insert position");const r=s>=2?t:t.GetParentLayer(),a=C3.New(C3.Layer,this,r,{name:e,sid:Math.floor(1e15*Math.random()),isDynamic:!0});this._InsertLayer(a,t,s),this.GetRuntime().UpdateRender(),this._ReindexAndUpdateAllLayers()}MoveLayer(e,t,s){if(!t&&s<2)throw new Error("invalid insert position");e===t&&s<2||(this._RemoveLayer(e),this._InsertLayer(e,t,s),this.GetRuntime().UpdateRender(),this._ReindexAndUpdateAllLayers())}RemoveLayer(e){if(this._RemoveLayer(e)){const t=this._runtime.GetEventSheetManager();t.BlockFlushingInstances(!0),e.Release(),t.BlockFlushingInstances(!1),this.GetRuntime().UpdateRender(),this._ReindexAndUpdateAllLayers()}}RemoveAllDynamicLayers(){const e=new Set;for(const t of this.allLayers())t.IsDynamic()&&!t.HasAnyDynamicParentLayer()&&e.add(t);if(0===e.size)return;const t=this._runtime.GetEventSheetManager();t.BlockFlushingInstances(!0);for(const t of e)this._RemoveLayer(t),t.Release();t.BlockFlushingInstances(!1),this.GetRuntime().UpdateRender(),this._ReindexAndUpdateAllLayers()}_InsertLayer(e,t,s){if(s>=2)if(t){if(t===e||t.HasParentLayer(e))throw new Error(`cannot move layer '${e.GetName()}' to sub-layer of itself`);t._AddSubLayer(e,2===s),e._SetParentLayer(t)}else 2===s?this._rootLayers.push(e):this._rootLayers.unshift(e),e._SetParentLayer(null);else{const r=t.GetParentLayer();if(r){if(t.HasParentLayer(e))throw new Error(`cannot move layer '${e.GetName()}' to sub-layer of itself`);r._InsertSubLayer(e,t,0===s),e._SetParentLayer(r)}else{let r=this._rootLayers.indexOf(t);if(-1===r)throw new Error("cannot find layer to insert by");0===s&&++r,this._rootLayers.splice(r,0,e),e._SetParentLayer(null)}}}_RemoveLayer(e){const t=e.GetParentLayer();if(t)return t._RemoveSubLayer(e),!0;if(this._rootLayers.length>1){const t=this._rootLayers.indexOf(e);if(-1===t)throw new Error("cannot find layer to remove");return this._rootLayers.splice(t,1),!0}return!1}_ReindexLayers(){this._allLayersFlat=[...this.allLayers()],this._layersByName.clear(),this._layersBySid.clear();for(let e=0,t=this._allLayersFlat.length;e<t;++e){const t=this._allLayersFlat[e];t._SetIndex(e),this._layersByName.set(t.GetName().toLowerCase(),t),this._layersBySid.set(t.GetSID(),t)}}_ReindexHTMLLayers(){let e=0;for(const t of this._rootLayers){for(const s of t.selfAndAllSubLayers())s._SetHTMLIndex(e);t.IsHTMLElementsLayer()&&e++}}GetHTMLLayerCount(){return this._rootLayers.at(-1).GetHTMLIndex()+1}async _ReindexAndUpdateAllLayers(){this._ReindexLayers(),this._ReindexHTMLLayers(),this._pendingSetHTMLLayerCount=this.GetHTMLLayerCount()}_GetPendingSetHTMLLayerCount(){return this._pendingSetHTMLLayerCount}_ResetPendingHTMLLayerCount(){this._pendingSetHTMLLayerCount=-1}GetRootLayersForHTMLLayer(e){const t=[];for(const s of this._rootLayers){const r=s.GetHTMLIndex();if(r===e)t.push(s);else if(r>e)break}return t}SaveTransform(){return{"scrollX":this.GetScrollX(),"scrollY":this.GetScrollY(),"scale":this.GetScale(),"angle":this.GetAngle(),"vpX":this.GetVanishingPointX(),"vpY":this.GetVanishingPointY()}}RestoreTransform(e){this.SetScrollX(e["scrollX"]),this.SetScrollY(e["scrollY"]),this.SetScale(e["scale"]),this.SetAngle(e["angle"]),this.SetVanishingPointXY(e["vpX"],e["vpY"])}GetLayoutBackgroundColor(){let e=this._rootLayers.filter((e=>e.ShouldDraw()))[0];for(;e;){if(!e.IsTransparent())return tempColor.copyRgb(e.GetBackgroundColor()),tempColor.setA(1),tempColor;if(e.UsesOwnTexture())return tempColor.setRgba(0,0,0,0),tempColor;e=e.GetSubLayers().filter((e=>e.ShouldDraw()))[0]}return tempColor.setRgba(0,0,0,0),tempColor}IsFirstVisit(){return this._isFirstVisit}_GetInitialObjectClasses(){return[...this._initialObjectClasses]}_AddInitialObjectClass(e){if(e.IsInContainer())for(const t of e.GetContainer().GetObjectTypes())this._initialObjectClasses.add(t);else this._initialObjectClasses.add(e)}_GetTextureLoadedObjectTypes(){return[...this._textureLoadedTypes]}_Load(e,t){if(e===this||!t)return Promise.resolve();e&&(C3.CopySet(this._textureLoadedTypes,e._textureLoadedTypes),e._textureLoadedTypes.clear());const s=[];for(const e of this._initialObjectClasses)this._textureLoadedTypes.has(e)||(s.push(e.LoadTextures(t)),this._textureLoadedTypes.add(e));return Promise.all(s)}async MaybeLoadTexturesFor(e){if(e.IsFamily())throw new Error("cannot load textures for family");const t=this._runtime.GetRenderer();if(!t||t.IsContextLost()||this._textureLoadedTypes.has(e))return;this._textureLoadedTypes.add(e);const s=e.LoadTextures(t);this._AddPendingTextureLoadPromise(s),await s,e.OnDynamicTextureLoadComplete(),this._runtime.UpdateRender()}_AddPendingTextureLoadPromise(e){this._textureLoadPendingPromises.add(e),e.then((()=>this._textureLoadPendingPromises.delete(e))).catch((()=>this._textureLoadPendingPromises.delete(e)))}WaitForPendingTextureLoadsToComplete(){return Promise.all([...this._textureLoadPendingPromises])}MaybeUnloadTexturesFor(e){if(e.IsFamily()||e.GetInstanceCount()>0)throw new Error("cannot unload textures");const t=this._runtime.GetRenderer();t&&this._textureLoadedTypes.has(e)&&(this._textureLoadedTypes.delete(e),e.ReleaseTextures(t))}_Unload(e,t){if(e!==this&&t)for(const t of this._textureLoadedTypes)t.IsGlobal()||e._initialObjectClasses.has(t)||(t.ReleaseTextures(),this._textureLoadedTypes.delete(t))}_OnRendererContextLost(){this._textureLoadedTypes.clear()}async _StartRunning(e){const t=this._runtime,s=this._layoutManager,r=t.GetEventSheetManager();this._eventSheetName&&(this._eventSheet=r.GetEventSheetByName(this._eventSheetName),this._eventSheet._UpdateDeepIncludes()),s._SetMainRunningLayout(this),this._width=this._originalWidth,this._height=this._originalHeight,this._scrollX=t.GetOriginalViewportWidth()/2,this._scrollY=t.GetOriginalViewportHeight()/2,this.BoundScrolling(),this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged(),this._ReindexHTMLLayers(),await this._runtime.GetCanvasManager().SetHTMLLayerCount(this.GetHTMLLayerCount(),!0),this._MoveGlobalObjectsToThisLayout(e),this._runtime.SetUsingCreatePromises(!0),this._CreateInitialInstances(),this._isFirstVisit||this._CreatePersistedInstances(),this._CreateAndLinkContainerInstances(this._createdInstances),this._CreateAndLinkContainerInstances(this._createdPersistedInstances),this._CreateInitialNonWorldInstances(),s.ClearPendingChangeLayout(),t.FlushPendingInstances(),this._runtime.SetUsingCreatePromises(!1);const a=this._runtime.GetCreatePromises();if(await Promise.all(a),C3.clearArray(a),!t.IsLoadingState()){for(const e of this._createdInstances)e.SetupInitialSceneGraphConnections();for(const e of this._createdPersistedInstances)e.SetupPersistedSceneGraphConnections(this._createdPersistedInstancesToDataMap,this._createdPersistedIndexToInstanceMap);for(const[e,t]of Object.entries(this._persistData)){const s=this._runtime.GetObjectClassBySID(parseInt(e,10));s&&!s.IsFamily()&&s.HasPersistBehavior()&&C3.clearArray(t)}for(const e of this._createdInstances)e._TriggerOnCreated();for(const e of this._createdPersistedInstances)e._TriggerOnCreated();for(const e of this._createdInstances)e.HasParent()||e._OnHierarchyReady();for(const e of this._createdPersistedInstances)e.HasParent()||e._OnHierarchyReady()}C3.clearArray(this._createdInstances),C3.clearArray(this._createdPersistedInstances),this._createdPersistedInstancesToDataMap.clear(),this._createdPersistedIndexToInstanceMap.clear(),await Promise.all([...this._initialObjectClasses].map((e=>e.PreloadTexturesWithInstances(this._runtime.GetRenderer())))),e&&(t.Dispatcher().dispatchEvent(new C3.Event("beforefirstlayoutstart")),await t.DispatchUserScriptEventAsyncWait(new C3.Event("beforeprojectstart"))),await this.DispatchRuntimeUserScriptEventAsyncWait(new C3.Event("beforeanylayoutstart")),t.Dispatcher().dispatchEvent(new C3.Event("beforelayoutstart")),await this.DispatchUserScriptEventAsyncWait(new C3.Event("beforelayoutstart")),t.IsLoadingState()||await t.TriggerAsync(C3.Plugins.System.Cnds.OnLayoutStart,null,null),t.Dispatcher().dispatchEvent(new C3.Event("afterlayoutstart")),await this.DispatchUserScriptEventAsyncWait(new C3.Event("afterlayoutstart")),await this.DispatchRuntimeUserScriptEventAsyncWait(new C3.Event("afteranylayoutstart")),e&&(t.Dispatcher().dispatchEvent(new C3.Event("afterfirstlayoutstart")),await t.DispatchUserScriptEventAsyncWait(new C3.Event("afterprojectstart"))),r._RunQueuedTriggers(s),await this.WaitForPendingTextureLoadsToComplete(),this._isFirstVisit=!1}_MoveGlobalObjectsToThisLayout(e){for(const e of this._runtime.GetAllObjectClasses())if(!e.IsFamily()&&e.IsWorldType())for(const t of e.GetInstances()){const e=t.GetWorldInfo(),s=e.GetLayer(),r=C3.clamp(s.GetIndex(),0,this._allLayersFlat.length-1),a=this._allLayersFlat[r];e._SetLayer(a,!0),a._MaybeAddInstance(t)}if(!e)for(const e of this._allLayersFlat)e._SortInstancesByLastCachedZIndex(!1)}_CreateInitialInstances(){for(const e of this._allLayersFlat)e.CreateInitialInstances(this._createdInstances),e._Start()}_CreatePersistedInstances(){let e=!1;for(const[t,s]of Object.entries(this._persistData)){const r=this._runtime.GetObjectClassBySID(parseInt(t,10));if(r&&!r.IsFamily()&&r.HasPersistBehavior())for(const t of s){let s=null;if(r.IsWorldType()&&(s=t.hasOwnProperty("instJson")?this.GetLayerBySID(t["instJson"]["w"]["l"]):this.GetLayerBySID(t["w"]["l"]),!s))continue;const a=this._runtime.CreateInstanceFromData(r,s,!1,0,0,!0);t.hasOwnProperty("instJson")?a.LoadFromJson(t["instJson"]):a.LoadFromJson(t),e=!0,this._createdPersistedInstances.push(a),t.hasOwnProperty("instJson")&&(this._createdPersistedInstancesToDataMap.set(a,t),this._createdPersistedIndexToInstanceMap.set(t["index"],a))}}for(const e of this._allLayersFlat)e._SortInstancesByLastCachedZIndex(!0),e.SetZIndicesChanged();e&&(this._runtime.FlushPendingInstances(),this._runtime._RefreshUidMap())}_CreateAndLinkContainerInstances(e){for(const t of e){if(!t.IsInContainer())continue;const s=t.GetWorldInfo(),r=t.GetIID();for(const a of t.GetObjectClass().GetContainer().objectTypes()){if(a===t.GetObjectClass())continue;const n=a.GetInstances();if(n.length>r)t._AddSibling(n[r]);else{let r;r=s?this._runtime.CreateInstanceFromData(a,s.GetLayer(),!0,s.GetX(),s.GetY(),!0):this._runtime.CreateInstanceFromData(a,null,!0,0,0,!0),this._runtime.FlushPendingInstances(),a._UpdateIIDs(),t._AddSibling(r),e.push(r)}}}}_CreateInitialNonWorldInstances(){for(const e of this._initialNonWorld){this._runtime.GetObjectClassByIndex(e[1]).IsInContainer()||this._runtime.CreateInstanceFromData(e,null,!0)}}_CreateGlobalNonWorlds(){const e=[],t=this._initialNonWorld;let s=0;for(let r=0,a=t.length;r<a;++r){const a=t[r],n=this._runtime.GetObjectClassByIndex(a[1]);n.IsGlobal()?n.IsInContainer()&&n.GetContainer().HasAnyWorldType()||e.push(this._runtime.CreateInstanceFromData(a,null,!0)):(t[s]=a,++s)}C3.truncateArray(t,s),this._runtime.FlushPendingInstances(),this._CreateAndLinkContainerInstances(e)}RecreateInitialObjects(e,t,s,r,a,n,i){if(s)return s.RecreateInitialObjects(e,t,a,n,r,i);{const s=[];for(const o of this._allLayersFlat)s.push(o.RecreateInitialObjects(e,t,a,n,r,i));return s.flat()}}async _StopRunning(){const e=this._layoutManager;this._runtime.IsLoadingState()||(await this.DispatchRuntimeUserScriptEventAsyncWait(new C3.Event("beforeanylayoutend")),await this.DispatchUserScriptEventAsyncWait(new C3.Event("beforelayoutend")),await this._runtime.TriggerAsync(C3.Plugins.System.Cnds.OnLayoutEnd,null,null),await this.DispatchUserScriptEventAsyncWait(new C3.Event("afterlayoutend")),await this.DispatchRuntimeUserScriptEventAsyncWait(new C3.Event("afteranylayoutend"))),e.SetIsEndingLayout(!0),this._runtime.GetEventSheetManager().ClearAllScheduledWaits(),this._isFirstVisit||this._SavePersistData();for(const e of this._allLayersFlat)e._End();for(const e of this._runtime.GetAllObjectClasses())if(!(e.IsGlobal()||e.IsWorldType()||e.GetPlugin().IsSingleGlobal()||e.IsFamily())){for(const t of e.GetInstances())this._runtime.DestroyInstance(t);this._runtime.FlushPendingInstances()}e.SetIsEndingLayout(!1),e.GetMainRunningLayout()===this&&e._SetMainRunningLayout(null)}_SaveInstanceToPersist(e,t){const s=e.GetObjectClass().GetSID().toString();this._persistData.hasOwnProperty(s)||(this._persistData[s]=[]);const r=this._persistData[s],a={"index":t,"instJson":e.SaveToJson(),"sceneGraphJson":{"children":[]}};r.push(a),this._persistedIntances.set(e,a)}_SaveSceneGraphInfoToPersist(e){const t=this._persistedIntances.get(e);for(const s of e.GetChildren()){const e=this._persistedIntances.get(s);e&&t["sceneGraphJson"]["children"].push({"index":e["index"],"flags":C3.SceneGraphInfo._GetFlagsNumber(s.GetWorldInfo())})}}_SavePersistData(){this._persistedIntances.clear();let e=0;for(const t of this._allLayersFlat){t._UpdateZIndices();for(const s of t._GetInstances()){const t=s.GetObjectClass();!t.IsGlobal()&&t.HasPersistBehavior()&&(this._SaveInstanceToPersist(s,e),e++)}}for(const e of this._allLayersFlat)for(const t of e._GetInstances()){const e=t.GetObjectClass();!e.IsGlobal()&&e.HasPersistBehavior()&&this._SaveSceneGraphInfoToPersist(t)}this._persistedIntances.clear()}ResetPersistData(){this._persistData={},this._isFirstVisit=!0}GetRenderTarget(){return this._curRenderTarget}UsesOwnTexture(){const e=this._runtime,t=e.GetRenderer().IsWebGL();return"low"===e.GetCanvasManager().GetCurrentFullscreenScalingQuality()||t&&e.UsesAnyBackgroundBlending()||this._effectList.HasAnyActiveEffect()||t&&e.Uses3DFeatures()}_MaybeStartDrawToOwnTexture(e){const t=this._runtime.GetCanvasManager();if(this.UsesOwnTexture()){e.SetRenderTarget(null),e.ClearRgba(0,0,0,0);const s={sampling:this._runtime.GetSampling(),isSampled:e.IsWebGPU()||this._runtime.UsesAnyBackgroundBlending()||this._effectList.HasAnyActiveEffect(),canReadPixels:!!e.IsWebGPU()&&this._runtime.UsesAnyBackgroundBlending()};"low"===t.GetCurrentFullscreenScalingQuality()&&(s.width=t.GetDrawWidth(),s.height=t.GetDrawHeight()),this._curRenderTarget=this._runtime.GetAdditionalRenderTarget(s)}else this._curRenderTarget=null}_MaybeCopyOwnTextureToBackbuffer(e){this._runtime._NeedsHTMLLayerCompositing(e)&&(e.SetDepthEnabled(!1),e.SetRenderTarget(null),e.SetTextureFillMode(),e.CopyRenderTarget(this._curRenderTarget))}_MaybeEndDrawToOwnTexture(e){this.UsesOwnTexture()&&(e.SetDepthEnabled(!1),this._DrawLayoutOwnTextureToRenderTarget(e,this._curRenderTarget))}DrawMain(e){e.SetRenderTarget(this._curRenderTarget),e.Clear(this.GetLayoutBackgroundColor()),this._runtime.Uses3DFeatures()&&e.ClearDepth();const t=this.GetRootLayersForHTMLLayer(0);this._DrawLayerList(e,this._curRenderTarget,t,!0),e.IsWebGPU()&&e.StartMeasuringRenderPassTime(0,1),this._MaybeEndDrawToOwnTexture(e),this._curRenderTarget=null}DrawForHTMLLayerIndex(e,t){let s=null;this._runtime._NeedsHTMLLayerCompositing(e)&&(s=this._curRenderTarget),e.SetRenderTarget(s),e.ClearRgba(0,0,0,0),this._runtime.Uses3DFeatures()&&e.ClearDepth();const r=this.GetRootLayersForHTMLLayer(t);this._DrawLayerList(e,s,r,!0),this._MaybeCopyOwnTextureToBackbuffer(e),e.EndBatch(),this._runtime.GetCanvasManager().BlitMainCanvasToHTMLLayerCanvas(t)}_DrawLayerList(e,t,s,r){const a=s.filter((e=>e.ShouldDraw()));for(let s=0,n=a.length;s<n;){const i=a[s];if(i.SelfAndAllSubLayersHave3DCamera()&&!i.SelfOrAnySubLayerUsesOwnTexture()){tempRender3dList.push(i);for(let e=s+1;e<n;++e){const t=a[e];if(!t.SelfAndAllSubLayersHave3DCamera()||t.SelfOrAnySubLayerUsesOwnTexture())break;tempRender3dList.push(a[e])}if(tempRender3dList.length>=2||1===tempRender3dList.length&&tempRender3dList[0].HasAnyVisibleSubLayer()){this._Draw3DLayers(e,t,tempRender3dList),s+=tempRender3dList.length,C3.clearArray(tempRender3dList);continue}C3.clearArray(tempRender3dList)}i.Draw(e,t,r&&0===s),++s}}_DrawLayoutOwnTextureToRenderTarget(e,t){const s=this._effectList.GetActiveEffectTypes(),r=this._runtime;0===s.length?(e.SetRenderTarget(null),e.SetTextureFillMode(),e.CopyRenderTarget(t),e.InvalidateRenderTarget(t),r.ReleaseAdditionalRenderTarget(t)):(tempLayoutRect.set(0,0,r.GetViewportWidth(),r.GetViewportHeight()),this.GetEffectChain().Render(e,null,{contentObject:this,blendMode:3,devicePixelRatio:this._runtime.GetEffectDevicePixelRatioParam(),layerScale:this._runtime.GetEffectLayerScaleParam()*this.GetScale(),layerAngle:this.GetAngle(),layoutRect:tempLayoutRect,drawSurfaceRect:null,invalidateRenderTargets:!0}))}_Draw3DLayers(e,t,s){s[0].IsTransparent()||(tempColor.copyRgb(s[0].GetBackgroundColor()),tempColor.setA(1),e.Clear(tempColor));this._runtime.GetCanvasManager();e.SetDepthEnabled(!0);const r=tempInstanceList1,a=tempInstanceList2,n=tempInstanceList3;for(const e of s)e._UpdateZIndices(),e._AppendAllInstancesIncludingSubLayersInDrawOrder(r);const i=s[0],o=i._MaybeStartWebGLProfiling(e);i._MaybeStartWebGPUProfiling(e);for(let s=0,i=r.length;s<i;){const o=r[s],l=o.GetWorldInfo(),h=l.GetLayer();if(!l.IsVisible()||!l.IsInViewport3D(h._GetViewFrustum())){++s;continue}(!o.RendersToOwnZPlane()||l.GetDepth()>0)&&n.push(o);const c=o.GetWorldInfo().GetTotalZElevation();a.push(o);let d=s+1;for(;d<i;++d){const e=r[d],t=e.GetWorldInfo();if(t.IsVisible()&&t.IsInViewport3D(t.GetLayer()._GetViewFrustum())){if(t.GetTotalZElevation()!==c)break;e.RendersToOwnZPlane()?(t.GetDepth()>0&&n.push(e),a.push(e)):n.push(e)}}if(1!==a.length||a[0].MustMitigateZFighting()){this._Draw3DLayersCoplanarInstances(e,t,a);for(let s=0,r=n.length;s<r;++s){const r=n[s],a=r.GetWorldInfo(),i=a.GetLayer();a._SetDrawNonBackFacesOnly(!0),MaybePrepareLayerDraw(i,e),i._DrawInstanceMaybeWithEffects(r,a,e,t),a._SetDrawNonBackFacesOnly(!1)}}else{MaybePrepareLayerDraw(h,e),h._DrawInstanceMaybeWithEffects(o,l,e,t);for(let s=0,r=n.length;s<r;++s){const r=n[s];if(r===o)continue;const a=r.GetWorldInfo(),i=a.GetLayer();MaybePrepareLayerDraw(i,e),i._DrawInstanceMaybeWithEffects(r,a,e,t)}}s=d,C3.clearArray(a),C3.clearArray(n)}o&&e.EndQuery(o),C3.clearArray(r),lastLayerPreparedForDrawing=null}_Draw3DLayersCoplanarInstances(e,t,s){e.CoplanarStartStencilPass();for(let t=0,r=s.length;t<r;++t){const r=s[t],a=r.GetWorldInfo(),n=a.GetLayer();a._SetDrawBackFaceOnly(!0),MaybePrepareLayerDraw(n,e),n._DrawInstance(r,a,e)}e.CoplanarStartColorPass();for(let r=0,a=s.length;r<a;++r){const a=s[r],n=a.GetWorldInfo(),i=n.GetLayer();MaybePrepareLayerDraw(i,e),i._DrawInstanceMaybeWithEffects(a,n,e,t),n._SetDrawBackFaceOnly(!1)}e.CoplanarRestoreStandardRendering()}_SaveToJson(){const e={"sx":this.GetScrollX(),"sy":this.GetScrollY(),"s":this.GetScale(),"a":this.GetAngle(),"w":this.GetWidth(),"h":this.GetHeight(),"ortho":this.IsOrthographicProjection(),"vpX":this.GetVanishingPointX(),"vpY":this.GetVanishingPointY(),"fv":this._isFirstVisit,"persist":this._persistData,"fx":this._effectList.SaveToJson(),"layers":{},"dynamicLayers":[]};for(const t of this._allLayersFlat)if(t.IsDynamic()){const s=t.GetParentLayer();e["dynamicLayers"].push({"sid":t.GetSID(),"name":t.GetName(),"parentSid":s?s.GetSID():null,"siblingIndex":t._GetSiblingIndex(),"data":t._SaveToJson()})}else e["layers"][t.GetSID().toString()]=t._SaveToJson();return e}_LoadFromJson(e){this._scrollX=e["sx"],this._scrollY=e["sy"],this._scale=e["s"],this._angle=e["a"],this._width=e["w"],this._height=e["h"],this._isOrthographicProjection=!!e["ortho"],e.hasOwnProperty("vpX")&&(this._vanishingPointX=e["vpX"]),e.hasOwnProperty("vpY")&&(this._vanishingPointY=e["vpY"]),this._isFirstVisit=!!e["fv"],this._persistData=e["persist"],this._effectList.LoadFromJson(e["fx"]),this._needsRebuildEffectChainSteps=!0;for(const[t,s]of Object.entries(e["layers"])){const e=parseInt(t,10),r=this.GetLayerBySID(e);r&&r._LoadFromJson(s)}if(e.hasOwnProperty("dynamicLayers")){this.RemoveAllDynamicLayers(),this._runtime.FlushPendingInstances();const t=new Map,s=e["dynamicLayers"];for(let e=s.length-1;e>=0;--e){const r=s[e],a=r["sid"],n=r["name"],i=r["parentSid"],o=r["siblingIndex"],l=r["data"];if(this._ReindexLayers(),this.HasLayerByName(n)||this.GetLayerBySID(a))continue;let h,c;if(null===i)h=null,c=this._rootLayers;else{if(h=this.GetLayerBySID(i),!h)continue;c=h.GetSubLayers()}const d=C3.New(C3.Layer,this,h,{name:n,sid:a,isDynamic:!0});c.push(d);let _=t.get(c);_||(_=[],t.set(c,_)),_.push({layer:d,siblingIndex:o}),d._LoadFromJson(l)}for(const[e,s]of t){s.sort(((e,t)=>e.siblingIndex-t.siblingIndex));for(const t of s){const s=t.layer,r=t.siblingIndex;let a=e.indexOf(s);e.splice(a,1),e.splice(r,0,s)}}}this._ReindexAndUpdateAllLayers(),this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged()}GetILayout(){return this._iLayout}UserScriptDispatcher(){return this._userScriptDispatcher}DispatchUserScriptEvent(e){e.layout=this.GetILayout();const t=this._runtime,s=t.IsDebug()&&!t.GetEventSheetManager().IsInEventEngine();s&&C3Debugger.StartMeasuringScriptTime(),this._userScriptDispatcher.dispatchEvent(e),s&&C3Debugger.AddScriptTime()}DispatchUserScriptEventAsyncWait(e){return e.layout=this.GetILayout(),this._userScriptDispatcher.dispatchEventAndWaitAsync(e)}DispatchRuntimeUserScriptEventAsyncWait(e){return e.layout=this.GetILayout(),this._runtime.DispatchUserScriptEventAsyncWait(e)}_LogLayerTree(){this._LogLayerList(this._rootLayers)}_LogLayerList(e,t=0){const s=e.slice(0);s.reverse();for(const e of s)console.log(`${"\t".repeat(t)}- ${e.GetName()}`),this._LogLayerList(e.GetSubLayers(),t+1)}};
}

// layouts/layoutManager.js
{
const C3=self.C3;C3.LayoutManager=class extends C3.DefendedBase{#t;#n=[];#u=new Map;#a=new Map;#i=null;#e=[];#s=null;#o=0;#y=null;constructor(t){super(),this.#t=t}Release(){this.#t=null,this.#i=null,this.#s=null,this.#y=null,C3.clearArray(this.#n),this.#u.clear(),this.#a.clear(),C3.clearArray(this.#e)}Create(t){const n=C3.New(C3.Layout,this,this.#n.length,t);this.#n.push(n),this.#u.set(n.GetName().toLowerCase(),n),this.#a.set(n.GetSID(),n)}GetRuntime(){return this.#t}SetFirstLayout(t){this.#s=t}GetFirstLayout(){if(this.#s)return this.#s;if(this.#n.length)return this.#n[0];throw new Error("no first layout")}GetLayoutByName(t){return this.#u.get(t.toLowerCase())||null}GetLayoutBySID(t){return this.#a.get(t)||null}GetLayoutByIndex(t){return t=C3.clamp(Math.floor(t),0,this.#n.length-1),this.#n[t]}GetLayout(t){return"number"==typeof t?this.GetLayoutByIndex(t):this.GetLayoutByName(t.toString())}GetAllLayouts(){return this.#n}_SetMainRunningLayout(t){this.#i=t}GetMainRunningLayout(){return this.#i}_AddRunningSubLayout(t){if(this.#e.includes(t))throw new Error("layout already running");this.#e.push(t)}_RemoveRunningSubLayout(t){const n=this.#e.indexOf(t);if(-1===n)throw new Error("layout not running");this.#e.splice(n,1)}*runningLayouts(){this.#i&&(yield this.#i),this.#e.length&&(yield*this.#e)}IsLayoutRunning(t){return this.#i===t||this.#e.includes(t)}SetIsEndingLayout(t){if(t)this.#o++;else{if(this.#o<=0)throw new Error("already unset");this.#o--}}IsEndingLayout(){return this.#o>0}ChangeMainLayout(t){this.#y=t}ClearPendingChangeLayout(){this.#y=null}IsPendingChangeMainLayout(){return!!this.#y}GetPendingChangeMainLayout(){return this.#y}SetAllLayerProjectionChanged(){const t=this.GetMainRunningLayout();t&&t._SetAllLayersProjectionChanged()}SetAllLayerMVChanged(){const t=this.GetMainRunningLayout();t&&t._SetAllLayersMVChanged()}};
}

// timelines/timelineManager.js
{
const C3=self.C3,NAMES_REGEXP=new RegExp("<(.+?)>","g");C3.TimelineManager=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e,this._timelineDataManager=C3.New(C3.TimelineDataManager),this._pluginInstance=null,this._timelines=[],this._timelinesByName=new Map,this._objectClassToTimelineMap=new Map,this._timelinesCreatedByTemplate=new Map,this._scheduledTimelines=[],this._playingTimelines=[],this._markedForRemovalTimelines=[],this._hasRuntimeListeners=!1,this._changingLayout=!1,this._isTickingTimelines=!1,this._tickFunc=()=>this._OnTick(),this._tick2Func=()=>this._OnTick2(),this._beforeLayoutChange=()=>this._OnBeforeChangeLayout(),this._layoutChange=()=>this._OnAfterChangeLayout(),this._instanceDestroy=e=>this._OnInstanceDestroy(e.instance),this._beforeLoad=e=>this._OnBeforeLoad(),this._afterLoad=e=>this._OnAfterLoad(),this._afterLayoutStart=e=>this._OnAfterLayoutStart(),this._destroyedWhileLoadingState=[],this._renderChange=0}Release(){this.RemoveRuntimeListeners(),this._tickFunc=null,this._tick2Func=null,this._beforeLayoutChange=null,this._layoutChange=null,this._instanceDestroy=null,this._afterLoad=null;for(const e of this._timelines)e.Stop(),e.Release();C3.clearArray(this._timelines),this._timelines=null,this._timelineDataManager.Release(),this._timelineDataManager=null,C3.clearArray(this._scheduledTimelines),this._scheduledTimelines=null,C3.clearArray(this._playingTimelines),this._playingTimelines=null,C3.clearArray(this._markedForRemovalTimelines),this._markedForRemovalTimelines=null,this._timelinesByName.clear(),this._timelinesByName=null,this._objectClassToTimelineMap.clear(),this._objectClassToTimelineMap=null,this._timelinesCreatedByTemplate.clear(),this._timelinesCreatedByTemplate=null,C3.clearArray(this._destroyedWhileLoadingState),this._destroyedWhileLoadingState=null,this._runtime=null}AddRuntimeListeners(){const e=this._runtime.Dispatcher();e.addEventListener("pretick",this._tickFunc),e.addEventListener("tick2",this._tick2Func),e.addEventListener("beforelayoutchange",this._beforeLayoutChange),e.addEventListener("layoutchange",this._layoutChange),e.addEventListener("instancedestroy",this._instanceDestroy),e.addEventListener("beforeload",this._beforeLoad),e.addEventListener("afterload",this._afterLoad),e.addEventListener("afterlayoutstart",this._afterLayoutStart)}RemoveRuntimeListeners(){const e=this._runtime.Dispatcher();e.removeEventListener("pretick",this._tickFunc),e.removeEventListener("tick2",this._tick2Func),e.removeEventListener("beforelayoutchange",this._beforeLayoutChange),e.removeEventListener("layoutchange",this._layoutChange),e.removeEventListener("instancedestroy",this._instanceDestroy),e.removeEventListener("beforeload",this._beforeLoad),e.removeEventListener("afterload",this._afterLoad),e.removeEventListener("afterlayoutstart",this._afterLayoutStart)}Create(e){this._timelineDataManager.Add(e);const i=C3.TimelineState.CreateInitial(e,this);this.Add(i),this.SetTimelineObjectClassesToMap(i),this._timelinesCreatedByTemplate.set(i.GetName(),0)}CreateFromTemplate(e){const i=this.GetTimelineDataManager(),t=e.GetTemplateName(),s=i.Get(t),n=C3.TimelineState.CreateFromTemplate(`${t}:${this._timelinesCreatedByTemplate.get(t)}`,s,this);return this._IncreaseTemplateTimelinesCount(t),this.Add(n),n}_IncreaseTemplateTimelinesCount(e){this._timelinesCreatedByTemplate.set(e,this._timelinesCreatedByTemplate.get(e)+1)}_SetCreatedTemplateTimelinesCount(){for(const e of this._timelines){if(e.IsTemplate())continue;const i=e.GetTemplateName();this._IncreaseTemplateTimelinesCount(i)}}_ClearCreatedTemplateTimelinesCount(){for(const e of this._timelinesCreatedByTemplate.keys())this._timelinesCreatedByTemplate.set(e,0)}Add(e){this._timelines.push(e),this._timelinesByName.set(e.GetName().toLowerCase(),e)}Remove(e){e.Removed(),e.IsTemplate()||(C3.arrayFindRemove(this._timelines,e),C3.arrayFindRemove(this._scheduledTimelines,e),C3.arrayFindRemove(this._playingTimelines,e),C3.arrayFindRemove(this._markedForRemovalTimelines,e),this._timelinesByName.delete(e.GetName().toLowerCase()),this.RemoveTimelineFromObjectClassMap(e),e.IsReleased()||e.Release())}Trigger(e){this._runtime.Trigger(e,this._pluginInstance,null)}GetRuntime(){return this._runtime}GetTimelineDataManager(){return this._timelineDataManager}SetPluginInstance(e){this._pluginInstance=e}GetPluginInstance(){return this._pluginInstance}*GetTimelines(){for(const e of this._timelines)yield e}*GetPlayingTimelines(){for(const e of this._playingTimelines)yield e}SetTimelineObjectClassToMap(e,i){this._objectClassToTimelineMap.has(e)||this._objectClassToTimelineMap.set(e,new Set),this._objectClassToTimelineMap.get(e).add(i)}SetTimelineObjectClassesToMap(e){for(const i of e.GetObjectClasses())this.SetTimelineObjectClassToMap(i,e)}RemoveTimelineFromObjectClassMap(e){for(const[i,t]of this._objectClassToTimelineMap.entries())t.has(e)&&(t.delete(e),0===t.size&&this._objectClassToTimelineMap.delete(i))}GetTimelinesForObjectClass(e){if(this._objectClassToTimelineMap.has(e))return this._objectClassToTimelineMap.get(e)}GetTimelineOfTemplateForInstances(e,i){if(i)for(const t of this._timelines){if(i.every((e=>t.HasTrackInstance(e.instance,e.trackId)))&&t.GetName().includes(e.GetName()))return t}}GetTimelineByName(e){return this._timelinesByName.get(e.toLowerCase())||null}GetScheduledOrPlayingTimelineByName(e){for(const i of this._scheduledTimelines)if(i.GetName()===e)return i;for(const i of this._playingTimelines)if(i.GetName()===e)return i;return null}*GetTimelinesByName(e){if(NAMES_REGEXP.test(e)){let i;NAMES_REGEXP.lastIndex=0;const t=new Set;do{if(i=NAMES_REGEXP.exec(e),i){const e=i[1].split(",");for(const i of e)t.add(i)}}while(i);for(const e of t.values()){const i=this.GetTimelineByName(e);i&&(yield i)}t.clear()}else{const i=this.GetTimelineByName(e);i&&(yield i)}}*GetTimelinesByTags(e){for(const i of this._timelines)i.HasTags(e)&&(yield i)}AddScheduledTimeline(e){this._scheduledTimelines.includes(e)||this._scheduledTimelines.push(e),this._MaybeEnableRuntimeListeners()}RemovePlayingTimeline(e){C3.arrayFindRemove(this._playingTimelines,e),this._MaybeDisableRuntimeListeners()}ScheduleTimeline(e){this._playingTimelines.includes(e)?(e.SetPlaying(!0),e.SetScheduled(!1),e.SetMarkedForRemoval(!1)):(e.SetPlaying(!1),e.SetScheduled(!0),e.SetMarkedForRemoval(!1),this._scheduledTimelines.includes(e)||this._scheduledTimelines.push(e)),this._MaybeEnableRuntimeListeners()}DeScheduleTimeline(e){e.SetPlaying(!1),e.SetScheduled(!1),e.ResolvePlayPromise(),C3.arrayFindRemove(this._scheduledTimelines,e),this._MaybeDisableRuntimeListeners()}CompleteTimeline(e){e.SetPlaying(!1),e.SetScheduled(!1),this._playingTimelines.includes(e)&&(e.SetMarkedForRemoval(!0),this._markedForRemovalTimelines.push(e),C3.arrayFindRemove(this._playingTimelines,e)),this._scheduledTimelines.includes(e)&&e.SetMarkedForRemoval(!0)}CompleteTimelineBeforeChangeOfLayout(e){e.SetPlaying(!1),e.SetScheduled(!1),e.SetMarkedForRemoval(!1),e.SetPlaybackRate(1),C3.arrayFindRemove(this._playingTimelines,e)}CompleteTimelineAndResolve(e){this.CompleteTimeline(e),e.ResolvePlayPromise()}_OnTick(){const e=this.GetRuntime();if(e.IsLoadingState())return;if(!this._hasRuntimeListeners)return;if(this._changingLayout)return;let i=0;for(e.IsDebug()&&(i=performance.now()),this._isTickingTimelines=!0;this._scheduledTimelines.length;){const e=this._scheduledTimelines.pop();e.IsMarkedForRemoval()?(e.SetInitialStateForce(),this._markedForRemovalTimelines.push(e)):(e.SetInitialState(),this._playingTimelines.push(e)),0!==e.GetRenderChange()&&(this._renderChange=1)}const t=this._runtime._GetDtFast(),s=this._runtime.GetDt1(),n=this._runtime.GetTimeScale();for(let e=this._playingTimelines.length-1;e>=0;e--){const i=this._playingTimelines[e];i&&i.Tick(t,n,s)}this._isTickingTimelines=!1,e.IsDebug()&&globalThis.C3Debugger.AddTweensAndTimelinesTime(performance.now()-i),0!==this._renderChange&&e.UpdateRender()}_OnTick2(){const e=this.GetRuntime();if(e.IsLoadingState())return;if(!this._hasRuntimeListeners)return;if(this._changingLayout)return;let i,t=0;e.IsDebug()&&(t=performance.now());for(let e=0,t=this._markedForRemovalTimelines.length;e<t;e++){const t=this._markedForRemovalTimelines[e];i||(i=new Set),t.Removed(),this._MaybeExecuteTimelineFinishTriggers(t),i.add(t)}if(i){C3.arrayRemoveAllInSet(this._markedForRemovalTimelines,i),this._renderChange=0;for(let e=0,i=this._playingTimelines.length;e<i;e++)if(0!==this._playingTimelines[e].GetRenderChange()){this._renderChange=1;break}}this._MaybeDisableRuntimeListeners(),e.IsDebug()&&globalThis.C3Debugger.AddTweensAndTimelinesTime(performance.now()-t)}_MaybeExecuteTimelineFinishTriggers(e){e.IsReleased()||e.HasValidTracks()&&e.IsComplete()&&e.InitialStateSet()&&e.FinishTriggers()}_MaybeEnableRuntimeListeners(){this._hasRuntimeListeners||(this._hasRuntimeListeners=!0)}_MaybeDisableRuntimeListeners(){this._markedForRemovalTimelines.length||this._playingTimelines.length||this._scheduledTimelines.length||this._isTickingTimelines||(this._hasRuntimeListeners=!1)}_OnBeforeChangeLayout(){for(this._changingLayout=!0;this._scheduledTimelines.length;)this.DeScheduleTimeline(this._scheduledTimelines.pop());const e=new Set;for(const i of this._playingTimelines){i._OnBeforeChangeLayout()&&(i.Removed(),e.add(i))}C3.arrayRemoveAllInSet(this._playingTimelines,e),e.clear();for(const i of this._markedForRemovalTimelines){i._OnBeforeChangeLayout()&&(i.Removed(),e.add(i))}C3.arrayRemoveAllInSet(this._markedForRemovalTimelines,e),this._MaybeDisableRuntimeListeners();for(const e of this._timelines)e.CleanCaches()}_OnAfterChangeLayout(){this._changingLayout=!1}_OnInstanceDestroy(e){const i=e.GetObjectClass(),t=this.GetTimelinesForObjectClass(i);if(t)if(this._runtime.IsLoadingState())this._destroyedWhileLoadingState.push(e);else for(const e of t)e.IsTemplate()||(e.IsReleased()?this.Remove(e):e.HasValidTracks()||(this._MaybeExecuteTimelineFinishTriggers(e),this.Remove(e)))}_OnBeforeLoad(){for(const e of this._scheduledTimelines.map((e=>e)))this._MaybeExecuteTimelineFinishTriggers(e),this.Remove(e);for(const e of this._playingTimelines.map((e=>e)))this._MaybeExecuteTimelineFinishTriggers(e),this.Remove(e)}_OnAfterLoad(){for(const e of this._destroyedWhileLoadingState)this._OnInstanceDestroy(e);C3.clearArray(this._destroyedWhileLoadingState);for(const e of this._timelines)e._OnAfterLoad()}_OnAfterLayoutStart(){const e=this._runtime.GetLayoutManager().GetMainRunningLayout();if(e)for(const i of this._timelines){const t=i.GetStartOnLayout();t&&(e.GetName()===t&&this.ScheduleTimeline(i))}}_SaveToJson(){return{"timelinesJson":this._SaveTimelinesToJson(),"scheduledTimelinesJson":this._SaveScheduledTimelinesToJson(),"playingTimelinesJson":this._SavePlayingTimelinesToJson(),"markedForRemovalTimelinesJson":this._SaveMarkedForRemovalTimelinesToJson(),"hasRuntimeListeners":this._hasRuntimeListeners,"changingLayout":this._changingLayout,"isTickingTimelines":this._isTickingTimelines}}_LoadFromJson(e){e&&(this._ClearCreatedTemplateTimelinesCount(),this._LoadTimelinesFromJson(e["timelinesJson"]),this._LoadScheduledTimelinesFromJson(e["scheduledTimelinesJson"]),this._LoadPlayingTimelinesFromJson(e["playingTimelinesJson"]),this._LoadMarkedForRemovalTimelinesFromJson(e["markedForRemovalTimelinesJson"]),this._hasRuntimeListeners=!e["hasRuntimeListeners"],this._changingLayout=!!e["changingLayout"],this._isTickingTimelines=!!e["isTickingTimelines"],this._SetCreatedTemplateTimelinesCount(),this._MaybeEnableRuntimeListeners(),this._MaybeDisableRuntimeListeners())}_SaveTimelinesToJson(){return this._timelines.map((e=>e._SaveToJson()))}_LoadTimelinesFromJson(e){for(const i of e){let e=this.GetTimelineByName(i["name"]);if(e)e._LoadFromJson(i);else{const t=this._GetTemplateNameFromJson(i);if(!t)continue;const s=this.GetTimelineByName(t);e=this.CreateFromTemplate(s),e._LoadFromJson(i)}e.HasTracks()||this.Remove(e)}}_GetTemplateNameFromJson(e){const i=e["name"].split(":");return i&&2===i.length?i[0]:null}_SaveScheduledTimelinesToJson(){return this._SaveTimelines(this._scheduledTimelines)}_LoadScheduledTimelinesFromJson(e){this._LoadTimelines(e,this._scheduledTimelines)}_SavePlayingTimelinesToJson(){return this._SaveTimelines(this._playingTimelines)}_LoadPlayingTimelinesFromJson(e){this._LoadTimelines(e,this._playingTimelines)}_SaveMarkedForRemovalTimelinesToJson(){return this._SaveTimelines(this._markedForRemovalTimelines)}_LoadMarkedForRemovalTimelinesFromJson(e){this._LoadTimelines(e,this._markedForRemovalTimelines)}_IsTimelineInJson(e,i){if(!i)return!1;for(const t of i)if(t===e.GetName())return!0;return!1}_SaveTimelines(e){return e.map((e=>e.GetName()))}_LoadTimelines(e,i){const t=new Set;for(const s of i)this._IsTimelineInJson(s,e)||t.add(s);if(C3.arrayRemoveAllInSet(i,t),e){const t=e=>i=>i.GetName()===e;for(const s of e){const e=this.GetTimelineByName(s);if(e){i.find(t(s))||i.push(e)}}}}};
}

// timelines/timelineInfo.js
{
const C3=self.C3,STEPS=100,LENGTH_STEP_SIZE=.01,BEZIER_STEP_SIZE=25,REFINE_ITERATIONS=20,LOOKUP_STEPS_FROM_LAST=5,TANGENT_RESULT=[0,0],MAP_RESULT=[0,0],SHORT_PROJECTION_RESULT=[0,0],PROJECTION_RESULT=[0,0,0,0,0],REFINE_LUT=new Array(4),REFINE_LUT_OBJECTS=[{x:0,y:0,t:0,distance:0},{x:0,y:0,t:0,distance:0},{x:0,y:0,t:0,distance:0}],REFINE_RESULT={x:0,y:0,t:0,distance:0};C3.TimelineInfo=class{constructor(t,i){this._initialized=!1,this._timeline=t,this._segments=[];let e=null;if(e=i?this._timeline.GetTrackById(i):C3.first(this._timeline.GetTracks()),!e)return;const s=e.GetPropertyTrack("offsetX"),_=e.GetPropertyTrack("offsetY");if(!s||!_)return;this._xTrack=s,this._yTrack=_;const h=s.GetPropertyKeyframeDataItemArrayIncludingDisabled(),n=_.GetPropertyKeyframeDataItemArrayIncludingDisabled();for(let t=1,i=Math.min(h.length,n.length);t<i;++t){const i=h[t],e=(i.GetNext(),i.GetPrevious()),s=n[t],_=(s.GetNext(),s.GetPrevious());e&&"cubic-bezier"===e.GetPathMode()&&_&&"cubic-bezier"===_.GetPathMode()?this._segments.push(C3.New(C3.TimelineCubicBezierSegmentInfo,e,_,i,s,this._segments.length)):(e&&"line"===e.GetPathMode()&&_&&_.GetPathMode(),this._segments.push(C3.New(C3.TimelineLineSegmentInfo,i,s,this._segments.length)))}this._initialized=!0}Release(){for(const t of this._segments)t.Release();C3.clearArray(this._segments),this._segments=null,this._timeline=null,this._xTrack=null,this._yTrack=null}WasInitialized(){return this._initialized}segments(){return this._segments}SetOrigin(t){const i="relative"===this._xTrack.GetResultMode()?t.GetX():0,e="relative"===this._yTrack.GetResultMode()?t.GetY():0;for(const t of this._segments)t.SetOrigin(i,e)}Project(t,i,e){let s=NaN,_=this._segments.length;for(let e=0;e<_;e++){const _=this._segments[e];if("cubic-bezier"===_.GetType()){const e=_.Project(t,i);(isNaN(s)||e[3]<s)&&(s=e[3],SHORT_PROJECTION_RESULT[0]=e[2],SHORT_PROJECTION_RESULT[1]=_.GetIndex())}}return SHORT_PROJECTION_RESULT}ProjectWithOptions(t,i,e){const s=e.tRange;C3.IsFiniteNumber(s[0])||(s[0]=0),C3.IsFiniteNumber(s[1])||(s[1]=1);let _=NaN,h=this._segments.length;for(let e=0;e<h;e++){const h=this._segments[e];if("cubic-bezier"===h.GetType()){const e=h.ProjectWithRange(t,i,s);(isNaN(_)||e[3]<_)&&(_=e[3],SHORT_PROJECTION_RESULT[0]=e[2],SHORT_PROJECTION_RESULT[1]=h.GetIndex())}}return SHORT_PROJECTION_RESULT}Tangent(t,i){return this._segments[i].Tangent(t)}TangentAngle(t,i){return this._segments[i].TangentAngle(t)}},C3.TimelineCubicBezierSegmentInfo=class{constructor(t,i,e,s,_){this._index=_;const h=t.GetAddOn("cubic-bezier"),n=e.GetAddOn("cubic-bezier"),r=i.GetAddOn("cubic-bezier"),a=s.GetAddOn("cubic-bezier");this._aX=t.GetValueWithResultMode(),this._aY=i.GetValueWithResultMode(),this._bX=t.GetValueWithResultMode()+h.GetStartAnchor(),this._bY=i.GetValueWithResultMode()+r.GetStartAnchor(),this._cX=e.GetValueWithResultMode()+n.GetEndAnchor(),this._cY=s.GetValueWithResultMode()+a.GetEndAnchor(),this._dX=e.GetValueWithResultMode(),this._dY=s.GetValueWithResultMode(),this._aXO=0,this._aYO=0,this._bXO=0,this._bYO=0,this._cXO=0,this._cYO=0,this._dXO=0,this._dYO=0,this._d0x=0,this._d0y=0,this._d1x=0,this._d1y=0,this._d2x=0,this._d2y=0,this._x1Factor=0,this._x2Factor=0,this._x3Factor=0,this._y1Factor=0,this._y2Factor=0,this._y3Factor=0,this._lutIndex=NaN,this._initialized=!1,this._len=100,this._arcLengths=new Array(this._len+1),this._arcLengths[0]=0,this._length=0,this._lut=[],this._lutObjects=[];for(let t=0;t<100;t++)this._lutObjects.push({x:0,y:0,t:0,distance:0});this._CalculateLength()}Release(){C3.clearArray(this._arcLengths),this._arcLengths=null,C3.clearArray(this._lut),this._lut=null,C3.clearArray(this._lutObjects),this._lutObjects=null}GetType(){return"cubic-bezier"}GetIndex(){return this._index}GetStepCount(){return Math.floor(this._length/25)}GetStepIncrement(){return 1/this.GetStepCount()}SetOrigin(t,i){this._originX=t,this._originY=i,this._arcLengths=new Array(this._len+1),this._arcLengths[0]=0,this._CalculateLength(),this._aXO=this._aX+this._originX,this._aYO=this._aY+this._originY,this._bXO=this._bX+this._originX,this._bYO=this._bY+this._originY,this._cXO=this._cX+this._originX,this._cYO=this._cY+this._originY,this._dXO=this._dX+this._originX,this._dYO=this._dY+this._originY,this._d0x=3*(this._bXO-this._aXO),this._d0y=3*(this._bYO-this._aYO),this._d1x=3*(this._cXO-this._bXO),this._d1y=3*(this._cYO-this._bYO),this._d2x=3*(this._dXO-this._cXO),this._d2y=3*(this._dYO-this._cYO),this._x1Factor=3*(this._bXO-this._aXO),this._x2Factor=3*(this._aXO+this._cXO-2*this._bXO),this._x3Factor=this._dXO-this._aXO+3*(this._bXO-this._cXO),this._y1Factor=3*(this._bYO-this._aYO),this._y2Factor=3*(this._aYO+this._cYO-2*this._bYO),this._y3Factor=this._dYO-this._aYO+3*(this._bYO-this._cYO)}Map(t){if(!this._initialized)return NaN;const i=this._Map(t);return MAP_RESULT[0]=this._X(i),MAP_RESULT[1]=this._Y(i),MAP_RESULT}Project(t,i){const e=this._GenerateLUT(100),s=this._FindClosestFromLUT(t,i,e),_=this._RefineProjection(t,i,e,s);return PROJECTION_RESULT[0]=_.x,PROJECTION_RESULT[1]=_.y,PROJECTION_RESULT[2]=_.t,PROJECTION_RESULT[3]=_.distance,PROJECTION_RESULT}ProjectWithRange(t,i,e){const s=this._GenerateLUT(100),_=this._FindClosestFromLUTWithRange(t,i,s,e),h=this._RefineProjection(t,i,s,_);return PROJECTION_RESULT[0]=h.x,PROJECTION_RESULT[1]=h.y,PROJECTION_RESULT[2]=h.t,PROJECTION_RESULT[3]=h.distance,PROJECTION_RESULT}Tangent(t){const i=1-t,e=i*i,s=2*i*t,_=t*t,h=e*this._d0x+s*this._d1x+_*this._d2x,n=e*this._d0y+s*this._d1y+_*this._d2y,r=C3.hypot2DFast(h,n);return TANGENT_RESULT[0]=h/r,TANGENT_RESULT[1]=n/r,TANGENT_RESULT}TangentAngle(t){const i=1-t,e=i*i,s=2*i*t,_=t*t,h=e*this._d0x+s*this._d1x+_*this._d2x,n=e*this._d0y+s*this._d1y+_*this._d2y;return Math.atan2(n,h)}_Map(t){if(!this._initialized)return;let i=t*this._arcLengths[this._len],e=0,s=this._len,_=0;for(;e<s;)_=e+((s-e)/2|0),this._arcLengths[_]<i?e=_+1:s=_;this._arcLengths[_]>i&&_--;const h=this._arcLengths[_];return h===i?_/this._len:(_+(i-h)/(this._arcLengths[_+1]-h))/this._len}_X(t){return this._initialized?self.Ease.GetRuntimeEase("cubicbezier")(t,this._aX+this._originX,this._bX+this._originX,this._cX+this._originX,this._dX+this._originX):NaN}_Y(t){return this._initialized?self.Ease.GetRuntimeEase("cubicbezier")(t,this._aY+this._originY,this._bY+this._originY,this._cY+this._originY,this._dY+this._originY):NaN}_GenerateLUT(t){if(t=t||100,this._lut.length>=t)return this._lut;this._lut=new Array(t),t++;for(let i=0;i<t-1;i++){const e=i/(t-1),s=e**2,_=e**3,h=this._x1Factor*e,n=this._x2Factor*s,r=this._x3Factor*_,a=this._y1Factor*e,c=this._y2Factor*s,l=this._y3Factor*_,o=this._aXO+h+n+r,d=this._aYO+a+c+l;this._lutObjects[i].x=o,this._lutObjects[i].y=d,this._lutObjects[i].t=e,this._lutObjects[i].distance=0,this._lut[i]=this._lutObjects[i]}return this._lut}_FindClosestFromLUT(t,i,e,s=null,_=Number.MAX_SAFE_INTEGER){let h=0;if(isNaN(this._lutIndex))for(let s=0;s<100;s++){const n=e[s],r=n.x-t,a=n.y-i;n.distance=r*r+a*a,n.distance<_&&(_=n.distance,h=s)}else{for(let s=this._lutIndex;s<this._lutIndex+5&&!(s>=e.length);s++){const n=e[s],r=n.x-t,a=n.y-i;n.distance=r*r+a*a,n.distance<_&&(_=n.distance,h=s)}for(let s=this._lutIndex;s>this._lutIndex-5&&!(s<0);s--){const n=e[s],r=n.x-t,a=n.y-i;n.distance=r*r+a*a,n.distance<_&&(_=n.distance,h=s)}}return this._lutIndex=h,h}_FindClosestFromLUTWithRange(t,i,e,s,_=Number.MAX_SAFE_INTEGER){let h=0;if(isNaN(this._lutIndex))for(let n=0;n<100;n++){const r=e[n],a=r.x-t,c=r.y-i;r.distance=a*a+c*c,r.t>=s[0]&&r.t<=s[1]&&r.distance<_&&(_=r.distance,h=n)}else{for(let n=this._lutIndex;n<this._lutIndex+5&&!(n>=e.length);n++){const r=e[n],a=r.x-t,c=r.y-i;r.distance=a*a+c*c,r.t>=s[0]&&r.t<=s[1]&&r.distance<_&&(_=r.distance,h=n)}for(let n=this._lutIndex;n>this._lutIndex-5&&!(n<0);n--){const r=e[n],a=r.x-t,c=r.y-i;r.distance=a*a+c*c,r.t>=s[0]&&r.t<=s[1]&&r.distance<_&&(_=r.distance,h=n)}}return this._lutIndex=h,h}_RefineProjection(t,i,e,s){let _=e[s],h=1,n=Number.MAX_SAFE_INTEGER;t:do{const h=e.length;let r=0===s?0:s-1,a=s===h-1?h-1:s+1,c=e[r].t,l=(e[a].t-c)/4;if(l<.001)break;REFINE_LUT[0]=e[r];for(let e=1;e<=2;e++){const h=c+e*l,r=h**2,a=h**3,o=this._x1Factor*h,d=this._x2Factor*r,u=this._x3Factor*a,O=this._y1Factor*h,T=this._y2Factor*r,E=this._y3Factor*a,R=this._aXO+o+d+u,g=this._aYO+O+T+E,N=R-t,I=g-i,S=N*N+I*I;if(S<n){n=S,s=e,REFINE_RESULT.x=R,REFINE_RESULT.y=g,REFINE_RESULT.t=h,REFINE_RESULT.distance=S,_=REFINE_RESULT;break t}const x=REFINE_LUT_OBJECTS[e-1];x.x=R,x.y=g,x.t=h,x.distance=S,REFINE_LUT[e]=x}REFINE_LUT[3]=e[a],e=REFINE_LUT}while(h++<20);return _}_CalculateLength(){this._initialized=!0;let t=this._X(0),i=this._Y(0),e=0;for(let s=1;s<=this._len;s++){const _=this._X(.01*s),h=this._Y(.01*s),n=t-_,r=i-h;e+=C3.hypot2DFast(n,r),this._arcLengths[s]=e,t=_,i=h}this._length=e}},C3.TimelineLineSegmentInfo=class{constructor(t,i,e){this._index=e,this._targetX=t.GetValueWithResultMode(),this._targetY=i.GetValueWithResultMode(),this._originX=0,this._originY=0}Release(){}GetType(){return"line"}GetIndex(){return this._index}SetOrigin(t,i){this._originX=t,this._originY=i}GetX(){return this._targetX+this._originX}GetY(){return this._targetY+this._originY}};
}

// timelines/state/timelineState.js
{
const C3=self.C3,PING_PONG_BEGIN=0,PING_PONG_END=1;C3.TimelineState=class extends C3.DefendedBase{constructor(t,e,i){super(),this._runtime=i.GetRuntime(),this._timelineManager=i,this._timelineDataItem=e,this._name=t,this._tracks=[],this._tracksLength=0,this._beforeAndAfterTracks=null,this._beforeAndAfterTracksLength=0,this.CreateTrackStates(),this._playPromise=null,this._playResolve=null,this._playheadTime=0,this._overshoot=0,this._playbackRate=1,this._pingPongState=0,this._resumePingPongState=-1,this._currentRepeatCount=1,this._isPlaying=!1,this._isScheduled=!1,this._initialStateSet=!1,this._complete=!0,this._released=!1,this._markedForRemoval=!1,this._completedTick=-1,this._implicitPause=!1,this._isTemplate=!1,this._finishedTriggers=!1,this._firstTick=!1,this._lastDelta=NaN,this._tags=[""],this._stringTags="",this._tagsChanged=!1,this._renderChange=0,this._hasNestedContent=0,this._stoppedKeyframeDataItem=null,this._iTimelineState=null}static CreateInitial(t,e){const i=e.GetTimelineDataManager(),s=i.GetNameId(),a=i.Get(t[s]),n=C3.New(C3.TimelineState,t[s],a,e);return n.SetIsTemplate(!0),n}static CreateFromTemplate(t,e,i){return C3.New(C3.TimelineState,t,e,i)}Release(){if(this.IsReleased())return;const t=this._runtime.Dispatcher();this._timelineManager.DeScheduleTimeline(this),this._timelineManager.CompleteTimelineAndResolve(this);for(const t of this._tracks)t.Release();C3.clearArray(this._tracks),this._tracks=null,this._runtime=null,this._timelineManager=null,this._timelineDataItem=null,this._released=!0,this._playPromise=null,this._playResolve=null,this.FireReleaseEvent(t)}FireReleaseEvent(t){const e=C3.New(C3.Event,"timelinestatereleased");e.timelineState=this,t.dispatchEvent(e)}GetType(){return 0}CreateTrackStates(){for(const t of this._timelineDataItem.GetTrackData().trackDataItems())this._tracksLength=this._tracks.push(C3.TrackState.Create(this,t))}GetTimelineManager(){return this._timelineManager}GetRuntime(){return this._runtime}GetTracks(){return this._tracks}GetSimilarPropertyTracks(t,e,i,s){if(!this._hasNestedContent)return;let a;for(let n=0;n<this._tracks.length;n++){let r=this._tracks[n];if(t!==r.GetInstance())continue;const h=r.GetPropertyTrack(i);h&&(e.constructor===h.GetSourceAdapter().constructor&&h.GetResultMode()===s.GetResultMode()&&(a||(a=[]),a.push(h)))}return a}HasTracks(){return!!this._tracks.length}GetTrackById(t){for(const e of this._tracks)if(C3.equalsNoCase(e.GetId(),t))return e;return null}GetTrackByName(t){for(const e of this._tracks)if(!e.IsInstanceTrack()&&C3.equalsNoCase(e.GetName(),t))return e;return null}SetName(t){this._name=t}GetName(){return this._name}GetTimelineDataItem(){return this._timelineDataItem}GetTemplateName(){return this._timelineDataItem.GetName()}GetTotalTime(){return this._timelineDataItem.GetTotalTime()}SetTotalTime(t){this._timelineDataItem.SetTotalTime(t)}GetStep(){return this._timelineDataItem.GetStep()}SetStep(t){this._timelineDataItem.SetStep(t)}GetInterpolationMode(){return this._timelineDataItem.GetInterpolationMode()}SetInterpolationMode(t){this._timelineDataItem.SetInterpolationMode(t)}GetResultMode(){return this._timelineDataItem.GetResultMode()}SetResultMode(t){this._timelineDataItem.GetResultMode(t)}SetEase(t){for(const e of this.GetTracks())e.SetEase(t)}GetLoop(){return this._timelineDataItem.GetLoop()}SetLoop(t){return this._timelineDataItem.SetLoop(t)}GetPingPong(){return this._timelineDataItem.GetPingPong()}SetPingPong(t){return this._timelineDataItem.SetPingPong(t)}GetRepeatCount(){return this._timelineDataItem.GetRepeatCount()}SetRepeatCount(t){return this._timelineDataItem.SetRepeatCount(t)}SetPlaybackRate(t){return this._playbackRate=t}GetPlaybackRate(){return this._playbackRate}GetStartOnLayout(){return this._timelineDataItem.GetStartOnLayout()}GetTransformWithSceneGraph(){return this._timelineDataItem.GetTransformWithSceneGraph()}GetUseSystemTimescale(){return this._timelineDataItem.GetUseSystemTimescale()}GetPingPongState(){return this._pingPongState}IsForwardPlayBack(){return!this.IsPlaying()||this._playbackRate>0}GetPlayPromise(){return this._playPromise||(this._playPromise=new Promise((t=>{this._playResolve=t}))),this._playPromise}ResolvePlayPromise(){this._playPromise&&(this._playResolve(),this._playPromise=null,this._playResolve=null)}SetTags(t){this._tags=C3.TimelineState._GetTagArray(t),this._tagsChanged=!0}GetTags(){return this._tags}GetStringTags(){return this._tagsChanged&&(this._stringTags=this._tags.join(" ")),this._tagsChanged=!1,this._stringTags}HasTags(t){if(!this._tags)return!1;if(!this._tags.length)return!1;const e=C3.TimelineState._GetTagArray(t);return!!e&&(!!e.length&&e.every(C3.TimelineState._HasTag,this))}OnStarted(){C3.Plugins.Timeline&&this.constructor===C3.TimelineState&&(C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStarted),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStartedByName),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStartedByTags),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnAnyTimelineStarted),C3.Plugins.Timeline.Cnds.PopTriggerTimeline())}OnCompleted(){this._completedTick=this._runtime.GetTickCount()}FinishTriggers(){this._finishedTriggers||(this._finishedTriggers=!0,C3.Plugins.Timeline&&this.constructor===C3.TimelineState&&(C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinished),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinishedByName),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinishedByTags),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnAnyTimelineFinished),C3.Plugins.Timeline.Cnds.PopTriggerTimeline()))}SetPlaying(t){this._isPlaying=t}IsCompletedTick(){return this._completedTick===this._runtime.GetTickCount()}IsPlaying(t=!1){return!!this.IsCompletedTick()||(!(!this.IsScheduled()||t)||this._isPlaying)}_IsPlaying(){return this.IsPlaying(!0)}IsPaused(){return this._IsPaused()}_IsPaused(){return!this.IsReleased()&&(!this.IsScheduled()&&(!this._IsPlaying()&&!this.IsComplete()))}SetScheduled(t){this._isScheduled=t}IsScheduled(){return this._isScheduled}SetComplete(t){this._complete=t;const e=this.GetLoop(),i=this.GetPingPong();if(e||i){if(e&&!i);else if(!e&&i){const t=this.GetTime();1===this._pingPongState&&(t<=0||t>=this.GetTotalTime())&&(this._complete=!0)}}else{const t=this.GetTime();(t<=0||t>=this.GetTotalTime())&&(this._complete=!0)}}IsComplete(){return this._complete}IsReleased(){return this._released}SetMarkedForRemoval(t){this._markedForRemoval=t}IsMarkedForRemoval(){return this._markedForRemoval}SetImplicitPause(t){this._implicitPause=t}IsImplicitPause(){return this._implicitPause}SetIsTemplate(t){this._isTemplate=!!t}IsTemplate(){return this._isTemplate}InitialStateSet(){return this._initialStateSet}GetTime(){return this._playheadTime}SetTime(t){const e=this.GetTime();this._SetTime(t),this.SetComplete(!1),this.IsComplete()||this.SetImplicitPause(!0),(this._IsPlaying()||this.IsScheduled()||!this._initialStateSet)&&(this._IsPlaying()||this.IsScheduled()||this._initialStateSet?this._IsPlaying()?this.Stop():this.IsScheduled()&&(this._timelineManager.DeScheduleTimeline(this),this.SetInitialStateFromSetTime()):this.SetInitialStateFromSetTime()),this._SetUpdateStateBefore(),this._Interpolate(this.GetTime(),!1,!0,!0,e),this._SetUpdateStateAfter(),this._renderChange&&this.GetRuntime().UpdateRender(),this._OnSetTime()}_SetTime(t){C3.IsFiniteNumber(t)||(t=this.GetTotalTime()),t<0?this._playheadTime=0:t>=this.GetTotalTime()?this._playheadTime=this.GetTotalTime():this._playheadTime=t}_SetTimeAndReset(t){C3.IsFiniteNumber(t)||(t=this.GetTotalTime()),t<0?this._playheadTime=0:t>=this.GetTotalTime()?this._playheadTime=this.GetTotalTime():this._playheadTime=t;for(const t of this._tracks)t.SetResetState()}_OnSetTime(){C3.Plugins.Timeline&&this.constructor===C3.TimelineState&&(C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSet),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSetByName),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSetByTags),C3.Plugins.Timeline.Cnds.PopTriggerTimeline())}_CanResume(){if(this.GetLoop())return!0;if(this.GetPingPong()&&1===this._pingPongState){if(this.IsForwardPlayBack()){if(this.GetTime()>=this.GetTotalTime())return!1}else if(this.GetTime()<=0)return!1}else if(!this.GetLoop()&&!this.GetPingPong())if(this.IsForwardPlayBack()){if(this.GetTime()>=this.GetTotalTime())return!1}else if(this.GetTime()<=0)return!1;return!0}Resume(){this.IsReleased()||this._CanResume()&&this.Play(!0)}Play(t=!1){return!this.IsReleased()&&(!this.IsScheduled()&&(this._IsPlaying()&&this.IsCompletedTick()?this._SchedulePlayingTimeline():!this._IsPlaying()&&(!!(this.IsComplete()||t||this.IsImplicitPause())&&this._ScheduleStoppedTimeline())))}_SchedulePlayingTimeline(){return this.SetImplicitPause(!1),this._timelineManager.RemovePlayingTimeline(this),this._timelineManager.ScheduleTimeline(this),this.GetPlayPromise(),!0}_ScheduleStoppedTimeline(){return this.SetImplicitPause(!1),this._timelineManager.ScheduleTimeline(this),this.GetPlayPromise(),!0}Stop(t=!1){this.IsReleased()||(this.SetComplete(t),this._timelineManager.CompleteTimeline(this),this.IsComplete()&&this.ResolvePlayPromise())}Reset(t=!0,e=!1){if(this.IsReleased())return;if(!this._IsPlaying()&&this.IsScheduled())return this._timelineManager.DeScheduleTimeline(this);if(this.IsComplete())return;this.Stop(!0),this.IsForwardPlayBack()?this._SetTime(0):this._SetTime(this.GetTotalTime());const i=this.GetTime();this._SetUpdateStateBefore(),e?this._InterpolateBeforeChangeLayout(i):this._Interpolate(i,!1,!1,!0),t&&this._OnSetTime(),this._SetUpdateStateAfter(),this._renderChange&&t&&this.GetRuntime().UpdateRender()}ResetBeforeChangeLayout(){this.Reset(!1,!0)}_InterpolateBeforeChangeLayout(t){this._Interpolate(t,!1,!1,!0,NaN,!1,!0)}_OnBeforeChangeLayout(){return!!this.IsReleased()||!(!this.GetRuntime().IsLoadingState()&&this.HasValidGlobalTracks())&&(this._timelineManager.CompleteTimelineBeforeChangeOfLayout(this),this.GetRuntime().IsLoadingState()||this.ResetBeforeChangeLayout(),!0)}SetInitialStateFromSetTime(){this.SetInitialState(!0)}SetInitialStateForce(){this.SetInitialState(!1,!0),this.SetPlaying(!1),this.SetScheduled(!1)}SetInitialState(t=!1,e=!1){if(!this.IsMarkedForRemoval()||e)if(t){this._finishedTriggers=!1,this._initialStateSet=!0,this._firstTick=!0,this._SetUpdateStateBefore();for(const t of this._tracks)t.SetInitialState();this._SetUpdateStateAfter()}else if(this.SetPlaying(!0),this.SetScheduled(!1),this.OnStarted(),this.IsComplete()){this._completedTick=-1,0!==this._pingPongState&&(this._playbackRate=Math.abs(this._playbackRate)),this._pingPongState=0,this._resumePingPongState=-1,this._currentRepeatCount=1,this._complete=!1,this._finishedTriggers=!1,this._initialStateSet=!0,this._firstTick=!0,this.IsForwardPlayBack()?this._SetTime(0):this._SetTime(this.GetTotalTime()),this._SetUpdateStateBefore();for(const t of this._tracks)t.SetInitialState();this._SetUpdateStateAfter()}else{-1!==this._resumePingPongState&&(this._pingPongState=this._resumePingPongState),this._firstTick=!0,this._finishedTriggers=!1,this._SetUpdateStateBefore();for(const t of this._tracks)t.SetResumeState();this._SetUpdateStateAfter()}}GetRenderChange(){return this._renderChange}_SetUpdateStateBefore(){this._hasNestedContent=0;for(const t of this._tracks)t.IsNested()&&(this._hasNestedContent=1)}_SetUpdateStateAfter(){this._renderChange=0;for(const t of this._tracks)t._SetUpdateState(),0===this._renderChange&&1===t.GetRenderChange()&&(this._renderChange=1),this._beforeAndAfterTracks||1!==t.GetNeedsBeforeAndAfter()||(this._beforeAndAfterTracks||(this._beforeAndAfterTracks=[]),this._beforeAndAfterTracksLength=this._beforeAndAfterTracks.push(t))}Tick(t,e,i){if(this.GetUseSystemTimescale()){if(0===t&&0===this._lastDelta)return;this._lastDelta=t,t=i}else{if(0===i&&0===this._lastDelta)return;this._lastDelta=i,t=i,e=1}const s=this._playheadTime+this._overshoot,a=s+t*e*this._playbackRate,n=this._timelineDataItem._totalTime;a<0?(this._playheadTime=0,this._overshoot=-a):a>=n?(this._playheadTime=n,this._overshoot=this._playheadTime-a):(this._playheadTime=a,this._overshoot=0);let r=!1,h=!1;const l=this.GetLoop(),o=this.GetPingPong();let m;l||o?l&&!o?this._playbackRate>0?this._playheadTime>=n&&(this._SetTimeAndReset(0),h=!0):this._playheadTime<=0&&(this._SetTimeAndReset(n),h=!0):!l&&o?this._playbackRate>0?this._playheadTime>=n&&(this._SetTime(n),this.SetPlaybackRate(-1*this.GetPlaybackRate()),h=!0,1===this._pingPongState?this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._pingPongState=0):r=!0:0===this._pingPongState&&(this._pingPongState=1)):this._playheadTime<=0&&(this._SetTime(0),this.SetPlaybackRate(-1*this.GetPlaybackRate()),h=!0,1===this._pingPongState?this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._pingPongState=0):r=!0:0===this._pingPongState&&(this._pingPongState=1)):l&&o&&(this._playbackRate>0?this._playheadTime>=n&&(this._SetTime(n),this.SetPlaybackRate(-1*this.GetPlaybackRate()),h=!0,this._pingPongState++,C3.wrap(this._pingPongState,0,2)):this._playheadTime<=0&&(this._SetTime(0),this.SetPlaybackRate(-1*this.GetPlaybackRate()),h=!0,this._pingPongState++,C3.wrap(this._pingPongState,0,2))):this._playbackRate>0?this._playheadTime>=n&&(this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._SetTimeAndReset(0),h=!0):(this._SetTime(n),r=!0)):this._playheadTime<=0&&(this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._SetTimeAndReset(n),h=!0):(this._SetTime(0),r=!0));const _=this._tracksLength;if(r){for(m=0;m<_;m++)this._tracks[m].SetEndState();return this.Stop(!0),void this.OnCompleted()}const c=this._beforeAndAfterTracksLength;for(m=0;m<c;m++)this._beforeAndAfterTracks[m].BeforeInterpolate();if(1===this._hasNestedContent)for(m=0;m<_;m++){const t=this._tracks[m],e=t.GetStartOffset();this._playheadTime-e<0&&s-e>0?(this._playheadTime=e<0?0:e>=n?n:e,t.Interpolate(e,!0,!1,h,this._firstTick,!1)):t.Interpolate(this._playheadTime,!0,!1,h,this._firstTick,!1)}else for(m=0;m<_;m++)this._tracks[m].Interpolate(this._playheadTime,!0,!1,h,this._firstTick,!1);if(!this.IsPlaying()&&this._stoppedKeyframeDataItem){const t=this._stoppedKeyframeDataItem.GetTime()+this._stoppedKeyframeDataItem.GetKeyframeData().GetTrackDataItem().GetStartOffset(),e=this._playheadTime-t;this._playheadTime-=e,0!==this._overshoot&&(this._overshoot-=e),this._stoppedKeyframeDataItem=null}for(m=0;m<c;m++)this._beforeAndAfterTracks[m].AfterInterpolate();this._firstTick&&(this._firstTick=!1)}SetStoppedOnKeyframe(t){this._stoppedKeyframeDataItem=t}GetStoppedOnKeyframe(){return this._stoppedKeyframeDataItem}_Interpolate(t,e=!1,i=!1,s=!1,a=NaN,n=!1,r=!1){for(const t of this._tracks)t.BeforeInterpolate();for(const n of this._tracks){let h=t;if("number"==typeof a&&!isNaN(a)){const t=this.GetTime()-n.GetStartOffset(),e=a-n.GetStartOffset();t<0&&e>0&&(h=n.GetStartOffset(),this._SetTime(h))}n.Interpolate(h,e,i,s,this._firstTick,r)}for(const t of this._tracks)t.AfterInterpolate();this._firstTick&&n&&(this._firstTick=!1)}AddTrack(){const t=this._timelineDataItem.GetTrackData().AddEmptyTrackDataItem(),e=C3.TrackState.Create(this,t);return this._tracksLength=this._tracks.push(e),e}Removed(){if(!this.IsReleased())for(const t of this._tracks)t.TimelineRemoved()}CleanCaches(){for(const t of this._tracks)t.CleanCaches()}ClearTrackInstances(){for(const t of this._tracks)t.ClearInstance()}SetTrackInstance(t,e,i){if(e){if("number"==typeof i&&i>=0){const t=this._tracks[i];if(!t)return;return t.SetInstance(e),void this._timelineManager.SetTimelineObjectClassToMap(e.GetObjectClass(),this)}for(const i of this._tracks)if(i.IsInstanceTrack()){if(t){if(i.GetId()!==t)continue;i.SetInstance(e),this._timelineManager.SetTimelineObjectClassToMap(e.GetObjectClass(),this);break}if(!i.HasInstance()){i.SetInstance(e),this._timelineManager.SetTimelineObjectClassToMap(e.GetObjectClass(),this);break}}}}HasTrackInstance(t,e){for(const i of this._tracks)if(i.IsInstanceTrack())if(e){if(e===i.GetId()&&t===i.GetInstance())return!0}else if(t===i.GetInstance())return!0;return!1}HasValidTracks(){return this._tracks.some((t=>!t.IsInstanceTrack()||t.CanInstanceBeValid()))}HasValidGlobalTracks(){return this._tracks.some((t=>{if(t.IsInstanceTrack()){if(!t.CanInstanceBeValid())return!1;const e=t.GetObjectClass();return!!e&&e.IsGlobal()}return!1}))}GetPropertyTrack(t){for(const e of this.GetTracks())for(const i of e.GetPropertyTracks())if(i.GetPropertyName()===t)return i}GetTrackFromInstance(t){for(const e of this._tracks)if(t===e.GetInstance())return e;return null}GetKeyframeWithTags(t){let e=t?t.split(" "):[];const i=new Set(e.map((t=>t.toLowerCase().trim())));e=[...i.values()];for(const t of this.GetTracks())for(const i of t.GetKeyframeDataItems()){if(e.every((t=>i.HasTag(t))))return i}}GetObjectClasses(){const t=[];for(const e of this.GetTracks())t.push(e.GetObjectClass());return t.filter((t=>t))}_OnAfterLoad(){for(const t of this.GetTracks())t._OnAfterLoad()}_SaveToJson(){return{"tracksJson":this._SaveTracksToJson(),"name":this._name,"playheadTime":this.GetTime(),"playbackRate":this._playbackRate,"pingPongState":this._pingPongState,"resumePingPongState":this._resumePingPongState,"currentRepeatCount":this._currentRepeatCount,"isPlaying":this._isPlaying,"isScheduled":this._isScheduled,"initialStateSet":this._initialStateSet,"finishedTriggers":this._finishedTriggers,"complete":this._complete,"released":this._released,"markedForRemoval":this._markedForRemoval,"completedTick":this._completedTick,"implicitPause":this._implicitPause,"isTemplate":this._isTemplate,"tags":this._tags.join(" "),"stringTags":this._stringTags,"tagsChanged":this._tagsChanged,"firstTick":this._firstTick}}_LoadFromJson(t){t&&(this._LoadTracksFromJson(t["tracksJson"]),this._name=t["name"],this._playheadTime=t["playheadTime"],this._playbackRate=t["playbackRate"],this._pingPongState=t["pingPongState"],this._resumePingPongState=t.hasOwnProperty("resumePingPongState")?t["resumePingPongState"]:-1,this._currentRepeatCount=t["currentRepeatCount"],this._isPlaying=!!t["isPlaying"],this._isScheduled=!!t["isScheduled"],this._initialStateSet=!!t["initialStateSet"],this._finishedTriggers=!!t.hasOwnProperty("finishedTriggers")&&!!t["finishedTriggers"],this._complete=!!t["complete"],this._released=!!t["released"],this._markedForRemoval=!!t["markedForRemoval"],this._completedTick=t["completedTick"],this._implicitPause=!!t["implicitPause"],this._isTemplate=!!t["isTemplate"],this._tags=t["tags"].split(" "),this._stringTags=t["stringTags"],this._tagsChanged=!!t["tagsChanged"],this._firstTick=!!t["firstTick"])}_SaveTracksToJson(){return this._tracks.map((t=>t._SaveToJson()))}_LoadTracksFromJson(t){this.ClearTrackInstances(),t.forEach(((t,e)=>{this._tracks[e]._LoadFromJson(t)})),this._tracks.filter((t=>t.CanInstanceBeValid()))}static _HasTag(t){const e=this.GetTags();return""===t?1===e.length&&""===e[0]:e.map((t=>t.toLowerCase())).includes(t.toLowerCase())}static _GetTagArray(t){if(C3.IsArray(t))return t.slice(0);if(C3.IsString(t))return t.split(" ");throw new Error("invalid tags")}GetITimelineState(){return this._iTimelineState||(this._iTimelineState=C3.New(self.ITimelineState,this)),this._iTimelineState}};
}

// timelines/state/trackState.js
{
const C3=self.C3,INSTANCE_TRACK=0,VALUE_TRACK=1,AUDIO_TRACK=2;C3.TrackState=class extends C3.DefendedBase{constructor(t,e){super(),this._timeline=t,this._trackDataItem=e,this._trackData=e.GetTrackData(),this._instanceUid=NaN,this._objectClassIndex=NaN,this._instance=null,this._worldInfo=null,this._cleared=!1,this._isNested=e.GetStartOffset()>0,this._initialStateOfNestedSet=!1,this._endStateOfNestedSet=!1,this._instanceUidToLoad=NaN,this._lastKeyframeDataItem=null,this._keyframeDataItems=this._trackDataItem.GetKeyframeData().GetKeyframeDataItemArray(),this._propertyTracks=[],this.CreatePropertyTrackStates(),this._worldInfoChange=0,this._renderChange=0,this._needsBeforeAndAfter=0}static Create(t,e){return C3.New(C3.TrackState,t,e)}Release(){this._keyframeDataItems=null;for(const t of this._propertyTracks)t.Release();C3.clearArray(this._propertyTracks),this._propertyTracks=null,this._timeline=null,this._instance=null,this._worldInfo=null,this._trackDataItem=null,this._lastKeyframeDataItem=null}CreatePropertyTrackStates(){for(const t of this._trackDataItem.GetPropertyTrackData().propertyTrackDataItems())this._propertyTracks.push(C3.PropertyTrackState.Create(this,t))}TimelineRemoved(){for(const t of this._propertyTracks)t.TimelineRemoved()}CleanCaches(){for(const t of this._propertyTracks)t.CleanCaches();this._instance=null,this._worldInfo=null}GetTimeline(){return this._timeline}GetRuntime(){return this._timeline.GetRuntime()}GetKeyframeDataItems(){return this._keyframeDataItems||(this._keyframeDataItems=this._trackDataItem.GetKeyframeData().GetKeyframeDataItemArray()),this._keyframeDataItems}GetPropertyTracks(){return this._propertyTracks}GetPropertyTrack(t){for(let e=0;e<this._propertyTracks.length;e++){const a=this._propertyTracks[e];if(a.GetPropertyName()===t)return a}}MaybeGetInstance(){this._instance||this.GetInstance()}IsInstanceValid(){return!!this._instance&&!this._instance.IsDestroyed()}CanInstanceBeValid(){if(!this.IsInstanceTrack())return!1;const t=this.GetInstanceUID(),e=this.GetRuntime().GetInstanceByUID(t);return!!e&&!e.IsDestroyed()}GetObjectClass(){if(!this.IsInstanceTrack())return;const t=this.GetObjectClassIndex();return-1!==t?this.GetRuntime().GetObjectClassByIndex(t):void 0}GetTrackIndexInTimeline(){return this._timeline.GetTracks().indexOf(this)}ClearInstance(){this._instance=null,this._instanceUid=NaN,this._worldInfo=null,this._objectClassIndex=NaN,this._cleared=!0}HasInstance(){return!!this._instance}GetInstance(){if(this._cleared)return;if(this._instance&&this.IsInstanceValid())return this._instance;const t=this.GetInstanceUID();return this._instance=this.GetRuntime().GetInstanceByUID(t),this._instance}SetInstance(t){if(this._cleared=!1,this._instance!==t){this.CleanCaches(),this._instance=t,this._objectClassIndex=t.GetObjectClass().GetIndex(),this._instanceUid=t.GetUID(),this._worldInfo=t.GetWorldInfo();for(const e of this.propertyTrackItems()){const a=e.propertyTrack,s=e.sourceAdapter;switch(a.GetSourceAdapterId()){case"instance-variable":{s.GetEditorIndex();const a=t.GetObjectClass(),r=a.GetInstanceVariableIndexByName(e.name),i=a.GetInstanceVariableName(r),n=a.GetInstanceVariableType(r);i===e.name&&n===e.type&&s.UpdateInstanceVariableIndex(r);break}case"behavior":{const a=e.behaviorType,r=this.GetObjectClass(),i=t.GetObjectClass(),n=s.GetBehaviorType(i);if(a&&n){const t=a.GetName();r.GetBehaviorIndexByName(t),i.GetBehaviorIndexByName(t),s.GetEditorIndex();s.UpdateBehaviorTypeSid(n.GetSID())}break}}}}}*propertyTrackItems(){for(const t of this._propertyTracks){const e=t.GetSourceAdapter(),a=this.GetObjectClass(),s={propertyTrack:t,sourceAdapter:e};switch(t.GetSourceAdapterId()){case"world-instance":s.property=t.GetPropertyName();break;case"instance-variable":{const t=e.GetEditorIndex();s.name=a.GetInstanceVariableName(t),s.type=a.GetInstanceVariableType(t);break}case"effect":{const t=a.GetEffectList(),r=e.GetEffectType(t);s.effectType=r;break}case"behavior":{const t=e.GetBehaviorType(a);s.behaviorType=t;break}case"plugin":s.plugin=a.GetPlugin()}yield s}}GetWorldInfo(){if(this._worldInfo&&this.IsInstanceValid())return this._worldInfo;const t=this.GetInstance();return t&&(this._worldInfo=t.GetWorldInfo()),this._worldInfo}GetTrackDataItem(){return this._trackDataItem}GetInstanceUID(){return isNaN(this._instanceUid)?this._trackDataItem.GetInstanceUID():this._instanceUid}SetInstanceUID(t){this._trackDataItem.SetInstanceUID(t)}GetInterpolationMode(){return this._trackDataItem.GetInterpolationMode()}SetInterpolationMode(t){this._trackDataItem.SetInterpolationMode(t)}GetResultMode(){return this._trackDataItem.GetResultMode()}GetId(){return this._trackDataItem.GetId()}GetStartOffset(){return this._trackDataItem.GetStartOffset()}GetLocalTotalTime(){return this._trackDataItem.GetLocalTotalTime()}SetLocalTotalTime(t){this._trackDataItem.SetLocalTotalTime(t)}SetResultMode(t){this._trackDataItem.SetResultMode(t)}SetEase(t){for(const e of this.GetKeyframeDataItems())e.SetEase(t);for(const e of this.GetPropertyTracks())e.SetEase(t)}GetEnable(){return this._trackDataItem.GetEnable()}SetEnable(t){this._trackDataItem.SetEnable(t)}GetObjectClassIndex(){return isNaN(this._objectClassIndex)?this._trackDataItem.GetObjectClassIndex():this._objectClassIndex}SetObjectClassIndex(t){this._trackDataItem.SetObjectClassIndex(t)}SetOriginalWidth(t){this._trackDataItem.SetOriginalWidth(t)}GetOriginalWidth(){const t=this.GetInstance();if(t){if(t.GetSdkInstance().IsOriginalSizeKnown())return t.GetSdkInstance().GetOriginalWidth()}return this._trackDataItem.GetOriginalWidth()}SetOriginalHeight(t){this._trackDataItem.SetOriginalHeight(t)}GetOriginalHeight(){const t=this.GetInstance();if(t){if(t.GetSdkInstance().IsOriginalSizeKnown())return t.GetSdkInstance().GetOriginalHeight()}return this._trackDataItem.GetOriginalHeight()}GetType(){return this._trackDataItem.GetType()}GetName(){return this._trackDataItem.GetName()}IsInstanceTrack(){return 0===this.GetType()}IsValueTrack(){return 1===this.GetType()}IsAudioTrack(){return 2===this.GetType()}GetWorldInfoChange(){return this._worldInfoChange}GetRenderChange(){return this._renderChange}GetNeedsBeforeAndAfter(){return this._needsBeforeAndAfter}IsNested(){return this._isNested}SetResetState(){for(const t of this._propertyTracks)t.SetResetState()}SetInitialState(){if(this.MaybeGetInstance(),!this.IsInstanceValid()&&this.IsInstanceTrack())return;const t=this.GetTimeline().IsForwardPlayBack(),e=t?0:this.GetLocalTotalTime();for(const t of this._propertyTracks)t.SetInitialState(e),0===this._worldInfoChange&&1===t.GetWorldInfoChange()&&(this._worldInfoChange=1),0===this._renderChange&&1===t.GetRenderChange()&&(this._renderChange=1);this._needsBeforeAndAfter=0;this._propertyTracks.some((t=>t.GetNeedsBeforeAndAfter()))&&(this._needsBeforeAndAfter=1),this._lastKeyframeDataItem=t?this._GetLastKeyFrameBeforeTime(e):this._GetFirstKeyFrameAfterTime(e),this._initialStateOfNestedSet=!1,this._endStateOfNestedSet=!1,this.Interpolate(e),this.OnInitialKeyframeReached(this._lastKeyframeDataItem)}SetResumeState(){if(this.MaybeGetInstance(),!this.IsInstanceValid()&&this.IsInstanceTrack())return;const t=this._timeline.IsForwardPlayBack(),e=this._timeline.GetTime()-this.GetStartOffset();this._lastKeyframeDataItem=t?this._GetLastKeyFrameBeforeTime(e):this._GetFirstKeyFrameAfterTime(e);for(const t of this._propertyTracks)t.SetResumeState(e)}SetEndState(){if(!this.GetTimeline().IsComplete()&&(this.MaybeGetInstance(),(this.IsInstanceValid()||!this.IsInstanceTrack())&&!this._isNested)){const t=this._timeline.GetTime();t>=this.GetStartOffset()+this.GetLocalTotalTime()?this.Interpolate(this.GetLocalTotalTime(),!0,!1,!0,!1,!1,!0):t<=0&&this.Interpolate(0,!0,!1,!0,!1,!1,!0)}}_SetUpdateState(){for(let t=0,e=this._propertyTracks.length;t<e;t++){const e=this._propertyTracks[t];e._SetUpdateState(),0===this._worldInfoChange&&1===e.GetWorldInfoChange()&&(this._worldInfoChange=1),0===this._renderChange&&1===e.GetRenderChange()&&(this._renderChange=1)}}BeforeInterpolate(){const t=this._propertyTracks.length;for(let e=0;e<t;e++)this._propertyTracks[e].BeforeInterpolate()}Interpolate(t,e=!1,a=!1,s=!1,r=!1,i=!1,n=!1){this._instance||this.GetInstance();const o=this._instance&&!this._instance.IsDestroyed(),h=0===this._trackDataItem._type;if((o||!h)&&!(i&&h&&this.GetObjectClass().IsGlobal()||(t-=this.GetStartOffset())<0)){this.MaybeSetInitialStateOfNestedTrack(t,e),this.MaybeTriggerKeyframeReachedConditions(t,e,r),!this.GetTimeline().IsPlaying()&&this.GetTimeline().GetStoppedOnKeyframe()&&(t=this.GetTimeline().GetStoppedOnKeyframe().GetTime());for(let e=0,r=this._propertyTracks.length;e<r;e++)this._propertyTracks[e].Interpolate(t,a,s,n);this.MaybeSetEndStateOfNestedTrack(t,e),0!==this._worldInfoChange&&(this._worldInfo||(this._worldInfo=this._instance.GetWorldInfo()),this._worldInfo&&this._worldInfo.SetBboxChanged())}}AfterInterpolate(){const t=this._propertyTracks.length;for(let e=0;e<t;e++)this._propertyTracks[e].AfterInterpolate()}MaybeSetInitialStateOfNestedTrack(t,e){if(!e)return;if(!this._isNested)return;if(this._initialStateOfNestedSet)return;if(this.GetTimeline().IsForwardPlayBack()){if(t<0)return}else if(t>this.GetLocalTotalTime())return;for(const t of this._propertyTracks)t.SetInitialState();this._initialStateOfNestedSet=!0}MaybeSetEndStateOfNestedTrack(t,e){if(!e)return;if(!this._isNested)return;if(this._endStateOfNestedSet)return;if(this.GetTimeline().IsForwardPlayBack()){if(t>=this.GetLocalTotalTime()){for(const t of this._propertyTracks)t.Interpolate(this.GetLocalTotalTime(),!1,!0);this._endStateOfNestedSet=!0}}else if(t<=0){for(const t of this._propertyTracks)t.Interpolate(0,!1,!0);this._endStateOfNestedSet=!0}}MaybeTriggerKeyframeReachedConditions(t,e,a){if(a)return;if(!e)return;if(!C3.Plugins.Timeline)return;const s=this.GetTimeline();if(s.IsForwardPlayBack()){const e=this._lastKeyframeDataItem.GetNext(),a=this._lastKeyframeDataItem.GetTime(),r=e?e.GetTime():s.GetTotalTime();(t<=a||t>=r)&&(this._lastKeyframeDataItem=this._trackData.GetFirstKeyFrameDataItemLowerOrEqualThan(t,this._trackDataItem),e&&this.OnKeyframeReached(this._lastKeyframeDataItem))}else{if(!this._trackData.GetFirstKeyFrameDataItemHigherOrEqualThan(t,this._trackDataItem))return;this._lastKeyframeDataItem||(this._lastKeyframeDataItem=this._trackData.GetFirstKeyFrameDataItemHigherOrEqualThan(t,this._trackDataItem));const e=this._lastKeyframeDataItem.GetLast(),a=this._lastKeyframeDataItem.GetTime(),s=e?e.GetTime():0;(t>=a||t<=s)&&(this._lastKeyframeDataItem=this._trackData.GetFirstKeyFrameDataItemHigherOrEqualThan(t,this._trackDataItem),this._lastKeyframeDataItem&&this.OnKeyframeReached(this._lastKeyframeDataItem))}}_GetLastKeyFrameBeforeTime(t){const e=this._trackData.GetKeyFrameDataItemAtTime(t,this._trackDataItem);return e||this._trackData.GetFirstKeyFrameDataItemLowerOrEqualThan(t,this._trackDataItem)}_GetFirstKeyFrameAfterTime(t){const e=this._trackData.GetKeyFrameDataItemAtTime(t,this._trackDataItem);return e||this._trackData.GetFirstKeyFrameDataItemHigherOrEqualThan(t,this._trackDataItem)}OnKeyframeReached(t,e=!1){if(!C3.Plugins.Timeline)return;const a=this.GetTimeline(),s=a.GetTimelineManager();C3.Plugins.Timeline.Cnds.PushTriggerTimeline(a),C3.Plugins.Timeline.Cnds.PushTriggerKeyframe(t),s.Trigger(C3.Plugins.Timeline.Cnds.OnAnyKeyframeReached),s.Trigger(C3.Plugins.Timeline.Cnds.OnKeyframeReached),a.IsPlaying()||e||a.SetStoppedOnKeyframe(t),C3.Plugins.Timeline.Cnds.PopTriggerTimeline(a),C3.Plugins.Timeline.Cnds.PopTriggerKeyframe(t)}OnInitialKeyframeReached(t){this.OnKeyframeReached(t,!0)}AddKeyframe(){return this._trackDataItem.GetKeyframeData().AddEmptyKeyframeDataItem()}AddPropertyTrack(){const t=this._trackDataItem.GetPropertyTrackData().AddEmptyPropertyTrackDataItem(),e=C3.PropertyTrackState.Create(this,t);return this._propertyTracks.push(e),e}DeleteKeyframes(t){this._trackDataItem.GetKeyframeData().DeleteKeyframeDataItems(t)}DeletePropertyKeyframes(t){for(const e of this._propertyTracks)e.DeletePropertyKeyframes(t)}SaveState(){for(const t of this._propertyTracks)t.SaveState()}CompareInitialStateWithCurrent(){if(this.MaybeGetInstance(),this.IsInstanceValid()||!this.IsInstanceTrack())for(const t of this._propertyTracks)t.CompareInitialStateWithCurrent()}CompareSaveStateWithCurrent(){if(this.MaybeGetInstance(),!this.IsInstanceValid()&&this.IsInstanceTrack())return;let t=!1;for(const e of this._propertyTracks){const a=e.CompareSaveStateWithCurrent();!t&&a&&(t=!0)}if(t){const t=this.AddKeyframe();t.SetTime(this.GetTimeline().GetTime()),t.SetEase("noease"),t.SetEnable(!0),t.SetTags("")}}_OnAfterLoad(){isNaN(this._instanceUidToLoad)||this._LoadInstanceFromJson(this._instanceUidToLoad),this._instanceUidToLoad=NaN}_SaveToJson(){const t=this.GetInstance(),e=t?t.GetUID():this.GetInstanceUID();return{"propertyTracksJson":this._SavePropertyTracksToJson(),"lastKeyframeDataItemJson":this._SaveLastKeyframeDataItemToJson(),"initialStateOfNestedSet":this._initialStateOfNestedSet,"endStateOfNestedSet":this._endStateOfNestedSet,"instanceUid":e,"cleared":this._cleared}}_LoadFromJson(t){if(t){this._LoadPropertyTracksFromJson(t["propertyTracksJson"]),this._LoadLastKeyframeDataItemFromJson(t["lastKeyframeDataItemJson"]),this._instanceUidToLoad=t["instanceUid"],this._initialStateOfNestedSet=!1,t.hasOwnProperty["initialStateOfNestedSet"]&&(this._initialStateOfNestedSet=t["initialStateOfNestedSet"]),this._endStateOfNestedSet=!1,t.hasOwnProperty["endStateOfNestedSet"]&&(this._endStateOfNestedSet=t["endStateOfNestedSet"]),this._cleared=!!t.hasOwnProperty("cleared")&&t["cleared"];for(const t of this._propertyTracks)0===this._worldInfoChange&&1===t.GetWorldInfoChange()&&(this._worldInfoChange=1),0===this._renderChange&&1===t.GetRenderChange()&&(this._renderChange=1);this._needsBeforeAndAfter=0,this._propertyTracks.some((t=>t.GetNeedsBeforeAndAfter()))&&(this._needsBeforeAndAfter=1)}}_SaveLastKeyframeDataItemToJson(){return this._trackDataItem.GetKeyframeData().GetKeyframeDataItemIndex(this._lastKeyframeDataItem)}_SavePropertyTracksToJson(){return this._propertyTracks.map((t=>t._SaveToJson()))}_LoadPropertyTracksFromJson(t){t.forEach(((t,e)=>{this._propertyTracks[e]._LoadFromJson(t)}))}_LoadInstanceFromJson(t){if(!C3.IsFiniteNumber(t))return;const e=this.GetRuntime().GetInstanceByUID(t);if(!e)return;this.GetTimeline().SetTrackInstance(this._trackDataItem.GetId(),e,this.GetTrackIndexInTimeline())}_LoadLastKeyframeDataItemFromJson(t){const e=this._trackDataItem.GetKeyframeData();this._lastKeyframeDataItem=e.GetKeyframeDataItemFromIndex(t)}};
}

// timelines/state/propertyTrackState.js
{
const C3=self.C3;C3.PropertyTrackState=class extends C3.DefendedBase{constructor(e,t){super(),this._track=e,this._propertyTrackDataItem=t,this._propertyTrackData=t.GetPropertyTrackData(),this._worldInfoChange=0,this._renderChange=0,this._needsBeforeAndAfter=0,this._sourceAdapter=this.GetSourceAdapter(),this._propertyKeyframeDataItems=this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),this._lastPropertyKeyframeDataItem=null,this._absoluteValueObject=null}static Create(e,t){return C3.New(C3.PropertyTrackState,e,t)}Release(){this._track=null,this._sourceAdapter&&(this._sourceAdapter.Release(),this._sourceAdapter=null),this._propertyKeyframeDataItems=null,this._propertyTrackDataItem=null,this._propertyTrackData=null}GetWorldInfoChange(){return this._worldInfoChange}GetRenderChange(){return this._renderChange}GetNeedsBeforeAndAfter(){return this._needsBeforeAndAfter}HasAbsoluteValueObject(){return!!this._absoluteValueObject}SetAbsoluteValueObject(e){this._absoluteValueObject=e}GetAbsoluteValueObject(){return this._absoluteValueObject}GetTrack(){return this._track}GetPropertyTrackDataItem(){return this._propertyTrackDataItem}GetPropertyTrackData(){return this._propertyTrackData}GetTimeline(){return this._track.GetTimeline()}GetRuntime(){return this._track.GetRuntime()}GetInstance(){return this._track.GetInstance()}GetSourceAdapter(){if(this._sourceAdapter)return this._sourceAdapter;let e;switch(this._propertyTrackDataItem.GetSourceAdapterId()){case"behavior":e=new C3.PropertyTrackState.BehaviorSourceAdapter(this);break;case"effect":e=new C3.PropertyTrackState.EffectSourceAdapter(this),this._renderChange=1;break;case"instance-variable":e=new C3.PropertyTrackState.InstanceVariableSourceAdapter(this);break;case"plugin":e=new C3.PropertyTrackState.PluginSourceAdapter(this),this._renderChange=1;break;case"world-instance":e=new C3.PropertyTrackState.PropertySourceAdapter(this),this._renderChange=1,this._worldInfoChange=1;break;case"value":e=new C3.PropertyTrackState.ValueSourceAdapter(this);break;case"audio":e=new C3.PropertyTrackState.AudioSourceAdapter(this)}return this._sourceAdapter=e,this._sourceAdapter}GetSourceAdapterId(){return this._propertyTrackDataItem.GetSourceAdapterId()}SetSourceAdapterId(e){this._propertyTrackDataItem.SetSourceAdapterId(e)}GetSourceAdapterArgs(){return this._propertyTrackDataItem.GetSourceAdapterArguments()}SetSourceAdapterArgs(e){this._propertyTrackDataItem.SetSourceAdapterArguments(e)}GetSourceAdapterValue(){return this.GetSourceAdapter().GetValue()}GetPropertyName(){return this._propertyTrackDataItem.GetProperty()}SetPropertyName(e){this._propertyTrackDataItem.SetProperty(e)}GetPropertyType(){return this._propertyTrackDataItem.GetType()}SetPropertyType(e){this._propertyTrackDataItem.SetType(e)}GetPropertyKeyframeType(){return this.GetPropertyTrackData().GetFirstPropertyKeyframeDataItem(this._propertyTrackDataItem).GetType()}GetMin(){return this._propertyTrackDataItem.GetMin()}SetMin(e){this._propertyTrackDataItem.SetMin(e)}GetMax(){return this._propertyTrackDataItem.GetMax()}SetMax(e){this._propertyTrackDataItem.SetMax(e)}GetEnable(){return this._propertyTrackDataItem.GetEnable()}SetEnable(e){this._propertyTrackDataItem.SetEnable(e)}GetInterpolationMode(){return this._propertyTrackDataItem.GetInterpolationMode()}SetInterpolationMode(e){this._propertyTrackDataItem.SetInterpolationMode(e)}GetResultMode(){return this._propertyTrackDataItem.GetResultMode()}SetResultMode(e){this._propertyTrackDataItem.SetResultMode(e)}SetEase(e){for(const t of this.GetPropertyKeyframeDataItems())t.SetEase(e)}CanHavePropertyKeyframes(){return this._propertyTrackDataItem.CanHavePropertyKeyframes()}GetPropertyKeyframeDataItems(){return this._propertyKeyframeDataItems||(this._propertyKeyframeDataItems=this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray()),this._propertyKeyframeDataItems}GetPropertyKeyframeDataItemArrayIncludingDisabled(){return this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArrayIncludingDisabled()}GetPropertyKeyFrameDataItemAtTime(e){return this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(e,this._propertyTrackDataItem)}GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e){return this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem)}GetPropertyKeyframeDataItemPairForTime(e){let t,r=this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(e,this._propertyTrackDataItem);return r?t=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherThan(e,this._propertyTrackDataItem):(r=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem),t=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(e,this._propertyTrackDataItem)),{start:r,end:t}}*GetPropertyKeyframeValues(){for(const e of this.GetPropertyKeyframeDataItems())yield e.GetValueWithResultMode()}*GetPropertyKeyframeTimes(){for(const e of this.GetPropertyKeyframeDataItems())yield e.GetTime()}TimelineRemoved(){this.GetSourceAdapter().TimelineRemoved()}CleanCaches(){this.GetSourceAdapter().CleanCaches()}GetCurrentState(){return this.GetSourceAdapter().GetCurrentState()}SetResetState(){this.GetSourceAdapter().SetResetState()}SetInitialState(e){this.GetSourceAdapter().SetInitialState(),this._lastPropertyKeyframeDataItem=this._GetLastPropertyKeyFrameBeforeTime(e),this._SetUpdateState()}SetResumeState(e){this.GetSourceAdapter().SetResumeState(),this._lastPropertyKeyframeDataItem=this._GetLastPropertyKeyFrameBeforeTime(e)}_SetUpdateState(){const e=this.GetTrack();if(this._needsBeforeAndAfter=0,e.IsInstanceTrack()){const t=this.GetTimeline(),r=e.GetInstance(),a=this.GetSourceAdapter(),o=this.GetPropertyName();if(a.MayNeedBeforeAndAfterInterpolate()){const e=t.GetSimilarPropertyTracks(r,a,o,this);e&&e.length&&(this._needsBeforeAndAfter=1)}else this._needsBeforeAndAfter=0}}_GetLastPropertyKeyFrameBeforeTime(e){const t=this.GetTimeline(),r=this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(e,this._propertyTrackDataItem);return r||(t.IsForwardPlayBack()?this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem):this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(e,this._propertyTrackDataItem))}BeforeInterpolate(){this._sourceAdapter.BeforeInterpolate()}Interpolate(e,t=!1,r=!1,a=!1){let o,s,p=!1;if(t)o=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem);else{if(this._lastPropertyKeyframeDataItem){const t=this.GetTimeline(),r=this._lastPropertyKeyframeDataItem.GetNext(),a=this._lastPropertyKeyframeDataItem.GetTime(),o=r?r.GetTime():t.GetTotalTime();(e<=a||e>=o)&&(this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem),p=!0)}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem),p=!0;o=this._lastPropertyKeyframeDataItem}o&&(s=o.GetNext()),this._sourceAdapter.Interpolate(e,o,s,t,r,a,p)}GetInterpolatedValue(e){if(this._lastPropertyKeyframeDataItem){const t=this.GetTimeline(),r=this._lastPropertyKeyframeDataItem.GetNext(),a=this._lastPropertyKeyframeDataItem.GetTime(),o=r?r.GetTime():t.GetTotalTime();(e<=a||e>=o)&&(this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem))}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem);const t=this._lastPropertyKeyframeDataItem,r=t.GetNext();return this._sourceAdapter.GetInterpolatedValue(e,t,r)}GetInterpolatedValueFast(e,t,r){return this._sourceAdapter.GetInterpolatedValue(e,t,r)}AfterInterpolate(){this._sourceAdapter.AfterInterpolate()}static GetStartPropertyKeyframeForTime(e,t){const r=t.GetPropertyTrackDataItem();return t._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,r)}static GetEndPropertyKeyframeForTime(e,t){const r=t.GetPropertyTrackDataItem();return t._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(e,r)}AddPropertyKeyframe(){const e=this._propertyTrackDataItem.GetPropertyKeyframeData().AddEmptyPropertyKeyframeDataItem();return this._lastPropertyKeyframeDataItem=null,e}DeletePropertyKeyframes(e){this._lastPropertyKeyframeDataItem=null;this._propertyTrackDataItem.GetPropertyKeyframeData().DeletePropertyKeyframeDataItems(e)}SaveState(){this.GetSourceAdapter().SaveState()}CompareInitialStateWithCurrent(){if(this.GetSourceAdapter().CompareInitialStateWithCurrent()){const e=this._propertyTrackData.GetFirstPropertyKeyframeDataItem(this._propertyTrackDataItem),t=this.GetSourceAdapter().GetCurrentState();e.SetAbsoluteValue(t)}}CompareSaveStateWithCurrent(){const e=this.GetSourceAdapter().CompareSaveStateWithCurrent();return e&&this.AddPropertyKeyframeAtCurrentTime(),this.GetSourceAdapter().ClearSaveState(),e}AddPropertyKeyframeAtCurrentTime(){const e=this.GetTimeline().GetTime(),t=this.GetSourceAdapter(),r=C3.PropertyTrackState.GetStartPropertyKeyframeForTime(e,this),a=this.AddPropertyKeyframe();a.SetType(r.GetType()),a.SetTime(e),a.SetEase(r.GetEase()),a.SetEnable(!0),a.SetValue(t.GetValueAtTime()),a.SetAbsoluteValue(t.GetCurrentState())}_SaveToJson(){return{"sourceAdapterJson":this.GetSourceAdapter()._SaveToJson()}}_LoadFromJson(e){e&&this.GetSourceAdapter()._LoadFromJson(e["sourceAdapterJson"])}};
}

// timelines/state/propertySourceAdapters/propertySourceAdapter.js
{
const C3=self.C3,NS=C3.PropertyTrackState;NS.PropertySourceAdapter=class{constructor(e){this._propertyTrack=e,this._propertyAdapter=null,this.GetPropertyAdapter()}Release(){this._propertyAdapter&&(this._propertyAdapter.Release(),this._propertyAdapter=null),this._propertyTrack=null}MayNeedBeforeAndAfterInterpolate(){return this._propertyAdapter.MayNeedBeforeAndAfterInterpolate()}GetPropertyTrack(){return this._propertyTrack}TimelineRemoved(){this._propertyAdapter&&this._propertyAdapter.TimelineRemoved()}CleanCaches(){this._propertyAdapter&&this._propertyAdapter.CleanCaches()}GetPropertyAdapter(){return this._propertyAdapter||(this._propertyAdapter=this._CreatePropertyAdapter()),this._propertyAdapter}GetEditorIndex(){}GetIndex(){return this.GetEditorIndex()}GetTarget(){}SetResetState(){this.GetPropertyAdapter().SetResetState()}SetInitialState(){this.GetPropertyAdapter().SetInitialState()}SetResumeState(){this.GetPropertyAdapter().SetResumeState()}BeforeInterpolate(){this._propertyAdapter.BeforeChangeProperty()}Interpolate(e,t,r,p,a,o,n){let s;switch(this._propertyTrack.GetPropertyKeyframeType()){case"numeric":s=NS.NumericTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"angle":s=NS.AngleTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"boolean":s=NS.BooleanTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"color":s=NS.ColorTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"text":s=NS.TextTypeAdapter.Interpolate(e,t,r,this._propertyTrack)}this._propertyAdapter.ChangeProperty(e,s,t,r,p,a,o,n)}GetInterpolatedValue(e,t,r){switch(this._propertyTrack.GetPropertyKeyframeType()){case"numeric":return NS.NumericTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"angle":return NS.AngleTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"boolean":return NS.BooleanTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"color":return NS.ColorTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"text":return NS.TextTypeAdapter.Interpolate(e,t,r,this._propertyTrack)}}AfterInterpolate(){this._propertyAdapter.AfterChangeProperty()}SaveState(){this.GetPropertyAdapter().SetSaveState()}ClearSaveState(){this.GetPropertyAdapter().ClearSaveState()}GetCurrentState(){return this.GetPropertyAdapter().GetCurrentState()}CompareInitialStateWithCurrent(){return this.GetPropertyAdapter().CompareInitialStateWithCurrent()}CompareSaveStateWithCurrent(){return this.GetPropertyAdapter().CompareSaveStateWithCurrent()}GetValueAtTime(){const e=this._propertyTrack,t=e.GetTrack().GetTimeline().GetTime(),r=NS.GetStartPropertyKeyframeForTime(t,e),p=r.GetNext();switch(e.GetPropertyKeyframeType()){case"numeric":return NS.NumericTypeAdapter.Interpolate(t,r,p,e);case"angle":return NS.AngleTypeAdapter.Interpolate(t,r,p,e);case"boolean":return NS.BooleanTypeAdapter.Interpolate(t,r,p,e);case"color":return NS.ColorTypeAdapter.Interpolate(t,r,p,e);case"text":return NS.TextTypeAdapter.Interpolate(t,r,p,e)}}_CreatePropertyAdapter(){const e=this._propertyTrack;switch(e.CanHavePropertyKeyframes()?e.GetPropertyKeyframeType():""){case"combo":case"boolean":case"text":case"string":return new NS.PropertyInterpolationAdapter.NoInterpolationAdapter(this);case"numeric":case"number":case"angle":return"combo"===this._propertyTrack.GetPropertyType()?new NS.PropertyInterpolationAdapter.NoInterpolationAdapter(this):new NS.PropertyInterpolationAdapter.NumericInterpolationAdapter(this);case"color":case"offsetColor":return new NS.PropertyInterpolationAdapter.ColorInterpolationAdapter(this);default:return new NS.PropertyInterpolationAdapter.NumericInterpolationAdapter(this)}}_SaveToJson(){return{"propertyAdapterJson":this.GetPropertyAdapter()._SaveToJson()}}_LoadFromJson(e){e&&this.GetPropertyAdapter()._LoadFromJson(e["propertyAdapterJson"])}};
}

// timelines/state/propertySourceAdapters/instanceVariableSourceAdapter.js
{
const C3=self.C3,INDEX=0;class InstanceVariableSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(e){super(e),this._updatedIndex=NaN}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0]}GetIndex(){return this._updatedIndex?this._updatedIndex:super.GetIndex()}GetTarget(){return this._propertyTrack.GetTrack().GetInstance()}UpdateInstanceVariableIndex(e){this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0]!==e&&(this._updatedIndex=e)}Interpolate(e,t,r,a,n,d,p){this.GetPropertyAdapter().CanChange(t.GetValue())&&super.Interpolate(e,t,r,a,n,d,p)}GetInterpolatedValue(e,t,r){if(this.GetPropertyAdapter().CanChange(t.GetValue()))return super.GetInterpolatedValue(e,t,r)}_SaveToJson(){return Object.assign(super._SaveToJson(),{"index":this._updatedIndex})}_LoadFromJson(e){e&&(super._LoadFromJson(e),this._updatedIndex=e["index"])}}C3.PropertyTrackState.InstanceVariableSourceAdapter=InstanceVariableSourceAdapter;
}

// timelines/state/propertySourceAdapters/behaviorSourceAdapter.js
{
const C3=self.C3,SID=0,INDEX=1,NAME=2;class BehaviorSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(e){super(e),this._sid=NaN}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[1]}GetTarget(){const e=this._propertyTrack.GetPropertyTrackDataItem(),t=this._propertyTrack.GetTrack(),r=this._sid?this._sid:e.GetSourceAdapterArguments()[0],a=t.GetInstance(),s=a.GetBehaviorIndexBySID(r);return a.GetBehaviorInstances()[s].GetSdkInstance()}GetBehaviorType(e){const t=this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[2];return e.GetBehaviorTypeByName(t)}UpdateBehaviorTypeSid(e){this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0]!==e&&(this._sid=e)}Interpolate(e,t,r,a,s,o,p){const c=this._propertyTrack.GetTrack().GetInstance();this.GetBehaviorType(c.GetObjectClass())&&super.Interpolate(e,t,r,a,s,o,p)}GetInterpolatedValue(e,t,r){const a=this._propertyTrack.GetTrack().GetInstance();if(this.GetBehaviorType(a.GetObjectClass()))return super.GetInterpolatedValue(e,t,r)}_SaveToJson(){return Object.assign(super._SaveToJson(),{"sid":this._sid})}_LoadFromJson(e){e&&(super._LoadFromJson(e),this._sid=e["sid"])}}C3.PropertyTrackState.BehaviorSourceAdapter=BehaviorSourceAdapter;
}

// timelines/state/propertySourceAdapters/effectSourceAdapter.js
{
const C3=self.C3,NAME=0,INDEX=1;class EffectSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(e){super(e)}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[1]}GetTarget(){const e=this._propertyTrack.GetTrack().GetWorldInfo().GetInstanceEffectList(),t=e.GetEffectList(),r=this.GetEffectType(t).GetIndex();return e.IsEffectIndexActive(r)?e.GetEffectParametersForIndex(r):null}GetEffectType(e){const t=this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0];return e.GetEffectTypeByName(t)}Interpolate(e,t,r,c,f,a,s){this._IsEffectActive()&&super.Interpolate(e,t,r,c,f,a,s)}GetInterpolatedValue(e,t,r){if(this._IsEffectActive())return super.GetInterpolatedValue(e,t,r)}_IsEffectActive(){const e=this._propertyTrack.GetTrack().GetWorldInfo().GetInstanceEffectList(),t=e.GetEffectList(),r=this.GetEffectType(t);if(!r)return;const c=r.GetIndex();return e.IsEffectIndexActive(c)}}C3.PropertyTrackState.EffectSourceAdapter=EffectSourceAdapter;
}

// timelines/state/propertySourceAdapters/pluginSourceAdapter.js
{
const C3=self.C3,INDEX=0;class PluginSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(t){super(t)}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0]}GetTarget(){return this._propertyTrack.GetTrack().GetInstance().GetSdkInstance()}Interpolate(t,e,r,n,a,i,s){const c=this._propertyTrack.GetTrack();c.GetObjectClass().GetPlugin()===c.GetInstance().GetObjectClass().GetPlugin()&&super.Interpolate(t,e,r,n,a,i,s)}GetInterpolatedValue(t,e,r){const n=this._propertyTrack.GetTrack();if(n.GetObjectClass().GetPlugin()===n.GetInstance().GetObjectClass().GetPlugin())return super.GetInterpolatedValue(t,e,r)}GetOptionalCallbacks(){const t=this._propertyTrack.GetTrack(),e=t.GetObjectClass().GetPlugin();if(C3.Plugins.Sprite&&e instanceof C3.Plugins.Sprite&&("initial-frame"===this._propertyTrack.GetPropertyName()||"initial-animation"===this._propertyTrack.GetPropertyName()))switch(this._propertyTrack.GetResultMode()){case"relative":return{onFrameChange:(e,r,n,a,i)=>{if(r!==a){const n=a/r,i=t.GetPropertyTrack("offsetWidth"),s=t.GetPropertyTrack("offsetScaleX");if(i||s){const c=i?.GetSourceAdapter()?.GetPropertyAdapter(),o=s?.GetSourceAdapter()?.GetPropertyAdapter();if(e.HasParent()&&e.GetTransformWithParentWidth())o&&o.SetOriginalSizeProperty(a),e.SetWidth(this.GetNewWidth(a,r,e,t,c,o));else{const r=a*((e._GetSceneGraphInfo()?._GetStartWidth()??this.GetInstanceOriginalWidth(e,t))/this.GetInstanceOriginalWidth(e,t));o&&o.SetOriginalSizeProperty(a);const i=c?.GetChangeAccumulatorProperty()??0,s=o?.GetChangeAccumulatorProperty()??0;e.SetWidth(r+(i+s*n))}}else e.SetWidth(e.GetWidth()*n)}if(n!==i){const r=i/n,a=t.GetPropertyTrack("offsetHeight"),s=t.GetPropertyTrack("offsetScaleY");if(a||s){const c=a?.GetSourceAdapter()?.GetPropertyAdapter(),o=s?.GetSourceAdapter()?.GetPropertyAdapter();if(e.HasParent()&&e.GetTransformWithParentHeight())o&&o.SetOriginalSizeProperty(i),e.SetHeight(this.GetNewHeight(i,n,e,t,c,o));else{const n=i*((e._GetSceneGraphInfo()?._GetStartHeight()??this.GetInstanceOriginalHeight(e,t))/this.GetInstanceOriginalHeight(e,t));o&&o.SetOriginalSizeProperty(i);const a=c?.GetChangeAccumulatorProperty()??0,s=o?.GetChangeAccumulatorProperty()??0;e.SetHeight(n+(a+s*r))}}else e.SetHeight(e.GetHeight()*r)}}};case"absolute":return null}}GetLastPropertyKeyframeValue(t,e,r,n=0){const a=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(!a)return n;const i=a.GetPropertyTrack(r);if(!i)return n;const s=i.GetPropertyTrackDataItem().GetPropertyKeyframeData();if(!s)return n;const c=s.GetLastPropertyKeyframeDataItem();return c?c.GetValue():n}GetInstanceOriginalWidth(t,e){const r=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(r)return r.GetOriginalWidth();const n=t.GetInstance().GetSdkInstance();return n.IsOriginalSizeKnown()?n.GetOriginalWidth():t._GetSceneGraphInfo()._GetStartWidth()}GetInstanceOriginalHeight(t,e){const r=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(r)return r.GetOriginalHeight();const n=t.GetInstance().GetSdkInstance();return n.IsOriginalSizeKnown()?n.GetOriginalHeight():t._GetSceneGraphInfo()._GetStartHeight()}GetNewWidth(t,e,r,n,a,i){const s=r._GetSceneGraphInfo()._GetStartWidth(),c=s/r.GetParent()._GetSceneGraphInfo()._GetStartWidth();let o=1;const G=i?.GetAbsoluteScaleXOffsetProperty()??0;if(0!==G){const t=s/this.GetInstanceOriginalWidth(r,n);o=(t+G)/(0===t?Number.EPSILON:t)}const p=s*(t/e);let l=a?.GetAbsoluteWidthOffsetProperty()??0;l+=p-s;const h=(s+l)/(0===s?Number.EPSILON:s);return r.GetParent().GetWidth()*c*o*h}GetNewHeight(t,e,r,n,a,i){const s=r._GetSceneGraphInfo()._GetStartHeight(),c=s/r.GetParent()._GetSceneGraphInfo()._GetStartHeight();let o=1;const G=i?.GetAbsoluteScaleYOffsetProperty()??0;if(0!==G){const t=s/this.GetInstanceOriginalHeight(r,n);o=(t+G)/(0===t?Number.EPSILON:t)}const p=s*(t/e);let l=a?.GetAbsoluteHeightOffsetProperty()??0;l+=p-s;const h=(s+l)/(0===s?Number.EPSILON:s);return r.GetParent().GetHeight()*c*o*h}}C3.PropertyTrackState.PluginSourceAdapter=PluginSourceAdapter;
}

// timelines/state/propertySourceAdapters/valueSourceAdapter.js
{
const C3=self.C3;class ValueSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(t){super(t),this._value=0,this._init=!1}MayNeedBeforeAndAfterInterpolate(){return!1}SetInitialState(){const t=this._propertyTrack.GetPropertyTrackData();let e=this._propertyTrack.GetPropertyTrackDataItem();e=t.GetFirstPropertyKeyframeDataItem(e),this._value=e.GetValueWithResultMode()}SetResumeState(){}GetValue(){return this._init||this._propertyTrack.Interpolate(0),this._value}Interpolate(t,e,r,a,i,o,u){this._value=C3.PropertyTrackState.NumericTypeAdapter.Interpolate(t,e,r,this._propertyTrack),this._init=!0}SaveState(){}ClearSaveState(){}GetCurrentState(){return this._value}CompareInitialStateWithCurrent(){return!1}CompareSaveStateWithCurrent(){return!1}_SaveToJson(){return{"value":this._value,"init":this._init}}_LoadFromJson(t){t&&(this._value=t["value"],this._init=!t.hasOwnProperty("init")||t["init"])}}C3.PropertyTrackState.ValueSourceAdapter=ValueSourceAdapter;
}

// timelines/state/propertySourceAdapters/audioSourceAdapter.js
{
const C3=self.C3,PROJECT_FILE=0,PROJECT_FILE_NAME=0,PROJECT_FILE_TYPE=1,START_OFFSET=1,AUDIO_DURATION=2,AUDIO_TAG=3;class AudioSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(t){super(t),this._audioPlaybackStarted=!1,this._sdkInstance=null,this._actions=null,this._expressions=null,this._timeline=this._propertyTrack.GetTimeline(),this._track=this._propertyTrack.GetTrack(),this._sourceAdapterArgs=this._propertyTrack.GetSourceAdapterArgs(),this._fileArgs=this._sourceAdapterArgs[0],this._startOffsetTime=this._sourceAdapterArgs[1],this._sourceAdapterArgs[3]?this._audioTag=this._sourceAdapterArgs[3]:this._audioTag=Math.random().toString(36).slice(2),this._pauseTime=NaN,this._pauseVolume=NaN,this._volume=NaN,this._audioSource=null,this._Initialize()}Release(){super.Release(),this._sdkInstance=null,this._actions=null,this._expressions=null,this._timeline=null,this._track=null,this._sourceAdapterArgs=null,this._fileArgs=null,this._audioSource=null}_Initialize(){if(!self.C3.Plugins.Audio)return;const t=this._propertyTrack.GetRuntime().GetSingleGlobalObjectClassByCtor(self.C3.Plugins.Audio);t&&(this._sdkInstance=t.GetSingleGlobalInstance().GetSdkInstance()),this._actions=self.C3.Plugins.Audio.Acts,this._expressions=self.C3.Plugins.Audio.Exps}_MaybeSetAudioSource(){if(this._audioSource)return;const t=this._propertyTrack.GetTrack().GetPropertyTrack("audioSource");t&&(this._audioSource=t.GetSourceAdapter())}_GetPauseVolume(){const t=this._propertyTrack.GetTrack().GetPropertyTrack("volume");return t?t.GetSourceAdapter()._pauseVolume:this._pauseVolume}TimelineRemoved(){super.TimelineRemoved(),this._audioPlaybackStarted=!1,this._sdkInstance&&(this._expressions&&(this._pauseTime=this._expressions.PlaybackTime.call(this._sdkInstance,this._audioTag),this._pauseVolume=this._expressions.Volume.call(this._sdkInstance,this._audioTag)),this._actions&&this._actions.Stop.call(this._sdkInstance,this._audioTag))}GetAudioTag(){return this._audioTag}GetVolume(){return this._volume}SetVolume(t){this._volume=t}SetInitialState(){super.SetInitialState(),this._pauseTime=NaN,this._audioPlaybackStarted=!1}SetResumeState(){super.SetResumeState();const t=this._propertyTrack.GetTimeline().GetTime();switch(this._pauseTime=t-this._startOffsetTime,this._propertyTrack.GetPropertyName()){case"audioSource":break;case"volume":this._pauseVolume=this._propertyTrack.GetInterpolatedValue(t)}this._audioPlaybackStarted=!1}Interpolate(t,e,s,i,a,o,r){if(this._sdkInstance)switch(this._propertyTrack.GetPropertyName()){case"audioSource":{if(!this._timeline.IsForwardPlayBack())return;if(i)return void(this._actions&&this._actions.Stop.call(this._sdkInstance,this._audioTag));if(t<this._startOffsetTime)return void(this._audioPlaybackStarted=!1);const e=this._expressions.PlaybackRate.call(this._sdkInstance,this._audioTag),s=this._timeline.GetPlaybackRate();if(s!==e&&this._actions.SetPlaybackRate.call(this._sdkInstance,this._audioTag,s),this._audioPlaybackStarted)return;if(!this._propertyTrack.GetTimeline().IsPlaying())return;if(this._audioPlaybackStarted=!0,isNaN(this._pauseTime)){const e=self["performance"].now(),s=t-this._startOffsetTime;if("suspended"===this._sdkInstance.GetAudioContextState())return void(this._audioPlaybackStarted=!1);const i=s+(self["performance"].now()-e)/1e3;if(this._actions){let t=this.GetVolume();isNaN(t)?(this.SetVolume(0),t=0):this.SetVolume(t),this._actions.PlayFromTimeline.call(this._sdkInstance,this._fileArgs,t,this._audioTag,i)}}else{const t=this._pauseTime;this._pauseTime=NaN;const e=this._GetPauseVolume();this._pauseVolume=NaN;if("suspended"===this._sdkInstance.GetAudioContextState())return void(this._audioPlaybackStarted=!1);this._actions&&(this.SetVolume(e),this._actions.PlayFromTimeline.call(this._sdkInstance,this._fileArgs,e,this._audioTag,t))}break}case"volume":this._MaybeSetAudioSource(),super.Interpolate(t,e,s,i,a,o,r)}}GetInterpolatedValue(t,e,s){if(this._sdkInstance)switch(this._propertyTrack.GetPropertyName()){case"audioSource":return;case"volume":return this._MaybeSetAudioSource(),super.GetInterpolatedValue(t,e,s)}}Getter(t,e){return this._audioSource?this._audioSource.GetVolume():0}Setter(t,e,s,i){this._audioSource&&this._audioSource.SetVolume(this.Getter()+e),this._actions&&this._audioSource&&this._actions.SetVolume.call(this._sdkInstance,this._audioSource.GetAudioTag(),this._audioSource.GetVolume())}AbsoluteSetter(t,e,s){this._audioSource&&this._audioSource.SetVolume(e),this._actions&&this._audioSource&&this._actions.SetVolume.call(this._sdkInstance,this._audioSource.GetAudioTag(),this._audioSource.GetVolume())}DoesRounding(){return!0}_SaveToJson(){return{"audioPlaybackStarted":this._audioPlaybackStarted,"audioTag":this._audioTag,"pauseTime":this._pauseTime,"pauseVolume":this._pauseVolume,"volume":this._volume}}_LoadFromJson(t){t&&(this._audioPlaybackStarted=t["audioPlaybackStarted"],this._audioTag=t["audioTag"],this._pauseTime=t["pauseTime"],this._pauseVolume=t["pauseVolume"],this._volume=t["volume"],this._Initialize())}}C3.PropertyTrackState.AudioSourceAdapter=AudioSourceAdapter;
}

// timelines/state/propertyInterpolationAdapters/propertyInterpolationAdapter.js
{
const C3=self.C3;C3.PropertyTrackState.PropertyInterpolationAdapter=class{constructor(t){this._sourceAdapter=t,this._propertyTrack=t.GetPropertyTrack(),this._worldInfo=this._propertyTrack.GetTrack().GetWorldInfo(),this._property=this._propertyTrack.GetPropertyName(),this._firstAbsoluteUpdate=!1,this._saveState=null,this._target=null}Release(){this._sourceAdapter=null,this._propertyTrack=null,this._worldInfo=null,this._saveState=null,this._target=null}MayNeedBeforeAndAfterInterpolate(){return!1}TimelineRemoved(){}CleanCaches(){this._worldInfo=null,this._saveState=null,this._target=null}GetSourceAdapter(){return this._sourceAdapter}GetPropertyTrack(){return this._propertyTrack}GetWorldInfo(){return this._worldInfo||(this._worldInfo=this._propertyTrack.GetTrack().GetWorldInfo()),this._worldInfo}SetFirstAbsoluteUpdate(t){this._firstAbsoluteUpdate=!!t}GetFirstAbsoluteUpdate(){return this._firstAbsoluteUpdate}SetResetState(){}SetInitialState(){}SetResumeState(){}SetSaveState(){this._saveState=this.GetCurrentState()}ClearSaveState(){this._saveState=null}GetCurrentState(){}CompareInitialStateWithCurrent(){}CompareSaveStateWithCurrent(){}CanChange(t){return typeof this._Getter()===typeof t}BeforeChangeProperty(){}ChangeProperty(t,e,r,a,s,o,i,n){}AfterChangeProperty(){}_FirstKeyframeGetter(){return this._PickTimelinePlaybackMode((()=>{const t=this._propertyTrack.GetPropertyTrackDataItem();return this._propertyTrack.GetPropertyTrackData().GetFirstPropertyKeyframeDataItem(t)}),(()=>{const t=this._propertyTrack.GetPropertyTrackDataItem();return this._propertyTrack.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(t)})).GetAbsoluteValue()}_CurrentKeyframeGetter(){const t=this._propertyTrack.GetTimeline().GetTime()-this._propertyTrack.GetTrack().GetStartOffset();return this._PickTimelinePlaybackMode((()=>{const e=this._propertyTrack.GetPropertyTrackDataItem();return this._propertyTrack.GetPropertyTrackData().GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,e)}),(()=>{const e=this._propertyTrack.GetPropertyTrackDataItem(),r=this._propertyTrack.GetPropertyTrackData(),a=r.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(t,e);return a||r.GetLastPropertyKeyframeDataItem(e)})).GetAbsoluteValue()}_PickTimelinePlaybackMode(t,e){return this._propertyTrack.GetTimeline().IsForwardPlayBack()?t():e()}_PickResultMode(t,e){return"relative"===this._propertyTrack.GetResultMode()?t():e()}_PickFirstAbsoluteUpdate(t,e){return this.GetFirstAbsoluteUpdate()?(this.SetFirstAbsoluteUpdate(!1),t()):e()}_GetAbsoluteInitialValue(t){}_GetIndex(){return this._sourceAdapter.GetIndex()}_GetTarget(){return this._target||(this._target=this._sourceAdapter.GetTarget()),this._target}_PickSource(t,e,r,a,s,o){switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":return t();case"effect":return e();case"instance-variable":return r();case"plugin":return a();case"world-instance":return s();case"audio":return o()}}_SaveToJson(){return{"firstAbsoluteUpdate":this._firstAbsoluteUpdate,"saveState":this._saveState}}_LoadFromJson(t){t&&(this._firstAbsoluteUpdate=t["firstAbsoluteUpdate"],this._saveState=t["saveState"])}_GetPropertyKeyframeStubs(t,e=!1){const r=[];for(const a of t){const t=a.GetTrack().GetStartOffset();for(const s of a.GetPropertyKeyframeDataItems())e&&0===s.GetTime()?r.push({time:t+s.GetTime(),value:s.GetAbsoluteValue()}):e||r.push({time:t+s.GetTime(),value:s.GetAbsoluteValue()})}return r.sort(((t,e)=>t.time-e.time))}_GetLastPropertyKeyframeStub(t,e,r){return this._GetPropertyKeyframeStubLowerThanPlayhead(e,r)}_GetPropertyKeyframeStubLowerThanPlayhead(t,e){for(let r=e.length-1;r>=0;r--){if(e[r].time<=t)return e[r]}return null}};
}

// timelines/state/propertyInterpolationAdapters/colorInterpolationAdapter.js
{
const C3=self.C3,TMP_COLORS_MAP=new Map,TMP_COLOR=[0,0,0];class ColorInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(e){super(e)}SetResetState(){}SetInitialState(){}SetResumeState(){}GetCurrentState(){const e=this._propertyTrack.GetSourceAdapterId(),t=this._GetTarget(),r=this._GetIndex();switch(e){case"behavior":case"plugin":return this._ToColorArray(t.GetPropertyValueByIndex(r));case"effect":return this._ToColorArray(t[r]);case"world-instance":return this._ToColorArray(this._Getter())}}CompareInitialStateWithCurrent(){const e=this._FirstKeyframeGetter();return!this._CompareColors(e,this._Getter())}CompareSaveStateWithCurrent(){return!C3.IsNullOrUndefined(this._saveState)&&!this._CompareColors(this._saveState,this._Getter())}_CompareColors(e,t){return e=this._GetColorFromArray(e),t=this._GetColorFromArray(t),e.equalsIgnoringAlpha(t)}_FirstKeyframeGetter(){const e=super._FirstKeyframeGetter();return this._GetColorFromArray(e)}_CurrentKeyframeGetter(){const e=super._CurrentKeyframeGetter();return this._GetColorFromArray(e)}_GetAbsoluteInitialValue(e){}_ToColorArray(e){return C3.IsInstanceOf(e,C3.Color)?e.toArray().slice(0,3):e.slice(0,3)}_GetColorFromArray(e){return C3.IsInstanceOf(e,C3.Color)?e:new C3.Color(e[0],e[1],e[2],1)}CanChange(e){return!0}MayNeedBeforeAndAfterInterpolate(){return!0}BeforeChangeProperty(){const e=this._propertyTrack.GetTimeline(),t=this._propertyTrack.GetInstance(),r=this._propertyTrack.GetSourceAdapter(),o=e.GetSimilarPropertyTracks(t,r,this._property,this._propertyTrack);if(o&&o.length>1){TMP_COLORS_MAP.has(t)||TMP_COLORS_MAP.set(t,new Map);const e=TMP_COLORS_MAP.get(t),r=this._propertyTrack.GetSourceAdapterId();e.has(r)||e.set(r,new Map);const o=e.get(r);o.has(this._property)||o.set(this._property,{used:!1,color:new C3.Color(0,0,0,1)})}}_GetTmpColor(e,t,r){const o=TMP_COLORS_MAP.get(e).get(t).get(r);return o.used=!0,o.color}ChangeProperty(e,t,r,o,s,a,n,i){const p=this._propertyTrack.GetTimeline(),_=this._propertyTrack.GetTrack(),c=this._propertyTrack.GetInstance(),l=this._propertyTrack.GetSourceAdapter(),h=this._propertyTrack.GetSourceAdapterId(),C=this._property,y=p.GetSimilarPropertyTracks(c,l,C,this._propertyTrack);if(y&&y.length>1){const e=this._GetPropertyKeyframeStubs(y,!0),r=this._GetLastPropertyKeyframeStub(p,p.GetTime(),e);if(r){const e=_.GetStartOffset(),o=r.time-e;if(0===o)this._GetTmpColor(c,h,this._property).addRgb(t[0],t[1],t[2]);else{if(o<0)return;const e=t[0],r=t[1],s=t[2],a=this._propertyTrack.Interpolate(o,!1,!0),n=C3.Color.DiffChannel(e,a[0]),i=C3.Color.DiffChannel(r,a[1]),p=C3.Color.DiffChannel(s,a[2]);this._GetTmpColor(c,h,this._property).addRgb(n,i,p)}}}else this._Setter(t[0],t[1],t[2])}AfterChangeProperty(){const e=this._propertyTrack.GetInstance();if(!TMP_COLORS_MAP.has(e))return;const t=TMP_COLORS_MAP.get(e),r=this._propertyTrack.GetSourceAdapterId();if(!t.has(r))return;const o=t.get(r);if(!o.has(this._property))return;const s=o.get(this._property),a=s.used,n=s.color;a&&this._Setter(n.getR(),n.getG(),n.getB()),0===o.size&&t.delete(r),0===t.size&&TMP_COLORS_MAP.delete(e)}_Getter(){const e=this._propertyTrack.GetSourceAdapterId(),t=this._GetTarget(),r=this._GetIndex();switch(e){case"behavior":case"plugin":return this._GetColorFromArray(t.GetPropertyValueByIndex(r));case"effect":return t[r].clone();case"world-instance":return this.GetWorldInfo().GetUnpremultipliedColor().clone()}}_Setter(e,t,r){const o=this._propertyTrack.GetSourceAdapterId(),s=this._GetTarget(),a=this._GetIndex();switch(o){case"behavior":case"plugin":TMP_COLOR[0]=e,TMP_COLOR[1]=t,TMP_COLOR[2]=r,s.SetPropertyValueByIndex(a,TMP_COLOR);break;case"effect":s[a].setRgb(e,t,r);break;case"world-instance":this.GetWorldInfo().SetUnpremultipliedColorRGB(e,t,r)}}_SaveToJson(){}_LoadFromJson(e){}}C3.PropertyTrackState.PropertyInterpolationAdapter.ColorInterpolationAdapter=ColorInterpolationAdapter;
}

// timelines/state/propertyInterpolationAdapters/noInterpolationAdapter.js
{
const C3=self.C3,NS=C3.PropertyTrackState;class NoInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(e){super(e)}SetResetState(){}SetInitialState(){}SetResumeState(){}GetCurrentState(){return this._Getter()}CompareInitialStateWithCurrent(){return this._FirstKeyframeGetter()!==this.GetCurrentState()}CompareSaveStateWithCurrent(){return!C3.IsNullOrUndefined(this._saveState)&&this._saveState!==this.GetCurrentState()}MayNeedBeforeAndAfterInterpolate(){return!1}ChangeProperty(e,t,r,a,n,i,s,o){const p=this._propertyTrack,c=p.GetTrack(),l=p.GetSourceAdapterId(),h=p.GetTimeline(),u=c.GetInstance(),S=p.GetSourceAdapter(),G=this._property,d=h.GetSimilarPropertyTracks(u,S,G,p);if(d&&d.length>1){const r=this._GetPropertyKeyframeStubs(d),a=e+c.GetStartOffset(),n=this._GetLastPropertyKeyframeStub(h,a,r);n&&(t=n.value)}switch(p.GetPropertyKeyframeType()){case"numeric":if(!NS.NumericTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,l))return;break;case"angle":if(!NS.AngleTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,l))return;break;case"boolean":if(!NS.BooleanTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,l))return;break;case"color":if(!NS.ColorTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,l))return;break;case"text":if(!NS.TextTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,l))return}this._Setter(t)}_Getter(){const e=this._propertyTrack.GetSourceAdapterId(),t=this._GetTarget(),r=this._GetIndex();switch(e){case"behavior":case"plugin":return t.GetPropertyValueByIndex(r);case"effect":return t[r];case"instance-variable":return t.GetInstanceVariableValue(r)}}_Setter(e){const t=this._propertyTrack.GetSourceAdapterId(),r=this._GetTarget(),a=this._GetIndex();switch(t){case"behavior":case"plugin":r.SetPropertyValueByIndex(a,e);break;case"effect":r[a]=e;break;case"instance-variable":r.SetInstanceVariableValue(a,e)}}}C3.PropertyTrackState.PropertyInterpolationAdapter.NoInterpolationAdapter=NoInterpolationAdapter;
}

// timelines/state/propertyInterpolationAdapters/numericInterpolationAdapter.js
{
const C3=self.C3,NS=C3.PropertyTrackState.PropertyInterpolationAdapter,INSTANCE_FUNC_MAP=new Map,add=(t,e,a,r,i,s=!1,o=null,n=null)=>{INSTANCE_FUNC_MAP.set(t,{setter:e,absolute_setter:a,getter:r,round:i,fRound:s,init:o,reset:n})},get_original_size=(t,e)=>{const a=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(a)return a.GetOriginalWidth();const r=t.GetInstance().GetSdkInstance();return r.IsOriginalSizeKnown()?r.GetOriginalWidth():t._GetSceneGraphInfo()._GetStartWidth()},get_last_property_keyframe_value=(t,e,a,r=0)=>{const i=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(!i)return r;const s=i.GetPropertyTrack(a);if(!s)return r;const o=s.GetPropertyTrackDataItem().GetPropertyKeyframeData();if(!o)return r;const n=o.GetLastPropertyKeyframeDataItem();return n?n.GetValue():r},get_parents=t=>{const e=[];let a=t.GetParent();for(;a;)e.push(a),a=a.GetParent();return e.reverse(),e};add("offsetX",((t,e,a,r)=>{"relative"===r._propertyTrack.GetResultMode()?t.OffsetX(e,a.GetTimeline().GetTransformWithSceneGraph()):t.OffsetX(e)}),((t,e)=>t.SetX(e)),(t=>t.GetX()),!0),add("offsetY",((t,e,a,r)=>{"relative"===r._propertyTrack.GetResultMode()?t.OffsetY(e,a.GetTimeline().GetTransformWithSceneGraph()):t.OffsetY(e)}),((t,e)=>t.SetY(e)),(t=>t.GetY()),!0),add("offsetWidth",((t,e,a,r,i=!1,s=!0)=>{if(0===e)return;const o="relative"===r._propertyTrack.GetResultMode(),n=1===r._typeAdapter.GetType();if((o||n)&&t.HasParent()&&t.GetTransformWithParentWidth()){if(isNaN(r._absoluteToFactor)){const e=get_parents(t);let a;if(n){a=e[e.length-1].GetWidth()}else{a=e[e.length-1]._GetSceneGraphInfo()._GetStartWidth()}r._absoluteToFactor=0===a?Number.EPSILON:a}if(i)return;r._absoluteWidthOffset+=e;const a=e/r._absoluteToFactor;t.OffsetWidth(a,s),r._changeAccumulator+=a}else t.OffsetWidth(e),r._changeAccumulator+=e}),((t,e)=>t.SetWidth(e)),(t=>t.GetWidth()),!0,!1,null,(t=>{t._changeAccumulator=0,t._absoluteWidthOffset=0})),add("offsetHeight",((t,e,a,r,i=!1,s=!0)=>{if(0===e)return;const o="relative"===r._propertyTrack.GetResultMode(),n=1===r._typeAdapter.GetType();if((o||n)&&t.HasParent()&&t.GetTransformWithParentHeight()){if(isNaN(r._absoluteToFactor)){const e=get_parents(t);let a;if(n){a=e[e.length-1].GetHeight()}else{a=e[e.length-1]._GetSceneGraphInfo()._GetStartHeight()}r._absoluteToFactor=0===a?Number.EPSILON:a}if(i)return;r._absoluteHeightOffset+=e;const a=e/r._absoluteToFactor;t.OffsetHeight(a,s),r._changeAccumulator+=a}else t.OffsetHeight(e),r._changeAccumulator+=e}),((t,e)=>t.SetHeight(e)),(t=>t.GetHeight()),!0,!1,null,(t=>{t._changeAccumulator=0,t._absoluteHeightOffset=0})),add("offsetAngle",((t,e,a,r,i)=>{t.OffsetAngle(e)}),((t,e)=>t.SetAngle(e)),(t=>t.GetAngle()),!1,!0),add("offsetOpacity",((t,e,a,r,i)=>{e/=r._opacityFactor?r._opacityFactor:1;const s=t.GetOpacity()+e;if(0===r._clampAccumulator)s>1?r._clampAccumulator+=s-1:s<0&&(r._clampAccumulator+=s),t.OffsetOpacity(e);else{const a=t.GetOpacity()+e;e>0&&r._clampAccumulator>0?a>1&&(r._clampAccumulator+=a-1):e>0&&r._clampAccumulator<0?(r._clampAccumulator+=e,r._clampAccumulator>0&&(t.OffsetOpacity(r._clampAccumulator),r._clampAccumulator=0)):e<0&&r._clampAccumulator>0?(r._clampAccumulator+=e,r._clampAccumulator<0&&(t.OffsetOpacity(r._clampAccumulator),r._clampAccumulator=0)):e<0&&r._clampAccumulator<0&&a<0&&(r._clampAccumulator+=a)}}),((t,e)=>{t.SetOpacity(e)}),(t=>t.GetOpacity()),!1,!0,((t,e,a)=>{switch(t._clampAccumulator=0,t._propertyTrack.GetResultMode()){case"relative":{t._propertyTrack.GetPropertyTrackData();const e=t._propertyTrack.GetPropertyTrackDataItem().GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray();let a=t.GetWorldInfo().GetOpacity(),r=a;for(const i of e){const e=i.GetTime();r=a+t._propertyTrack.GetInterpolatedValue(e),r=C3.clamp(r,0,1)}t._totalForewardOpacityDelta=a-r,t._totalForewardOpacityDelta=Math.round(100*(t._totalForewardOpacityDelta+Number.EPSILON))/100,r=a;for(let a=e.length-1;a>=0;a--){const i=e[a].GetTime();r-=t._propertyTrack.GetInterpolatedValue(i),r=C3.clamp(r,0,1)}t._totalBackwardOpacityDelta=r,t._totalBackwardOpacityDelta=Math.round(100*(t._totalBackwardOpacityDelta+Number.EPSILON))/100;break}}const r="relative"===t._propertyTrack.GetResultMode(),i=1===t._typeAdapter.GetType();if((r||i)&&e.HasParent()&&e.GetTransformWithParentOpacity()){const r=get_parents(e);let i=r[0]._GetSceneGraphInfo().GetStartOpacity();i+=get_last_property_keyframe_value(r[0],a,"offsetOpacity");for(let t=1;t<r.length;t++)i+=get_last_property_keyframe_value(r[t],a,"offsetOpacity");t._opacityFactor=0===i?1:i}}),(t=>{switch(t._propertyTrack.GetResultMode()){case"relative":{t._clampAccumulator=0;const e=t.GetWorldInfo();let a=e.GetOpacity();a=Math.round(100*(a+Number.EPSILON))/100,t._propertyTrack.GetTimeline().IsForwardPlayBack()?(e.SetOpacity(a+t._totalForewardOpacityDelta),t._lastValue=0):(e.SetOpacity(a-t._totalBackwardOpacityDelta),t._lastValue=t.GetSourceAdapter().GetValueAtTime());break}}})),add("offsetOriginX",((t,e)=>t.OffsetOriginX(e)),((t,e)=>t.SetOriginX(e)),(t=>t.GetOriginX()),!1),add("offsetOriginY",((t,e)=>t.OffsetOriginY(e)),((t,e)=>t.SetOriginY(e)),(t=>t.GetOriginY()),!1),add("offsetZElevation",((t,e)=>t.OffsetZElevation(e)),((t,e)=>t.SetZElevation(e)),(t=>t.GetZElevation()),!0),add("offsetScaleX",((t,e,a,r)=>{if(0===e)return;const i=t.GetWidth()<0?-1:1;if(r._absoluteScaleXOffset+=e,"relative"===r._propertyTrack.GetResultMode()&&t.HasParent()&&t.GetTransformWithParentWidth()){const s=get_last_property_keyframe_value(t,a,"offsetWidth"),o=isNaN(r._originalSize)?a.GetOriginalWidth():r._originalSize,n=(o+s/(t._GetSceneGraphInfo()._GetStartWidth()/o))*i*e;isNaN(r._absoluteToFactor)&&INSTANCE_FUNC_MAP.get("offsetWidth").setter(t,1,a,r,!0);const l=n/r._absoluteToFactor;t.OffsetWidth(l,!0),r._changeAccumulator+=l}else{const s=(isNaN(r._originalSize)?a.GetOriginalWidth():r._originalSize)*i*e;t.OffsetWidth(s),r._changeAccumulator+=s}}),((t,e,a)=>{t.SetWidth(a.GetOriginalWidth()*e)}),((t,e)=>{const a=t.GetWidth()<0?-1:1;if(t.GetTransformWithParentWidth()){const r=t.GetParent(),i=e.GetTimeline().GetTrackFromInstance(r.GetInstance());let s=NaN;if(i)s=r.GetWidth()/i.GetOriginalWidth();else{const t=r.GetInstance().GetSdkInstance();s=t.IsOriginalSizeKnown()?r.GetWidth()/t.GetOriginalWidth():1}return t.GetWidth()*a/(e.GetOriginalWidth()*s)}return t.GetWidth()*a/e.GetOriginalWidth()}),!1,!1,null,(t=>{t._changeAccumulator=0,t._originalSize=NaN,t._absoluteScaleXOffset=0})),add("offsetScaleY",((t,e,a,r)=>{if(0===e)return;const i=t.GetHeight()<0?-1:1;if(r._absoluteScaleYOffset+=e,"relative"===r._propertyTrack.GetResultMode()&&t.HasParent()&&t.GetTransformWithParentHeight()){const s=get_last_property_keyframe_value(t,a,"offsetHeight"),o=isNaN(r._originalSize)?a.GetOriginalHeight():r._originalSize,n=(o+s/(t._GetSceneGraphInfo()._GetStartHeight()/o))*i*e;isNaN(r._absoluteToFactor)&&INSTANCE_FUNC_MAP.get("offsetHeight").setter(t,1,a,r,!0);const l=n/r._absoluteToFactor;t.OffsetHeight(l,!0),r._changeAccumulator+=l}else{const s=(isNaN(r._originalSize)?a.GetOriginalHeight():r._originalSize)*i*e;t.OffsetHeight(s),r._changeAccumulator+=s}}),((t,e,a)=>{t.SetHeight(a.GetOriginalHeight()*e)}),((t,e)=>{const a=t.GetHeight()<0?-1:1;if(t.GetTransformWithParentHeight()){const r=t.GetParent(),i=e.GetTimeline().GetTrackFromInstance(r.GetInstance());let s=NaN;if(i)s=r.GetHeight()/i.GetOriginalHeight();else{const t=r.GetInstance().GetSdkInstance();s=t.IsOriginalSizeKnown()?r.GetHeight()/t.GetOriginalHeight():1}return t.GetHeight()*a/(e.GetOriginalHeight()*s)}return t.GetHeight()*a/e.GetOriginalHeight()}),!1,!1,null,(t=>{t._changeAccumulator=0,t._originalSize=NaN,t._absoluteScaleYOffset=0}));class NumericInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(t){super(t),this._lastValue=0,this._clampAccumulator=0,this._totalForewardOpacityDelta=0,this._totalBackwardOpacityDelta=0,this._opacityFactor=NaN,this._absoluteToFactor=NaN,this._changeAccumulator=0,this._originalSize=NaN,this._absoluteWidthOffset=0,this._absoluteScaleXOffset=0,this._absoluteHeightOffset=0,this._absoluteScaleYOffset=0,this._angleReflectMirrorOrFlip=void 0,this._angleReflectMirrorAndFlip=void 0,this._instance_getter=null,this._instance_setter=null,this._instance_absolute_setter=null,this._reset_action=null,this._init_action=null,this._source_adapter_getter=null,this._source_adapter_setter=null,this._source_adapter_absolute_setter=null,this._round=!1,this._fRound=!1,C3.IsInstanceOf(this._propertyTrack.GetTimeline(),C3.TweenState)?this._typeAdapter=new C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTween(this):this._typeAdapter=new C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTimeline(this);const e=this._propertyTrack.GetPropertyName();switch(this._propertyTrack.GetSourceAdapterId()){case"world-instance":{const t=INSTANCE_FUNC_MAP.get(e);this._instance_getter=t.getter,this._instance_setter=t.setter,this._instance_absolute_setter=t.absolute_setter,this._round=t.round,this._fRound=t.fRound,this._init_action=t.init,this._reset_action=t.reset;break}case"audio":this._source_adapter_getter=t.Getter,this._source_adapter_setter=t.Setter,this._source_adapter_absolute_setter=t.AbsoluteSetter,this._round=!!t.DoesRounding(),this._fRound=!1}}Release(){this._typeAdapter=null,this._instance_getter=null,this._instance_setter=null,this._instance_absolute_setter=null,this._reset_action=null,this._init_action=null,this._source_adapter_getter=null,this._source_adapter_setter=null,this._source_adapter_absolute_setter=null,super.Release()}MayNeedBeforeAndAfterInterpolate(){return this._typeAdapter.MayNeedBeforeAndAfterInterpolate()}GetLastValue(){return this._lastValue}SetLastValue(t){this._lastValue=t}SetResetState(){this._reset_action&&this._reset_action(this)}SetInitialState(){const t=this._typeAdapter.SetInitialState();if("number"==typeof t&&(this._lastValue=t),this._init_action){const t=this.GetWorldInfo(),e=this._propertyTrack.GetTrack();this._init_action(this,t,e)}}SetResumeState(){const t=this._typeAdapter.SetResumeState();"number"==typeof t&&(this._lastValue=t)}GetCurrentState(){return this._Getter()}CompareInitialStateWithCurrent(){return this._FirstKeyframeGetter()!==this.GetCurrentState()}CompareSaveStateWithCurrent(){return!C3.IsNullOrUndefined(this._saveState)&&this._saveState!==this.GetCurrentState()}BeforeChangeProperty(){this._typeAdapter.BeforeChangeProperty()}ChangeProperty(t,e,a,r,i,s,o,n){return this._typeAdapter.ChangeProperty(t,e,a,r,i,s,o,n)}AfterChangeProperty(){this._typeAdapter.AfterChangeProperty()}_Getter(){const t=this._GetTarget(),e=this._GetIndex(),a=this.GetWorldInfo(),r=this._propertyTrack.GetTrack();switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":case"plugin":return t.GetPropertyValueByIndex(e);case"effect":return t[e];case"instance-variable":return t.GetInstanceVariableValue(e);case"world-instance":return this._instance_getter(a,r);case"audio":return this._source_adapter_getter.call(this.GetSourceAdapter(),a,r)}}_Setter(t,e,a,r=!0){const i=this._GetTarget(),s=this._GetIndex(),o=this.GetWorldInfo(),n=this._propertyTrack.GetTrack();switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":i.OffsetPropertyValueByIndex(s,t);break;case"effect":i[s]+=t;break;case"instance-variable":i.SetInstanceVariableOffset(s,t);break;case"plugin":i.OffsetPropertyValueByIndex(s,t,this.GetSourceAdapter().GetOptionalCallbacks());break;case"world-instance":this._instance_setter(o,t,n,this,!1,r);break;case"audio":this._source_adapter_setter.call(this.GetSourceAdapter(),o,t,n,this)}}_SetterAbsolute(t,e,a){let r=this._propertyTrack.GetInterpolationMode();if(r="default"===r?"continuous":r,"discrete"===r&&!e)return;if("discrete"===r&&a){const t=this._propertyTrack.GetTimeline().GetTime();if(!this._propertyTrack.GetPropertyKeyFrameDataItemAtTime(t))return}const i=this._GetTarget(),s=this._GetIndex(),o=this.GetWorldInfo(),n=this._propertyTrack.GetTrack();switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":i.SetPropertyValueByIndex(s,t);break;case"effect":i[s]=t;break;case"instance-variable":i.SetInstanceVariableValue(s,t);break;case"plugin":i.SetPropertyValueByIndex(s,t,this.GetSourceAdapter().GetOptionalCallbacks());break;case"world-instance":this._instance_absolute_setter(o,t,n);break;case"audio":this._source_adapter_absolute_setter.call(this.GetSourceAdapter(),o,t,n)}}_MaybeEnsureValue(t,e,a,r,i,s,o,n){this._typeAdapter._MaybeEnsureValue(t,e,a,r,i,s,o,n)}_AddDelta(t,e,a,r,i){if("angle"===this._propertyTrack.GetPropertyType())t=C3.toDegrees(t);const s=(t.toString().split(".")[1]||"").length,o=this._Getter();let n;if(0===s)if(this._round)n=Math.round(o);else if(this._fRound)if("angle"===this._propertyTrack.GetPropertyType())n=C3.toRadians(Math.round(C3.toDegrees(o)));else n=Number(C3.toFixed(o,2));else n=o;else n=this._round?Number(C3.toFixed(o,s)):(this._fRound,o);switch(this._Setter(n-o,e,a,!1),this._propertyTrack.GetPropertyName()){case"offsetWidth":case"offsetScaleX":{const t=this.GetWorldInfo(),e=t.GetWidth(),a=Number(C3.toFixed(e,2));t.OffsetWidth(a-e);break}case"offsetHeight":case"offsetScaleY":{const t=this.GetWorldInfo(),e=t.GetHeight(),a=Number(C3.toFixed(e,2));t.OffsetHeight(a-e);break}}}_SaveToJson(){return Object.assign(super._SaveToJson(),{"v":this._lastValue,"a":this._clampAccumulator,"fod":this._totalForewardOpacityDelta,"bod":this._totalBackwardOpacityDelta,"of":this._opacityFactor,"sf":this._absoluteToFactor,"armorf":this._angleReflectMirrorOrFlip,"armandf":this._angleReflectMirrorAndFlip,"ca":this._changeAccumulator,"os":this._originalSize,"awo":this._absoluteWidthOffset,"aho":this._absoluteHeightOffset,"asxo":this._absoluteScaleXOffset,"asyo":this._absoluteScaleYOffset})}_LoadFromJson(t){t&&(super._LoadFromJson(t),this._lastValue=t["v"],this._clampAccumulator=t["a"],this._totalForewardOpacityDelta=C3.IsFiniteNumber(t["fod"])?t["fod"]:0,this._totalBackwardOpacityDelta=C3.IsFiniteNumber(t["bod"])?t["bod"]:0,this._opacityFactor=C3.IsFiniteNumber(t["of"])?t["of"]:NaN,this._absoluteToFactor=C3.IsFiniteNumber(t["sf"])?t["sf"]:NaN,this._angleReflectMirrorOrFlip=C3.IsFiniteNumber(t["armorf"])?t["armorf"]:void 0,this._angleReflectMirrorAndFlip=C3.IsFiniteNumber(t["armandf"])?t["armandf"]:void 0,this._changeAccumulator=C3.IsFiniteNumber(t["ca"])?t["ca"]:0,this._originalSize=C3.IsFiniteNumber(t["os"])?t["os"]:NaN,this._absoluteWidthOffset=C3.IsFiniteNumber(t["awo"])?t["awo"]:0,this._absoluteHeightOffset=C3.IsFiniteNumber(t["aho"])?t["aho"]:0,this._absoluteScaleXOffset=C3.IsFiniteNumber(t["asxo"])?t["asxo"]:0,this._absoluteScaleYOffset=C3.IsFiniteNumber(t["asyo"])?t["asyo"]:0)}SetOriginalSizeProperty(t){this._originalSize=t}GetChangeAccumulatorProperty(){return this._changeAccumulator}GetAbsoluteWidthOffsetProperty(){return this._absoluteWidthOffset}GetAbsoluteHeightOffsetProperty(){return this._absoluteHeightOffset}GetAbsoluteScaleXOffsetProperty(){return this._absoluteScaleXOffset}GetAbsoluteScaleYOffsetProperty(){return this._absoluteScaleYOffset}}C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapter=NumericInterpolationAdapter;
}

// timelines/state/propertyInterpolationAdapters/numericInterpolationAdapterForTimeline.js
{
const C3=self.C3;class AbsoluteValueObject{constructor(e){this._used=!1,this._value=0,this._propertyKeyframeReached=!1,this._endState=!1,this._propertyTracks=e;for(let e=0,t=this._propertyTracks.length;e<t;e++)this._propertyTracks[e].SetAbsoluteValueObject(this)}GetPropertyTracks(){return this._propertyTracks}SetUsed(){this._used=!0}GetUsed(){return this._used}SetValue(e){this._value=e}GetValue(){return this._value}SetPropertyKeyframeReached(e){this._propertyKeyframeReached=e}GetPropertyKeyframeReached(){return this._propertyKeyframeReached}SetEndState(e){this._endState=e}GetEndState(){return this._endState}Reset(){this._used=!1,this._value=0,this._propertyKeyframeReached=!1,this._endState=!1}}class NumericInterpolationAdapterForTimeline{constructor(e){this._numericInterpolationAdapter=e}Release(){this._numericInterpolationAdapter=null}GetType(){return 0}SetInitialState(){const e=this._numericInterpolationAdapter;this._numericInterpolationAdapter.GetPropertyTrack();return e._PickResultMode((()=>e._PickTimelinePlaybackMode((()=>0),(()=>e.GetSourceAdapter().GetValueAtTime()))),(()=>{}))}SetResumeState(){}MayNeedBeforeAndAfterInterpolate(){this._numericInterpolationAdapter;switch(this._numericInterpolationAdapter.GetPropertyTrack().GetResultMode()){case"relative":return!1;case"absolute":return!0}}BeforeChangeProperty(){this._numericInterpolationAdapter;const e=this._numericInterpolationAdapter.GetPropertyTrack(),t=e.GetPropertyName();switch(e.GetResultMode()){case"relative":break;case"absolute":if(e.HasAbsoluteValueObject()){e.GetAbsoluteValueObject().Reset()}else{const r=e.GetTimeline(),a=e.GetInstance(),s=e.GetSourceAdapter(),o=r.GetSimilarPropertyTracks(a,s,t,e);o&&o.length>1&&new AbsoluteValueObject(o)}}}ChangeProperty(e,t,r,a,s,o,i,n){const l=this._numericInterpolationAdapter,u=this._numericInterpolationAdapter.GetPropertyTrack();switch(u.GetResultMode()){case"relative":{const i=l.GetLastValue();l._Setter(t-i,r,a),o&&this._MaybeEnsureValue(e,r,a,s,i,t),l.SetLastValue(t);break}case"absolute":{const e=u.GetTimeline(),r=u.GetTrack();u.GetInstance(),u.GetSourceAdapter();if(u.HasAbsoluteValueObject()){const a=u.GetAbsoluteValueObject(),s=a.GetPropertyTracks(),o=l._GetPropertyKeyframeStubs(s,!0),c=l._GetLastPropertyKeyframeStub(e,e.GetTime(),o);if(c){const e=r.GetStartOffset(),s=c.time-e;if(0===s)a.SetEndState(i),a.SetPropertyKeyframeReached(n),a.SetUsed(),a.SetValue(a.GetValue()+t);else{if(s<0)return;const e=u.GetInterpolatedValue(s);a.SetEndState(i),a.SetPropertyKeyframeReached(n),a.SetUsed(),a.SetValue(a.GetValue()+(t-e))}}}else l._SetterAbsolute(t,n,i);break}}}AfterChangeProperty(){const e=this._numericInterpolationAdapter,t=this._numericInterpolationAdapter.GetPropertyTrack();switch(t.GetResultMode()){case"relative":break;case"absolute":if(t.HasAbsoluteValueObject()){const r=t.GetAbsoluteValueObject();r.GetUsed()&&e._SetterAbsolute(r.GetValue(),r.GetPropertyKeyframeReached(),r.GetEndState())}}}_MaybeEnsureValue(e,t,r,a,s,o){const i=this._numericInterpolationAdapter;a||(t&&e===t.GetTime()?i._AddDelta(t.GetValueWithResultMode(),t,r):r&&e===r.GetTime()?i._AddDelta(r.GetValueWithResultMode(),t,r):o-s==0&&i._AddDelta(t.GetValueWithResultMode(),t,r))}}C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTimeline=NumericInterpolationAdapterForTimeline;
}

// timelines/state/propertyInterpolationAdapters/numericInterpolationAdapterForTween.js
{
const C3=self.C3;class NumericInterpolationAdapterForTween{constructor(e){this._numericInterpolationAdapter=e}Release(){this._numericInterpolationAdapter=null}GetType(){return 1}SetInitialState(){const e=this._numericInterpolationAdapter;return e.SetFirstAbsoluteUpdate(!0),this._GetAbsoluteInitialValue(e._FirstKeyframeGetter())}SetResumeState(){const e=this._numericInterpolationAdapter;if(e._FirstKeyframeGetter()!==e._CurrentKeyframeGetter())return e.SetFirstAbsoluteUpdate(!0),this._GetAbsoluteInitialValue(e._CurrentKeyframeGetter())}MayNeedBeforeAndAfterInterpolate(){return!1}BeforeChangeProperty(){}ChangeProperty(e,t,r,a,n,i,o,l){const s=this._numericInterpolationAdapter,u=s.GetLastValue();switch(s.GetPropertyTrack().GetResultMode()){case"relative":s._Setter(t-u,r,a),i&&this._MaybeEnsureValue(e,r,a,n,u,t,!1,o);break;case"absolute":s.GetFirstAbsoluteUpdate()?(s.SetFirstAbsoluteUpdate(!1),s._Setter(u,r,a)):0===e&&0===s.GetPropertyTrack().GetTimeline().GetTotalTime()?s._SetterAbsolute(t,!0,!1):(s._Setter(t-u,r,a),i&&this._MaybeEnsureValue(e,r,a,n,u,t,this._ForceEndValue(),o))}s.SetLastValue(t)}AfterChangeProperty(){}_GetAbsoluteInitialValue(e){return e-this._numericInterpolationAdapter.GetCurrentState()}_ForceEndValue(){const e=this._numericInterpolationAdapter,t=e.GetWorldInfo().GetInstance(),r=e.GetPropertyTrack().GetRuntime().GetTimelineManager();let a=0;for(const e of r.GetPlayingTimelines())0===e.GetType()?e.HasTrackInstance(t)&&a++:1===e.GetType()&&e.GetInstance()===t&&a++;return a<=1}_MaybeEnsureValue(e,t,r,a,n,i,o,l){const s=this._numericInterpolationAdapter;a?t&&e===t.GetTime()?s._AddDelta(t.GetValueWithResultMode(),t,r,o,l):r&&e===r.GetTime()?s._AddDelta(r.GetValueWithResultMode(),t,r,o,l):r||s._AddDelta(t.GetValueWithResultMode(),t,r,o,l):t&&e===t.GetTime()?s._AddDelta(t.GetValueWithResultMode(),t,r,o,l):r&&e===r.GetTime()?s._AddDelta(r.GetValueWithResultMode(),t,r,o,l):i-n==0&&s._AddDelta(t.GetValueWithResultMode(),t,r,o,l)}}C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTween=NumericInterpolationAdapterForTween;
}

// timelines/state/propertyTypeAdapters/numericTypeAdapter.js
{
const C3=self.C3,Ease=self.Ease;C3.PropertyTrackState.NumericTypeAdapter=class{constructor(){}static WillChange(e,t,a,r){let s;switch(r){case"behavior":case"plugin":s=t.GetPropertyValueByIndex(e);break;case"effect":s=t[e];break;case"instance-variable":s=t.GetInstanceVariableValue(e)}return s!==a}static Interpolate(e,t,a,r){if(!a){let e=r.GetPropertyTrackDataItem();return e=r.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e),e.GetValueWithResultMode()}let s=r.GetInterpolationMode();if("default"===s&&(s="continuous"),"combo"===r.GetPropertyType()&&(s="discrete"),"discrete"===s)return t.GetValueWithResultMode();if("continuous"===s||"step"===s){const n=r.GetTimeline().GetStep();if("step"===s&&0!==n){const t=1/n;e=Math.floor(e*t)/t}const i=t.GetValueWithResultMode(),c=a.GetValueWithResultMode(),o=t.GetAddOn("cubic-bezier"),l=a.GetAddOn("cubic-bezier"),u=o&&o.GetStartEnable()&&l&&l.GetEndEnable();if(!u&&i===c)return i;const G=t.GetTime(),p=a.GetTime();"step"===s&&0!==n&&(e=C3.clamp(e,G,p));const d=C3.normalize(e,G,p),b=t.GetEase();let f;if(u){const e=p-G;f=Ease.GetRuntimeEase(b)(e*d,0,1,e),f=Ease.GetRuntimeEase("cubicbezier")(f,i,i+o.GetStartAnchor(),c+l.GetEndAnchor(),c)}else f=Ease.GetRuntimeEase(b)((p-G)*d,i,c-i,p-G);return"integer"===r.GetPropertyType()?Math.floor(f):f}}};
}

// timelines/state/propertyTypeAdapters/angleTypeAdapter.js
{
const C3=self.C3;C3.PropertyTrackState.AngleTypeAdapter=class{constructor(){}static WillChange(e,t,a,r){let s;switch(r){case"behavior":case"plugin":s=t.GetPropertyValueByIndex(e);break;case"effect":s=t[e];break;case"instance-variable":s=t.GetInstanceVariableValue(e)}return s!==a}static Interpolate(e,t,a,r){if(!a){let e=r.GetPropertyTrackDataItem();return e=r.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e),e.GetValueWithResultMode()}let s=r.GetInterpolationMode();if("default"===s&&(s="continuous"),"combo"===r.GetPropertyType()&&(s="discrete"),"discrete"===s)return t.GetValueWithResultMode();if("continuous"===s||"step"===s){const n=r.GetTimeline().GetStep();if("step"===s&&0!==n){const t=1/n;e=Math.floor(e*t)/t}const i=t.GetTime(),o=a.GetTime(),c=t.GetValueWithResultMode(),l=a.GetValueWithResultMode();"step"===s&&0!==n&&(e=C3.clamp(e,i,o));const u=t.GetAddOn("angle");if(!u){if(c===l)return c;const a=C3.normalize(e,i,o),r=self.Ease.GetRuntimeEase(t.GetEase());return C3.angleLerp(c,l,r(a,0,1,1))}{const a=u.GetRevolutions();if(c===l&&0===a)return c;const r=C3.normalize(e,i,o),s=self.Ease.GetRuntimeEase(t.GetEase())(r,0,1,1);switch(u.GetDirection()){case"closest":return C3.angleLerp(c,l,s,a);case"clockwise":return C3.angleLerpClockwise(c,l,s,a);case"anti-clockwise":return C3.angleLerpAntiClockwise(c,l,s,a)}}}}};
}

// timelines/state/propertyTypeAdapters/booleanTypeAdapter.js
{
const C3=self.C3;C3.PropertyTrackState.BooleanTypeAdapter=class{constructor(){}static WillChange(e,t,a,r){let c;switch(r){case"behavior":case"plugin":c=t.GetPropertyValueByIndex(e);break;case"effect":c=t[e];break;case"instance-variable":c=t.GetInstanceVariableValue(e)}return!!c!=!!a}static Interpolate(e,t,a,r){if(!a){let e=r.GetPropertyTrackDataItem();return e=r.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e),e.GetValueWithResultMode()?1:0}return t.GetValueWithResultMode()?1:0}};
}

// timelines/state/propertyTypeAdapters/colorTypeAdapter.js
{
const C3=self.C3,TEMP_COLOR_ARRAY=[0,0,0],TEMP_COLOR_ARRAY_2=[0,0,0],TEMP_COLOR_ARRAY_3=[0,0,0];C3.PropertyTrackState.ColorTypeAdapter=class{constructor(){}static WillChange(R,_,e,t){let A;switch(t){case"behavior":case"plugin":A=_.GetPropertyValueByIndex(R);break;case"effect":A=_[R];break;case"instance-variable":A=_.GetInstanceVariableValue(R)}return Array.isArray(e)?(TEMP_COLOR_ARRAY[0]=e[0],TEMP_COLOR_ARRAY[1]=e[1],TEMP_COLOR_ARRAY[2]=e[2]):(TEMP_COLOR_ARRAY_3.parseCommaSeparatedRgb(e),TEMP_COLOR_ARRAY[0]=Math.floor(255*TEMP_COLOR_ARRAY_3.getR()),TEMP_COLOR_ARRAY[1]=Math.floor(255*TEMP_COLOR_ARRAY_3.getG()),TEMP_COLOR_ARRAY[2]=Math.floor(255*TEMP_COLOR_ARRAY_3.getB())),Array.isArray(A)?(TEMP_COLOR_ARRAY_2[0]=A[0],TEMP_COLOR_ARRAY_2[1]=A[1],TEMP_COLOR_ARRAY_2[2]=A[2]):(TEMP_COLOR_ARRAY_3.parseCommaSeparatedRgb(A),TEMP_COLOR_ARRAY_2[0]=Math.floor(255*TEMP_COLOR_ARRAY_3.getR()),TEMP_COLOR_ARRAY_2[1]=Math.floor(255*TEMP_COLOR_ARRAY_3.getG()),TEMP_COLOR_ARRAY_2[2]=Math.floor(255*TEMP_COLOR_ARRAY_3.getB())),TEMP_COLOR_ARRAY[0]!==TEMP_COLOR_ARRAY_2[0]||(TEMP_COLOR_ARRAY[1]!==TEMP_COLOR_ARRAY_2[1]||TEMP_COLOR_ARRAY[2]!==TEMP_COLOR_ARRAY_2[2])}static Interpolate(R,_,e,t){if(!e){let R=t.GetPropertyTrackDataItem();R=t.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(R);const _=R.GetValueWithResultMode();return TEMP_COLOR_ARRAY[0]=_[0],TEMP_COLOR_ARRAY[1]=_[1],TEMP_COLOR_ARRAY[2]=_[2],TEMP_COLOR_ARRAY}let A=t.GetInterpolationMode();if("default"===A&&(A="continuous"),"discrete"===A){const R=_.GetValueWithResultMode();return TEMP_COLOR_ARRAY[0]=R[0],TEMP_COLOR_ARRAY[1]=R[1],TEMP_COLOR_ARRAY[2]=R[2],TEMP_COLOR_ARRAY}if("continuous"===A||"step"===A){const O=t.GetTimeline().GetStep();if("step"===A&&0!==O){const _=1/O;R=Math.floor(R*_)/_}const a=_.GetTime(),r=e.GetTime(),M=_.GetValueWithResultMode(),C=e.GetValueWithResultMode();"step"===A&&0!==O&&(R=C3.clamp(R,a,r));const T=C3.normalize(R,a,r),o=_.GetEase(),P=M[0],E=M[1],L=M[2],Y=C[0],s=C[1],l=C[2],i=self.Ease.GetRuntimeEase(o),n=r-a,c=n*T;return TEMP_COLOR_ARRAY[0]=P===Y?P:i(c,P,Y-P,n),TEMP_COLOR_ARRAY[1]=E===s?E:i(c,E,s-E,n),TEMP_COLOR_ARRAY[2]=L===l?L:i(c,L,l-L,n),TEMP_COLOR_ARRAY}}};
}

// timelines/state/propertyTypeAdapters/textTypeAdapter.js
{
const C3=self.C3;C3.PropertyTrackState.TextTypeAdapter=class{constructor(){}static WillChange(e,t,a,r){let c;switch(r){case"behavior":case"plugin":c=t.GetPropertyValueByIndex(e);break;case"effect":c=t[e];break;case"instance-variable":c=t.GetInstanceVariableValue(e)}return c!==a}static Interpolate(e,t,a,r){if(!a){let e=r.GetPropertyTrackDataItem();return e=r.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e),e.GetValueWithResultMode()}return t.GetValueWithResultMode()}};
}

// timelines/data/timelineDataManager.js
{
const C3=self.C3;C3.TimelineDataManager=class{constructor(){this._timelineDataItems=new Map}Release(){for(const e of this._timelineDataItems.values())e.Release();this._timelineDataItems.clear(),this._timelineDataItems=null}Add(e){const a=new C3.TimelineDataItem(e),t=a.GetName();this._timelineDataItems.set(t,a)}Get(e){return this._timelineDataItems.get(e)}GetNameId(){return 0}static _CreateDataItems(e,a,t,s){if(a)for(const i of a)C3.TimelineDataManager._CreateDataItem("create",i,e,t,s)}static _CreateDataItemsIncludingDisabled(e,a,t,s){if(a)for(const i of a)C3.TimelineDataManager._CreateDataItem("create-including-disabled",i,e,t,s)}static _LoadDataItemsFromJson(e,a,t,s){e.length?a.forEach(((a,t)=>{e[t]._LoadFromJson(a)})):a.forEach((a=>{C3.TimelineDataManager._CreateDataItem("load",a,e,t,s)}))}static _CreateDataItem(e,a,t,s,i){let n;if("function"==typeof s)switch(e){case"load":n=new s(null,i);break;case"create":case"create-including-disabled":n=new s(a,i)}else if("object"==typeof s){const t=a[s.prop],c=s.map.get(t);switch(e){case"load":n=new c(null,i);break;case"create":case"create-including-disabled":n=new c(a,i)}}switch(e){case"load":n._LoadFromJson(a),t.push(n);break;case"create":if("function"==typeof n.GetEnable&&!n.GetEnable())return n.Release();t.push(n);break;case"create-including-disabled":t.push(n)}}};
}

// timelines/data/timelineData.js
{
const C3=self.C3,NAME=0,TOTAL_TIME=1,STEP=2,INTERPOLATION_MODE=3,RESULT_MODE=4,TRACKS=5,LOOP=6,PING_PONG=7,REPEAT_COUNT=8,START_ON_LAYOUT=9,TRANSFORM_WITH_SCENE_GRAPH=10,USE_SYSTEM_TIMESCALE=11;C3.TimelineDataItem=class{constructor(t){this._name="",this._totalTime=NaN,this._step=0,this._interpolationMode="default",this._resultMode="default",this._loop=!1,this._pingPong=!1,this._repeatCount=1,this._trackData=null,this._startOnLayout="",this._transformWithSceneGraph=!1,this._useSystemTimescale=!0,t&&(this._name=t[0],this._totalTime=t[1],this._step=t[2],this._interpolationMode=t[3],this._resultMode=t[4],this._loop=!!t[6],this._pingPong=!!t[7],this._repeatCount=t[8],this._startOnLayout=t[9],this._transformWithSceneGraph=!!t[10],this._useSystemTimescale=!!t[11],this._trackData=new C3.TrackData(t[5],this))}Release(){this._trackData.Release(),this._trackData=null}GetTrackData(){return this._trackData||(this._trackData=new C3.TrackData(null,this)),this._trackData}GetName(){return this._name}SetName(t){this._name=t}GetTotalTime(){return this._totalTime}SetTotalTime(t){this._totalTime=t}GetStep(){return this._step}SetStep(t){this._step=t}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(t){this._interpolationMode=t}GetResultMode(){return this._resultMode}SetResultMode(t){this._resultMode=t}GetLoop(){return this._loop}SetLoop(t){this._loop=t}GetPingPong(){return this._pingPong}SetPingPong(t){this._pingPong=t}GetRepeatCount(){return this._repeatCount}SetRepeatCount(t){this._repeatCount=t}GetStartOnLayout(){return this._startOnLayout}GetTransformWithSceneGraph(){return this._transformWithSceneGraph}GetUseSystemTimescale(){return this._useSystemTimescale}_SaveToJson(){return{"trackDataJson":this._trackData._SaveToJson(),"name":this._name,"totalTime":this._totalTime,"step":this._step,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,"loop":this._loop,"pingPong":this._pingPong,"repeatCount":this._repeatCount,"startOnLayout":this._startOnLayout,"transformWithSceneGraph":!!this._transformWithSceneGraph,"useSystemTimescale":this._useSystemTimescale}}_LoadFromJson(t){t&&(this.GetTrackData()._LoadFromJson(t["trackDataJson"]),this._name=t["name"],this._totalTime=t["totalTime"],this._step=t["step"],this._interpolationMode=t["interpolationMode"],this._resultMode=t["resultMode"],this._loop=t["loop"],this._pingPong=t["pingPong"],this._repeatCount=t["repeatCount"],this._startOnLayout=t["startOnLayout"],this._transformWithSceneGraph=!!t["transformWithSceneGraph"],this._useSystemTimescale=!!t["useSystemTimescale"])}};
}

// timelines/data/trackData.js
{
const C3=self.C3,WI_DATA=0,OC_INDEX=1,WI_UID=2,INTERPOLATION_MODE=1,RESULT_MODE=2,ENABLED=3,KEYFRAMES=4,PROPERTY_TRACKS=5,ID=6,NESTED_DATA=7,START_OFFSET=0,LOCAL_TOTAL_TIME=1,WI_ADDITIONAL_DATA=8,ORIGINAL_WIDTH=0,ORIGINAL_HEIGHT=1,TRACK_TYPE=9,TRACK_NAME=10;class TrackDataItem{constructor(t,a){this._trackData=a,this._instanceData=null,this._additionalInstanceData=null,this._instanceUid=NaN,this._objectClassIndex=NaN,this._interpolationMode="default",this._resultMode="default",this._enabled=!1,this._keyframeData=null,this._propertyTrackData=null,this._id="",this._nestedData=null,this._startOffset=0,this._localTotalTime=this._trackData.GetTimelineDataItem().GetTotalTime(),this._type=0,this._name="",t&&(t[0]&&(this._instanceData=t[0],this._instanceUid=t[0][2],this._objectClassIndex=t[0][1]),this._interpolationMode=t[1],this._resultMode=t[2],this._enabled=!!t[3],t[6]&&(this._id=t[6]),t[7]&&(this._nestedData=t[7],this._startOffset=t[7][0],this._localTotalTime=t[7][1]),t[8]&&(this._additionalInstanceData=t[8]),t[8]&&(this._additionalInstanceData=t[8]),t[9]&&(this._type=t[9]),t[10]&&(this._name=t[10]),this._keyframeData=new C3.KeyframeData(t[4],this),this._propertyTrackData=new C3.PropertyTrackData(t[5],this))}Release(){this._instanceData=null,this._trackData=null,this._keyframeData&&(this._keyframeData.Release(),this._keyframeData=null),this._propertyTrackData&&(this._propertyTrackData.Release(),this._propertyTrackData=null),this._nestedData=null}GetTrackData(){return this._trackData}GetKeyframeData(){return this._keyframeData||(this._keyframeData=new C3.KeyframeData(null,this)),this._keyframeData}GetPropertyTrackData(){return this._propertyTrackData||(this._propertyTrackData=new C3.PropertyTrackData(null,this)),this._propertyTrackData}GetInstanceData(){return this._instanceData}GetObjectClassIndex(){return this._objectClassIndex}SetObjectClassIndex(t){this._objectClassIndex=t}GetInstanceUID(){return this._instanceUid}SetInstanceUID(t){this._instanceUid=t}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(t){this._interpolationMode=t}GetResultMode(){return this._resultMode}SetResultMode(t){this._resultMode=t}GetEnable(){return this._enabled}SetEnable(t){this._enabled=!!t}GetId(){return this._id}GetStartOffset(){return this._startOffset}GetLocalTotalTime(){return this._localTotalTime}SetLocalTotalTime(t){this._localTotalTime=t}GetOriginalWidth(){return this._additionalInstanceData[0]}SetOriginalWidth(t){this._additionalInstanceData||(this._additionalInstanceData=[]),this._additionalInstanceData[0]=t}GetOriginalHeight(){return this._additionalInstanceData||(this._additionalInstanceData=[]),this._additionalInstanceData[1]}SetOriginalHeight(t){this._additionalInstanceData||(this._additionalInstanceData=[]),this._additionalInstanceData[1]=t}GetType(){return this._type}GetName(){return this._name}_SaveToJson(){return{"keyframeDataJson":this._keyframeData._SaveToJson(),"propertyTrackDataJson":this._propertyTrackData._SaveToJson(),"instanceData":this._instanceData,"additionalInstanceData":this._additionalInstanceData,"instanceUid":this._instanceUid,"objectClassIndex":this._objectClassIndex,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,"enabled":this._enabled,"id":this._id,"nestedData":this._nestedData,"type":this._type,"name":this._name}}_LoadFromJson(t){t&&(this._instanceData=t["instanceData"],this._instanceUid=t["instanceUid"],this._objectClassIndex=t["objectClassIndex"],this._interpolationMode=t["interpolationMode"],this._resultMode=t["resultMode"],this._enabled=t["enabled"],this._id=t["id"],this._type=t["type"]?t["type"]:0,this._name=t["name"]?t["name"]:"",this._localTotalTime=this._trackData.GetTimelineDataItem().GetTotalTime(),t["nestedData"]&&(this._nestedData=t["nestedData"],this._startOffset=this._nestedData[0],this._localTotalTime=this._nestedData[1]),t["additionalInstanceData"]&&(this._additionalInstanceData=t["additionalInstanceData"]),this.GetKeyframeData()._LoadFromJson(t["keyframeDataJson"]),this.GetPropertyTrackData()._LoadFromJson(t["propertyTrackDataJson"]))}}C3.TrackData=class{constructor(t,a){this._timelineDataItem=a,this._trackDataItems=[],C3.TimelineDataManager._CreateDataItems(this._trackDataItems,t,TrackDataItem,this)}Release(){this._timelineDataItem=null;for(const t of this._trackDataItems)t.Release();C3.clearArray(this._trackDataItems),this._trackDataItems=null}GetTimelineDataItem(){return this._timelineDataItem}AddEmptyTrackDataItem(){const t=new TrackDataItem(null,this);return this._trackDataItems.push(t),t}GetFirstKeyframeDataItem(t){return t.GetKeyframeData().GetKeyframeDataItemArray()[0]}GetLastKeyframeDataItem(t){return t.GetKeyframeData().GetKeyframeDataItemArray().at(-1)}GetKeyFrameDataItemAtTime(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray(),s=e.length;for(let a=0;a<s;a++){const s=e[a];if(s.GetTime()===t)return s}}GetFirstKeyFrameDataItemHigherThan(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray(),s=e.length;for(let a=0;a<s;a++){const s=e[a];if(s.GetTime()>t)return s}}GetFirstKeyFrameDataItemHigherOrEqualThan(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray(),s=e.length;for(let a=0;a<s;a++){const s=e[a];if(s.GetTime()>=t)return s}}GetFirstKeyFrameDataItemLowerOrEqualThan(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray();for(let a=e.length-1;a>=0;a--){const s=e[a];if(s.GetTime()<=t)return s}}*trackDataItems(){for(const t of this._trackDataItems)yield t}_SaveToJson(){return{"trackDataItemsJson":this._trackDataItems.map((t=>t._SaveToJson()))}}_LoadFromJson(t){t&&C3.TimelineDataManager._LoadDataItemsFromJson(this._trackDataItems,t["trackDataItemsJson"],TrackDataItem,this)}};
}

// timelines/data/propertyTrackData.js
{
const C3=self.C3,SOURCE_DATA=0,SOURCE=0,PROPERTY=1,TYPE=2,MIN=3,MAX=4,INTERPOLATION_MODE=5,RESULT_MODE=6,ENABLED=7,PROPERTY_KEYFRAMES=8,CAN_HAVE_PROPERTY_KEYFRAMES=9;class PropertyTrackDataItem{constructor(t,e){this._propertyTrackData=e,this._sourceAdapterId="",this._sourceAdapterArguments=null,this._property=null,this._type=null,this._min=NaN,this._max=NaN,this._interpolationMode="default",this._resultMode="default",this._enabled=!1,this._propertyKeyframeData=null,this._canHavePropertyKeyframes=!0,t&&(this._sourceAdapterId=t[0][0],this._sourceAdapterArguments=t[0].slice(1),this._property=t[1],this._type=t[2],this._min=t[3],this._max=t[4],this._interpolationMode=t[5],this._resultMode=t[6],this._enabled=!!t[7],this._propertyKeyframeData=new C3.PropertyKeyframeData(t[8],this),this._canHavePropertyKeyframes=t[9])}Release(){this._propertyKeyframeData.Release(),this._propertyKeyframeData=null,this._propertyTrackData=null,this._sourceAdapterArguments=null}GetPropertyTrackData(){return this._propertyTrackData}GetPropertyKeyframeData(){return this._propertyKeyframeData||(this._propertyKeyframeData=new C3.PropertyKeyframeData(null,this)),this._propertyKeyframeData}GetSourceAdapterId(){return this._sourceAdapterId}SetSourceAdapterId(t){this._sourceAdapterId=t}GetSourceAdapterArguments(){return this._sourceAdapterArguments}SetSourceAdapterArguments(t){this._sourceAdapterArguments=t}GetProperty(){return this._property}SetProperty(t){this._property=t}GetType(){return this._type}SetType(t){this._type=t}GetMin(){return this._min}SetMin(t){this._min=t}GetMax(){return this._max}SetMax(t){this._max=t}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(t){this._interpolationMode=t}GetResultMode(){return this._resultMode}SetResultMode(t){this._resultMode=t}GetEnable(){return this._enabled}SetEnable(t){this._enabled=!!t}CanHavePropertyKeyframes(){return!!this._canHavePropertyKeyframes}_SaveToJson(){return{"propertyKeyframeDataJson":this._propertyKeyframeData._SaveToJson(),"sourceAdapterId":this._sourceAdapterId,"sourceAdapterArguments":this._sourceAdapterArguments,"property":this._property,"type":this._type,"min":this._min,"max":this._max,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,"enabled":this._enabled,"canHavePropertyKeyframes":this._canHavePropertyKeyframes}}_LoadFromJson(t){t&&(this._sourceAdapterId=t["sourceAdapterId"],this._sourceAdapterArguments=t["sourceAdapterArguments"],this._property=t["property"],this._type=t["type"],this._min=t["min"],this._max=t["max"],this._interpolationMode=t["interpolationMode"],this._resultMode=t["resultMode"],this._enabled=t["enabled"],this._canHavePropertyKeyframes=t["canHavePropertyKeyframes"],this.GetPropertyKeyframeData()._LoadFromJson(t["propertyKeyframeDataJson"]))}}C3.PropertyTrackData=class{constructor(t,e){this._trackDataItem=e,this._propertyTrackDataItems=[],C3.TimelineDataManager._CreateDataItems(this._propertyTrackDataItems,t,PropertyTrackDataItem,this)}Release(){this._trackDataItem=null;for(const t of this._propertyTrackDataItems)t.Release();C3.clearArray(this._propertyTrackDataItems),this._propertyTrackDataItems=null}GetTrackDataItem(){return this._trackDataItem}AddEmptyPropertyTrackDataItem(){const t=new PropertyTrackDataItem(null,this);return this._propertyTrackDataItems.push(t),t}GetFirstPropertyKeyframeDataItem(t){return t.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray()[0]}GetLastPropertyKeyframeDataItem(t){return t.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray().at(-1)}GetPropertyKeyFrameDataItemAtTime(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),a=r.length;for(let e=0;e<a;e++){const a=r[e];if(a.GetTime()===t)return a}}GetFirstPropertyKeyFrameDataItemHigherThan(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),a=r.length;for(let e=0;e<a;e++){const a=r[e];if(a.GetTime()>t)return a}}GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),a=r.length;for(let e=0;e<a;e++){const a=r[e];if(a.GetTime()>=t)return a}}GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray();for(let e=r.length-1;e>=0;e--){const a=r[e];if(a.GetTime()<=t)return a}}*propertyTrackDataItems(){for(const t of this._propertyTrackDataItems)yield t}_SaveToJson(){return{"propertyTrackDataItemsJson":this._propertyTrackDataItems.map((t=>t._SaveToJson()))}}_LoadFromJson(t){t&&C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyTrackDataItems,t["propertyTrackDataItemsJson"],PropertyTrackDataItem,this)}};
}

// timelines/data/keyframeData.js
{
const C3=self.C3,TIME=0,EASE=1,ENABLE=2,TAGS=3;class KeyframeDataItem{constructor(e,t){if(this._keyframeData=t,this._time=-1,this._ease="noease",this._enable=!1,this._tags=null,this._lowerTags=null,!e)return;this._time=e[0],this._ease=e[1],this._enable=!!e[2];const a=e[3];this._tags=a?a.split(" "):[],this._lowerTags=new Set(this._tags.map((e=>e.toLowerCase()))),this._next=null,this._last=null}Release(){this._keyframeData=null,C3.clearArray(this._tags),this._tags=null,this._lowerTags.clear(),this._lowerTags=null,this._next=null}GetKeyframeData(){return this._keyframeData}GetNext(){return this._next}SetNext(e){this._next=e}GetLast(){return this._last}SetLast(e){this._last=e}GetTime(){return this._time}SetTime(e){this._time=e,this._keyframeData._LinkKeyframeDataItems()}GetEase(){return this._ease}SetEase(e){this._ease=e}GetEnable(){return this._enable}SetEnable(e){this._enable=!!e}GetTags(){return this._tags}SetTags(e){this._tags=e?e.split(" "):[],this._lowerTags=new Set(this._tags.map((e=>e.toLowerCase())))}GetLowerTags(){return this._lowerTags}HasTag(e){return this._lowerTags.has(e.toLowerCase())}_SaveToJson(){return{"time":this._time,"ease":this._ease,"enable":this._enable,"tags":this._tags}}_LoadFromJson(e){e&&(this._time=e["time"],this._ease=e["ease"],this._enable=e["enable"],this._tags=e["tags"],this._lowerTags=new Set(this._tags.map((e=>e.toLowerCase()))))}}C3.KeyframeData=class{constructor(e,t){this._trackDataItem=t,this._keyframeDataItems=[],C3.TimelineDataManager._CreateDataItems(this._keyframeDataItems,e,KeyframeDataItem,this),this._LinkKeyframeDataItems()}Release(){this._trackDataItem=null;for(const e of this._keyframeDataItems)e.Release();C3.clearArray(this._keyframeDataItems),this._keyframeDataItems=null}_LinkKeyframeDataItems(){this._keyframeDataItems.sort(((e,t)=>e.GetTime()-t.GetTime()));for(let e=0;e<this._keyframeDataItems.length;e++){const t=this._keyframeDataItems[e];t.SetNext(this._keyframeDataItems[e+1]),t.SetLast(this._keyframeDataItems[e-1])}}GetTrackDataItem(){return this._trackDataItem}GetKeyframeDataItemCount(){return this._keyframeDataItems.length}GetKeyframeDataItemArray(){return this._keyframeDataItems}AddEmptyKeyframeDataItem(){const e=new KeyframeDataItem(null,this);return this._keyframeDataItems.push(e),this._LinkKeyframeDataItems(),e}DeleteKeyframeDataItems(e){for(const t of this._keyframeDataItems){if(!e(t))continue;const a=this._keyframeDataItems.indexOf(t);-1!==a&&(t.Release(),this._keyframeDataItems.splice(a,1))}this.SortKeyframeDataItems(),this._LinkKeyframeDataItems()}SortKeyframeDataItems(){this._keyframeDataItems.sort(((e,t)=>e.GetTime()-t.GetTime()))}GetKeyframeDataItemIndex(e){return this._keyframeDataItems.indexOf(e)}GetKeyframeDataItemFromIndex(e){return this._keyframeDataItems[e]}*keyframeDataItems(){for(const e of this._keyframeDataItems)yield e}*keyframeDataItemsReverse(){for(let e=this._keyframeDataItems.length-1;e>=0;e--)yield this._keyframeDataItems[e]}_SaveToJson(){return{"keyframeDataItemsJson":this._keyframeDataItems.map((e=>e._SaveToJson()))}}_LoadFromJson(e){e&&(C3.TimelineDataManager._LoadDataItemsFromJson(this._keyframeDataItems,e["keyframeDataItemsJson"],KeyframeDataItem,this),this._LinkKeyframeDataItems())}};
}

// timelines/data/propertyKeyframeData.js
{
const C3=self.C3,VALUE_DATA=0,VALUE_DATA_VALUE=0,VALUE_DATA_ABSOLUTE_VALUE=1,VALUE_DATA_TYPE=2,TIME=1,EASE=2,ENABLE=3,ADDONS=4,PATH_MODE=5;class PropertyKeyframeDataItem{constructor(e,t){this._propertyKeyframeData=t,this._value=null,this._aValue=null,this._type="",this._time=NaN,this._ease="noease",this._enable=!1,this._addonData=null,this._addonInstance=void 0,this._pathMode="line",e&&(this._value=e[0][0],this._aValue=e[0][1],this._type=e[0][2],this._time=e[1],this._ease=e[2],this._enable=!!e[3],this._pathMode=e[5],this._addonData=null,e[4]&&(this._addonData=new C3.AddonData(e[4],this)),this._next=null,this._prev=null)}Release(){this._propertyKeyframeData=null,this._addonData&&(this._addonData.Release(),this._addonData=null),this._next=null,this._prev=null}GetAddonData(){return this._addonData}SetNext(e){this._next=e}GetNext(){return this._next}SetPrevious(e){this._prev=e}GetPrevious(){return this._prev}GetValue(){return this._value}SetValue(e){"color"===this._type&&C3.IsFiniteNumber(e)?(this._value[0]=C3.GetRValue(e),this._value[1]=C3.GetGValue(e),this._value[2]=C3.GetBValue(e)):this._value=e}GetAbsoluteValue(){return this._aValue}SetAbsoluteValue(e){"color"===this._type&&C3.IsFiniteNumber(e)?(this._aValue[0]=C3.GetRValue(e),this._aValue[1]=C3.GetGValue(e),this._aValue[2]=C3.GetBValue(e)):this._aValue=e}GetValueWithResultMode(){const e=this._propertyKeyframeData.GetPropertyTrackDataItem().GetResultMode();return"relative"===e?this.GetValue():"absolute"===e?this.GetAbsoluteValue():void 0}GetType(){return this._type}SetType(e){this._type=e}GetTime(){return this._time}SetTime(e){this._time=e,this._propertyKeyframeData._LinkPropertyKeyframeDataItems()}GetEase(){return this._ease}SetEase(e){this._ease=e}GetEnable(){return this._enable}SetEnable(e){this._enable=!!e}GetPathMode(){return this._pathMode}GetAddOn(e){if(!this._addonData)return;if(this._addonInstance||null===this._addonInstance)return this._addonInstance;const t=this._addonData.GetAddDataItemArray();if(!t)return this._addonInstance=null,this._addonInstance;const a=t.length;for(let r=0;r<a;r++){const a=t[r];if(a.GetId()===e)return this._addonInstance=a,this._addonInstance}return this._addonInstance=null,this._addonInstance}_SaveToJson(){const e=this._addonData;return{"addonDataJson":e?e._SaveToJson():e,"value":this._value,"aValue":this._aValue,"type":this._type,"time":this._time,"ease":this._ease,"enable":this._enable}}_LoadFromJson(e){e&&(e["addonDataJson"]&&this._addonData._SetFromJson(e["addonDataJson"]),this._value=e["value"],this._aValue=e["aValue"],this._type=e["type"],this._time=e["time"],this._ease=e["ease"],this._enable=e["enable"])}}C3.PropertyKeyframeData=class{constructor(e,t){this._propertyTrackDataItem=t,this._propertyKeyframeDataItems=[],this._propertyKeyframeDataItemsIncludingDisabled=[],C3.TimelineDataManager._CreateDataItems(this._propertyKeyframeDataItems,e,PropertyKeyframeDataItem,this),C3.TimelineDataManager._CreateDataItemsIncludingDisabled(this._propertyKeyframeDataItemsIncludingDisabled,e,PropertyKeyframeDataItem,this),this._LinkPropertyKeyframeDataItems()}Release(){this._propertyTrackDataItem=null;for(const e of this._propertyKeyframeDataItems)e.Release();C3.clearArray(this._propertyKeyframeDataItems),this._propertyKeyframeDataItems=null;for(const e of this._propertyKeyframeDataItemsIncludingDisabled)e.Release();C3.clearArray(this._propertyKeyframeDataItemsIncludingDisabled),this._propertyKeyframeDataItemsIncludingDisabled=null}_LinkPropertyKeyframeDataItems(){let e=this._propertyKeyframeDataItems;e.sort(((e,t)=>e.GetTime()-t.GetTime()));for(let t=0;t<e.length;t++){const a=e[t];t+1<e.length&&a.SetNext(e[t+1]),t-1>=0&&a.SetPrevious(e[t-1])}e=this._propertyKeyframeDataItemsIncludingDisabled,e.sort(((e,t)=>e.GetTime()-t.GetTime()));for(let t=0;t<e.length;t++){const a=e[t];t+1<e.length&&a.SetNext(e[t+1]),t-1>=0&&a.SetPrevious(e[t-1])}}AddEmptyPropertyKeyframeDataItem(){const e=new PropertyKeyframeDataItem(null,this);return this._propertyKeyframeDataItems.push(e),this._LinkPropertyKeyframeDataItems(),e}DeletePropertyKeyframeDataItems(e){for(const t of this._propertyKeyframeDataItems){if(!e(t))continue;const a=this._propertyKeyframeDataItems.indexOf(t);-1!==a&&(t.Release(),this._propertyKeyframeDataItems.splice(a,1))}this.SortPropertyKeyFrameDataItems(),this._LinkPropertyKeyframeDataItems()}SortPropertyKeyFrameDataItems(){this._propertyKeyframeDataItems.sort(((e,t)=>e.GetTime()-t.GetTime()))}GetPropertyTrackDataItem(){return this._propertyTrackDataItem}GetPropertyKeyframeDataItemCount(){return this._propertyKeyframeDataItems.length}GetLastPropertyKeyframeDataItem(){return this._propertyKeyframeDataItems[this._propertyKeyframeDataItems.length-1]}GetPropertyKeyframeDataItemArray(){return this._propertyKeyframeDataItems}GetPropertyKeyframeDataItemArrayIncludingDisabled(){return this._propertyKeyframeDataItemsIncludingDisabled}*propertyKeyframeDataItems(){for(const e of this._propertyKeyframeDataItems)yield e}*propertyKeyframeDataItemsReverse(){for(let e=this._propertyKeyframeDataItems.length-1;e>=0;e--)yield this._propertyKeyframeDataItems[e]}_SaveToJson(){const e=this._propertyKeyframeDataItems,t=this._propertyKeyframeDataItemsIncludingDisabled;return{"propertyKeyframeDataItemsJson":e.map((e=>e._SaveToJson())),"propertyKeyframeDataItemsIncludingDisabledJson":t.map((e=>e._SaveToJson()))}}_LoadFromJson(e){e&&(C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyKeyframeDataItems,e["propertyKeyframeDataItemsJson"],PropertyKeyframeDataItem,this),C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyKeyframeDataItemsIncludingDisabled,e["propertyKeyframeDataItemsIncludingDisabledJson"],PropertyKeyframeDataItem,this),this._LinkPropertyKeyframeDataItems())}};
}

// timelines/data/propertyKeyframeAddonData.js
{
const C3=self.C3,ADDON_ID=0,ADDON_DATA=1;class AddonDataItem{constructor(t,a){this._addonData=a,this._id=t[0],this._data=t[1]}Release(){this._addonData=null,this._data=null}GetAddonData(){return this._addonData}GetId(){return this._id}_SaveToJson(){return{"id":this._id,"data":this._data}}_LoadFromJson(t){t&&(this._id=t["id"],this._data=t["data"])}}const START_ANCHOR=0,START_ENABLE=1,END_ANCHOR=2,END_ENABLE=3;class AddonDataCubicBezierItem extends AddonDataItem{constructor(t,a){super(t,a),this._startAnchor=this._data[0],this._startEnable=!!this._data[1],this._endAnchor=this._data[2],this._endEnable=!!this._data[3]}Release(){super.Release()}GetStartAnchor(){return this._startAnchor}GetStartEnable(){return this._startEnable}GetEndAnchor(){return this._endAnchor}GetEndEnable(){return this._endEnable}_SaveToJson(){return Object.assign(super._SaveToJson(),{"startAnchor":this._startAnchor,"startEnable":!!this._startEnable,"endAnchor":this._endAnchor,"endEnable":!!this._endEnable})}_LoadFromJson(t){t&&(super._LoadFromJson(t),this._startAnchor=t["startAnchor"],this._startEnable=!!t["startEnable"],this._endAnchor=t["endAnchor"],this._endEnable=!!t["endEnable"])}}const DIRECTION=0,REVOLUTIONS=1;class AddonDataAngleItem extends AddonDataItem{constructor(t,a){super(t,a),this._direction=this._data[0],this._revolutions=this._data[1]}Release(){super.Release()}GetDirection(){return this._direction}GetRevolutions(){return this._revolutions}_SaveToJson(){return Object.assign(super._SaveToJson(),{"direction":this._direction,"revolutions":this._revolutions})}_LoadFromJson(t){t&&(super._LoadFromJson(t),this._direction=t["direction"],this._revolutions=t["revolutions"])}}C3.AddonData=class{constructor(t,a){this._propertyKeyframeDataItem=a,this._addonDataItems=[],C3.TimelineDataManager._CreateDataItems(this._addonDataItems,t,{prop:0,map:new Map([["cubic-bezier",AddonDataCubicBezierItem],["angle",AddonDataAngleItem]])},this)}Release(){this._propertyKeyframeDataItem=null;for(const t of this._addonDataItems)t.Release();C3.clearArray(this._addonDataItems),this._addonDataItems=null}GetPropertyKeyframeDataItem(){return this._propertyKeyframeDataItem}GetAddDataItemArray(){return this._addonDataItems}*addonDataItems(){for(const t of this._addonDataItems)yield t}_SaveToJson(){return{"addonDataItemsJson":this._addonDataItems.map((t=>t._SaveToJson()))}}_LoadFromJson(t){t&&C3.TimelineDataManager._LoadDataItemsFromJson(this._addonDataItems,t["addonDataItemsJson"],{prop:"id",map:new Map([["cubic-bezier",AddonDataCubicBezierItem],["angle",AddonDataAngleItem]])},this)}};
}

// timelines/tweens/tweenState.js
{
const C3=self.C3,INITIAL_VALUE_MODE_START_VALUE="start-value",INITIAL_VALUE_MODE_CURRENT_STATE="current-state",PING_PONG_BEGIN=0,PING_PONG_END=1;let createdTweens=0;C3.TweenState=class extends C3.TimelineState{constructor(e,t){super("tween-"+createdTweens++,e,t),this._id="",this._destroyInstanceOnComplete=!1,this._initialValueMode="start-value",this._instance=null,this._on_completed_callbacks=null,this._on_started_callbacks=null,this._behInst=null,this._track=null,this._iTweenState=null}FireReleaseEvent(e){const t=C3.New(C3.Event,"tweenstatereleased");t.tweenState=this,e.dispatchEvent(t)}GetType(){return 1}CreateTrackStates(){for(const e of this._timelineDataItem.GetTrackData().trackDataItems())this._tracks.push(C3.TweenTrackState.Create(this,e));this._track=this._tracks[0]}AddTrack(){const e=this._timelineDataItem.GetTrackData().AddEmptyTrackDataItem(),t=C3.TweenTrackState.Create(this,e);return this._tracks.push(t),this._CacheTrack(),t}_CacheTrack(){this._track=this._tracks[0]}GetPropertyTrack(e){return this._track.GetPropertyTracks()[0]}SetPropertyType(e){this._propertyType=e}GetInstance(){const e=this.GetTracks();if(!e||!e.length)return;const t=e[0];if(this._track=t,!t)return;const n=t.GetInstance();return t.IsInstanceValid()?n:void 0}SetBehaviorInstance(e){this._behInst=e}AddStartedCallback(e){this._on_started_callbacks||(this._on_started_callbacks=[]),this._on_started_callbacks.push(e)}AddCompletedCallback(e){this._on_completed_callbacks||(this._on_completed_callbacks=[]),this._on_completed_callbacks.push(e)}RemoveStartedCallback(e){if(!this._on_started_callbacks)return;const t=this._on_started_callbacks.indexOf(e);-1!==t&&this._on_started_callbacks.splice(t,1)}RemoveCompletedCallback(e){if(!this._on_completed_callbacks)return;const t=this._on_completed_callbacks.indexOf(e);-1!==t&&this._on_completed_callbacks.splice(t,1)}SetStartValue(e,t){for(const n of this._tracks)for(const s of n._propertyTracks){if(s.GetPropertyName()!==t)continue;const n=s.GetPropertyTrackData(),i=s.GetPropertyTrackDataItem(),a=n.GetFirstPropertyKeyframeDataItem(i);a.SetValue(e),a.SetAbsoluteValue(e)}}_GetPropertyTrackState(e){for(const t of this._tracks)for(const n of t._propertyTracks)if(n.GetPropertyName()===e)return n}BeforeSetEndValues(e){for(const t of e){const e=this._GetPropertyTrackState(t);this.SetStartValue(e.GetCurrentState(),t)}if(this.IsForwardPlayBack()){const e=this.GetTotalTime()-this.GetTime();this.SetTotalTime(e);for(const t of this._tracks)t.SetLocalTotalTime(e);this._SetTime(0)}else{const e=this.GetTime();this.SetTotalTime(e);for(const t of this._tracks)t.SetLocalTotalTime(e);this._SetTime(e)}this.SetInitialStateFromSetTime()}SetEndValue(e,t){const n=this._GetPropertyTrackState(t),s=n.GetPropertyTrackData(),i=n.GetPropertyTrackDataItem(),a=s.GetLastPropertyKeyframeDataItem(i);a.SetTime(this.GetTotalTime()),a.SetValue(e),a.SetAbsoluteValue(e)}SetId(e){this._id=e}GetId(){return this._id}SetInitialValueMode(e){this._initialValueMode=e}GetInitialValueMode(){return this._initialValueMode}SetDestroyInstanceOnComplete(e){this._destroyInstanceOnComplete=e}GetDestroyInstanceOnComplete(){return this._destroyInstanceOnComplete}OnStarted(){if(this._on_started_callbacks)for(const e of this._on_started_callbacks)e(this);if(!this.IsComplete())for(const e of this._tracks)e.CompareSaveStateWithCurrent()}OnCompleted(){this._completedTick=this._runtime.GetTickCount()}FinishTriggers(){if(!this._finishedTriggers&&(this._finishedTriggers=!0,this._on_completed_callbacks))for(const e of this._on_completed_callbacks)e(this)}SetTime(e){this._DeleteIntermediateKeyframes(),super.SetTime(e)}_SetTimeAndReset(e){C3.IsFiniteNumber(e)||(e=this.GetTotalTime()),e<0?this._playheadTime=0:e>=this.GetTotalTime()?this._playheadTime=this.GetTotalTime():this._playheadTime=e,this._track.SetResetState()}SetInitialState(e){if(!this.InitialStateSet()&&"current-state"===this.GetInitialValueMode())for(const e of this._tracks)e.CompareInitialStateWithCurrent();super.SetInitialState(e)}Stop(e=!1){if(super.Stop(e),!this.IsComplete())for(const e of this._tracks)e.SaveState()}Reset(e=!0,t=!1){this._DeleteIntermediateKeyframes(),super.Reset(e,t)}_DeleteIntermediateKeyframes(){for(const e of this._tracks){const t=e=>{const t=e.GetTime(),n=this.GetTotalTime();return 0!==t&&t!==n};e.DeleteKeyframes(t),e.DeletePropertyKeyframes(t)}}_OnBeforeChangeLayout(){if(this.IsReleased())return!0;const e=this.GetInstance();return(!e||!e.GetObjectClass().IsGlobal())&&(this._timelineManager.CompleteTimelineBeforeChangeOfLayout(this),this.ResetBeforeChangeLayout(),!0)}Tick(e,t,n){if(this._instance||(this._instance=this.GetInstance()),!this._instance||this._instance.IsDestroyed())return this.Stop(!0),void this.OnCompleted();const s=this._instance.GetTimeScale();if(-1!==s&&(e=n*s),0===e&&0===this._lastDelta)return;this._lastDelta=e;const i=this._playheadTime+this._overshoot+e*this._playbackRate,a=this._timelineDataItem._totalTime;i<0?(this._playheadTime=0,this._overshoot=-i):i>=a?(this._playheadTime=a,this._overshoot=this._playheadTime-i):(this._playheadTime=i,this._overshoot=0);let r=!1,o=!1;const h=this.GetLoop(),T=this.GetPingPong();if(h||T?h&&!T?this._playbackRate>0?this._playheadTime>=a&&(this._SetTimeAndReset(0),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),o=!0):this._playheadTime<=0&&(this._SetTimeAndReset(a),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),o=!0):!h&&T?this._playbackRate>0?this._playheadTime>=a&&(this._SetTime(a),this.SetPlaybackRate(-1*this.GetPlaybackRate()),o=!0,1===this._pingPongState?this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong),this.IsPlaying()?this._pingPongState=0:this._resumePingPongState=0):(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong),r=!0):0===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong),this.IsPlaying()?this._pingPongState=1:this._resumePingPongState=1)):this._playheadTime<=0&&(this._SetTime(0),this.SetPlaybackRate(-1*this.GetPlaybackRate()),o=!0,1===this._pingPongState?this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong),this.IsPlaying()?this._pingPongState=0:this._resumePingPongState=0):(r=!0,this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)):0===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong),this.IsPlaying()?this._pingPongState=1:this._resumePingPongState=1)):h&&T&&(this._playbackRate>0?this._playheadTime>=a&&(this._SetTime(a),this.SetPlaybackRate(-1*this.GetPlaybackRate()),o=!0,0===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)),1===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)),this.IsPlaying()?(this._pingPongState++,this._pingPongState=C3.wrap(this._pingPongState,0,2)):(this._resumePingPongState=this._pingPongState+1,this._resumePingPongState=C3.wrap(this._resumePingPongState,0,2))):this._playheadTime<=0&&(this._SetTime(0),this.SetPlaybackRate(-1*this.GetPlaybackRate()),o=!0,0===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)),1===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)),this.IsPlaying()?(this._pingPongState++,this._pingPongState=C3.wrap(this._pingPongState,0,2)):(this._resumePingPongState=this._pingPongState+1,this._resumePingPongState=C3.wrap(this._resumePingPongState,0,2)))):this._playbackRate>0?this._playheadTime>=a&&(this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._SetTimeAndReset(0),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),o=!0):(this._SetTime(a),r=!0)):this._playheadTime<=0&&(this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._SetTimeAndReset(a),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),o=!0):(this._SetTime(0),r=!0)),this.IsPlaying()){if(r)return this._track.SetEndState(),this.Stop(!0),void this.OnCompleted();this._track.Interpolate(this._playheadTime,!0,!1,o,this._firstTick,!1),this._firstTick&&(this._firstTick=!1)}}_TweenTrigger(e){const t=this.GetInstance();this._behInst.PushTriggerTween(this),this._runtime.Trigger(e,t,this._behInst.GetBehaviorType()),this._behInst.PopTriggerTween()}_SaveToJson(){const e=super._SaveToJson(),t=this.GetTimelineDataItem();return Object.assign(e,{"tweenDataItemJson":t._SaveToJson(),"id":this._id,"destroyInstanceOnComplete":this._destroyInstanceOnComplete,"initialValueMode":this._initialValueMode})}_LoadFromJson(e){if(!e)return;this.GetTimelineDataItem()._LoadFromJson(e["tweenDataItemJson"]),super._LoadFromJson(e),this._id=e["id"],this._destroyInstanceOnComplete=e["destroyInstanceOnComplete"],this._initialValueMode=e["initialValueMode"],this._CacheTrack()}static IsPlaying(e){return e.IsPlaying()}static IsPaused(e){return e.IsPaused()}static IsPing(e){return!!e.GetPingPong()&&0===e.GetPingPongState()}static IsPong(e){return!!e.GetPingPong()&&1===e.GetPingPongState()}static Build(e){const t=e.runtime.GetTimelineManager(),n=new C3.TimelineDataItem;if(e.json){n._LoadFromJson(e.json["tweenDataItemJson"]);const s=new C3.TweenState(n,t);return s._LoadFromJson(e.json),s}{const s=new C3.TweenState(n,t);C3.IsArray(e.propertyTracksConfig)||(e.propertyTracksConfig=[e.propertyTracksConfig]),s.SetId(e.id),s.SetTags(e.tags),s.SetInitialValueMode(e.initialValueMode),s.SetDestroyInstanceOnComplete(e.releaseOnComplete),s.SetLoop(e.loop),s.SetPingPong(e.pingPong),s.SetTotalTime(e.time),s.SetStep(0),s.SetInterpolationMode("default"),s.SetResultMode(e.propertyTracksConfig[0].resultMode),s.SetRepeatCount(e.repeatCount);const i=s.AddTrack();i.SetInstanceUID(e.instance.GetUID()),i.SetInterpolationMode("default"),i.SetResultMode(e.propertyTracksConfig[0].resultMode),i.SetEnable(!0),i.SetObjectClassIndex(e.instance.GetObjectClass().GetIndex());const a=e.instance.GetSdkInstance(),r=a.IsOriginalSizeKnown()?a.GetOriginalWidth():e.instance.GetWorldInfo().GetWidth(),o=a.IsOriginalSizeKnown()?a.GetOriginalHeight():e.instance.GetWorldInfo().GetHeight();i.SetOriginalWidth(r),i.SetOriginalHeight(o);const h=i.AddKeyframe();h.SetTime(0),h.SetEase("noease"),h.SetEnable(!0),h.SetTags("");const T=i.AddKeyframe();T.SetTime(e.time),T.SetEase("noease"),T.SetEnable(!0),T.SetTags("");for(const t of e.propertyTracksConfig){const n=i.AddPropertyTrack();n.SetSourceAdapterId(t.sourceId),n.SetSourceAdapterArgs(t.sourceArgs),n.SetPropertyName(t.property),n.SetPropertyType(t.type),n.SetMin(NaN),n.SetMax(NaN),n.SetInterpolationMode("default"),n.SetResultMode(t.resultMode),n.SetEnable(!0);const s=n.AddPropertyKeyframe();s.SetType(t.valueType),s.SetTime(0),s.SetEase(t.ease),s.SetEnable(!0),s.SetValue(t.startValue),s.SetAbsoluteValue(t.startValue);const a=n.AddPropertyKeyframe();a.SetType(t.valueType),a.SetTime(e.time),a.SetEase(t.ease),a.SetEnable(!0),a.SetValue(t.endValue),a.SetAbsoluteValue(t.endValue),n.GetSourceAdapter()}return s}}static SetInstanceUID(e,t){if(!isNaN(t))for(const n of e.GetTracks())n.SetInstanceUID(t)}static SetBehaviorInstance(e,t){e.SetBehaviorInstance(t)}GetITweenState(e,t){return this._iTweenState||(this._iTweenState=C3.New(self.ITweenState,this,e,t)),this._iTweenState}};
}

// timelines/tweens/tweenTrackState.js
{
const C3=self.C3;C3.TweenTrackState=class extends C3.TrackState{constructor(t,e){super(t,e),this._firstPropertyTrack=null,this._secondPropertyTrack=null}static Create(t,e){return C3.New(C3.TweenTrackState,t,e)}_CachePropertyTracks(){1===this._propertyTracks.length?this._firstPropertyTrack=this._propertyTracks[0]:(this._firstPropertyTrack=this._propertyTracks[0],this._secondPropertyTrack=this._propertyTracks[1])}CreatePropertyTrackStates(){for(const t of this._trackDataItem.GetPropertyTrackData().propertyTrackDataItems())this._propertyTracks.push(C3.TweenPropertyTrackState.Create(this,t));this._CachePropertyTracks()}AddPropertyTrack(){const t=this._trackDataItem.GetPropertyTrackData().AddEmptyPropertyTrackDataItem(),e=C3.TweenPropertyTrackState.Create(this,t);return this._propertyTracks.push(e),this._CachePropertyTracks(),e}SetInitialState(){if(this.MaybeGetInstance(),!this.IsInstanceValid()&&this.IsInstanceTrack())return;const t=this.GetTimeline().IsForwardPlayBack()?0:this.GetLocalTotalTime();for(const e of this._propertyTracks)e.SetInitialState(t),0===this._worldInfoChange&&1===e.GetWorldInfoChange()&&(this._worldInfoChange=1),0===this._renderChange&&1===e.GetRenderChange()&&(this._renderChange=1);this._needsBeforeAndAfter=0;this._propertyTracks.some((t=>t.GetNeedsBeforeAndAfter()))&&(this._needsBeforeAndAfter=1),this._lastKeyframeDataItem=this._GetLastKeyFrameBeforeTime(t),this._initialStateOfNestedSet=!1,this._endStateOfNestedSet=!1,this.Interpolate(t)}BeforeInterpolate(){}Interpolate(t,e=!1,r=!1,s=!1,a=!1,o=!1,n=!1){if(this._instance||this.GetInstance(),!this._instance)return;return!this._instance.IsDestroyed()&&((!o||!this.GetObjectClass().IsGlobal())&&(this._secondPropertyTrack?(this._firstPropertyTrack.Interpolate(t,r,s,n),this._secondPropertyTrack.Interpolate(t,r,s,n)):this._firstPropertyTrack.Interpolate(t,r,s,n),void(0!==this._firstPropertyTrack.GetWorldInfoChange()&&(this._worldInfo||(this._worldInfo=this._instance.GetWorldInfo()),this._worldInfo&&this._worldInfo.SetBboxChanged()))))}AfterInterpolate(){}_LoadFromJson(t){super._LoadFromJson(t),this._CachePropertyTracks()}};
}

// timelines/tweens/tweenPropertyTrackState.js
{
const C3=self.C3;C3.TweenPropertyTrackState=class extends C3.PropertyTrackState{constructor(t,e){super(t,e),this._basic=!1}static Create(t,e){return C3.New(C3.TweenPropertyTrackState,t,e)}Interpolate(t,e=!1,r=!1,a=!1){let s,o;if(this._basic)s=this._propertyKeyframeDataItems[0],o=this._propertyKeyframeDataItems[1];else if(e)s=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,this._propertyTrackDataItem),o=s.GetNext();else{if(this._lastPropertyKeyframeDataItem){const e=this.GetTimeline(),r=this._lastPropertyKeyframeDataItem.GetNext(),a=this._lastPropertyKeyframeDataItem.GetTime(),s=r?r.GetTime():e.GetTotalTime();(t<=a||t>=s)&&(this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,this._propertyTrackDataItem))}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,this._propertyTrackDataItem);s=this._lastPropertyKeyframeDataItem,o=s.GetNext()}this._sourceAdapter.Interpolate(t,s,o,e,r,a)}AddPropertyKeyframe(){const t=this._propertyTrackDataItem.GetPropertyKeyframeData().AddEmptyPropertyKeyframeDataItem();return this._lastPropertyKeyframeDataItem=null,this._basic=this.GetPropertyKeyframeDataItems().length<=2,t}DeletePropertyKeyframes(t){this._lastPropertyKeyframeDataItem=null;this._propertyTrackDataItem.GetPropertyKeyframeData().DeletePropertyKeyframeDataItems(t),this._basic=this.GetPropertyKeyframeDataItems().length<=2}_SaveToJson(){return{"sourceAdapterJson":this.GetSourceAdapter()._SaveToJson(),"basic":this._basic}}_LoadFromJson(t){t&&(this.GetSourceAdapter()._LoadFromJson(t["sourceAdapterJson"]),this._basic=t["basic"])}};
}

// timelines/transitions/transition.js
{
const C3=self.C3,Ease=self.Ease,NAME=0,TRANSITION_KEYFRAMES=1,LINEAR=2;C3.Transition=class extends C3.DefendedBase{constructor(e,t=!0){super(),this._name=e[0],this._linear=e[2],this._transitionKeyframes=[];for(const t of e[1]){const e=C3.TransitionKeyframe.Create(this,t);this._transitionKeyframes.push(e)}for(let e=0;e<this._transitionKeyframes.length;e++){const t=this._transitionKeyframes[e],a=this._transitionKeyframes[e+1],s=this._transitionKeyframes[e-1];t.SetNext(a),t.SetPrevious(s)}this._precalculatedSamples=new Map,this._transitionKeyframeCache=new Map,this._PreCalcSamples(),t&&Ease.AddCustomEase(this._name,((e,t,a,s)=>this.Interpolate(e,t,a,s)),null,{transition:this})}static Create(e){return C3.New(C3.Transition,e)}Release(){for(const e of this._transitionKeyframes)e.Release();C3.clearArray(this._transitionKeyframes),this._transitionKeyframes=null,this._precalculatedSamples.clear(),this._precalculatedSamples=null,this._transitionKeyframeCache.clear(),this._transitionKeyframeCache=null}MakeLinear(e){this._linear=!!e}GetTransitionKeyFrameAt(e){const t=this._transitionKeyframeCache.get(e);if(t)return t;for(const t of this._transitionKeyframes)if(t.GetValueX()===e)return this._transitionKeyframeCache.set(e,t),t}GetFirstTransitionKeyFrameLowerOrEqualThan(e){for(let t=this._transitionKeyframes.length-1;t>=0;t--){const a=this._transitionKeyframes[t],s=a.GetValueX();if(s<=e){let t=a;if(s<e)return t;if(s===e){for(;t;){const e=t.GetPrevious();if(!e)break;if(e.GetValueX()!==t.GetValueX())break;t=e}return t}}}}Interpolate(e,t,a,s){let n=e/s;if(this._linear){const n=this.GetTransitionKeyFrameAt(0),r=this.GetTransitionKeyFrameAt(1),i=t+(t+a)*n.GetValueY(),l=(t+a)*r.GetValueY()-i;return 0===s?i+l:Ease.NoEase(e,i,l,s)}0===s&&(n=1);let r=this.GetFirstTransitionKeyFrameLowerOrEqualThan(n),i=r.GetNext();if(!i){const e=r.GetPrevious(),t=r;r=e,i=t}const l=i.GetValueX()-r.GetValueX(),o=C3.mapToRange(n,r.GetValueX(),i.GetValueX(),0,l);if(r.IsSegmentLinear()||0===l){const e=t+(t+a)*r.GetValueY(),s=(t+a)*i.GetValueY()-e;return 0===l?1===o?e+s:e:Ease.NoEase(o,e,s,l)}const h=r.GetValueX(),u=r.GetValueY(),c=r.GetValueX()+r.GetStartAnchorX(),f=r.GetValueY()+r.GetStartAnchorY(),G=i.GetValueX()+i.GetEndAnchorX(),m=i.GetValueY()+i.GetEndAnchorY(),_=i.GetValueX(),y=i.GetValueY();let K=Ease.GetRuntimeEase("spline")(o,h,u,c,f,G,m,_,y,this._precalculatedSamples.get(r));return K+=r.GetValueY(),(1-K)*t+K*(t+a)}_PreCalcSamples(){this._precalculatedSamples.clear();for(let e=0;e<this._transitionKeyframes.length-1;e++){const t=this._transitionKeyframes[e];if(!t.GetStartEnable())continue;const a=t,s=this._transitionKeyframes[e+1];if(!s.GetEndEnable())continue;const n=a.GetValueX(),r=a.GetValueX()+a.GetStartAnchorX(),i=s.GetValueX()+s.GetEndAnchorX(),l=s.GetValueX();this._precalculatedSamples.set(a,Ease.GetBezierSamples(n,r,i,l))}}};
}

// timelines/transitions/transitionKeyframe.js
{
const C3=self.C3,VALUE_X=0,VALUE_Y=1,START_ANCHOR_X=2,START_ANCHOR_Y=3,END_ANCHOR_X=4,END_ANCHOR_Y=5,START_ENABLE=6,END_ENABLE=7,SEGMENT_MODE=8;C3.TransitionKeyframe=class extends C3.DefendedBase{constructor(t,e){super(),this._transition=t,this._valueX=e[0],this._valueY=e[1],this._startAnchorX=e[2],this._startAnchorY=e[3],this._endAnchorX=e[4],this._endAnchorY=e[5],this._startEnable=e[6],this._endEnable=e[7],this._segmentMode=e[8],this._next=null,this._prev=null}Release(){this._transition=null}static Create(t,e){return C3.New(C3.TransitionKeyframe,t,e)}SetNext(t){this._next=t}GetNext(){return this._next}SetPrevious(t){this._prev=t}GetPrevious(){return this._prev}GetValueX(){return this._valueX}GetValueY(){return this._valueY}GetStartAnchorX(){return this._startAnchorX}GetStartAnchorY(){return this._startAnchorY}GetEndAnchorX(){return this._endAnchorX}GetEndAnchorY(){return this._endAnchorY}GetStartEnable(){return this._startEnable}GetEndEnable(){return this._endEnable}IsSegmentLinear(){return"linear"===this._segmentMode}IsSegmentCubic(){return"cubic"===this._segmentMode}};
}

// timelines/transitions/transitionManager.js
{
const C3=self.C3;C3.TransitionManager=class extends C3.DefendedBase{constructor(s){super(),this._runtime=s,this._transitions=[]}Release(){for(const s of this._transitions)s.Release();C3.clearArray(this._transitions),this._transitions=null}Create(s){this._transitions.push(C3.Transition.Create(s))}};
}

// templates/templateManager.js
{
const C3=self.C3;C3.TemplateManager=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e,this._templateDataMap=null,this._instanceToTemplateNameMap=null,this._instanceDestroy=e=>this._OnInstanceDestroy(e.instance)}Release(){if(this.RemoveRuntimeListeners(),this._templateDataMap){for(const e of this._templateDataMap.values())e.clear();this._templateDataMap.clear()}this._templateDataMap=null,this._runtime=null}Create(e){if(this._templateDataMap||(this._templateDataMap=new Map),!e)return;const t=e[0][16][0],a=e[1];this._templateDataMap.has(a)||this._templateDataMap.set(a,new Map);this._templateDataMap.get(a).set(t,e)}AddRuntimeListeners(){const e=this._runtime.Dispatcher();e&&e.addEventListener("instancedestroy",this._instanceDestroy)}RemoveRuntimeListeners(){const e=this._runtime.Dispatcher();e&&e.removeEventListener("instancedestroy",this._instanceDestroy)}HasTemplates(){return!!this._templateDataMap&&0!==this._templateDataMap.size}GetTemplateData(e,t){let a=0;if(a=e instanceof C3.ObjectClass?e.GetIndex():e,!this._templateDataMap.has(a))return;const s=this._templateDataMap.get(a).get(t);return s?JSON.parse(JSON.stringify(s)):void 0}MapInstanceToTemplateName(e,t){this._instanceToTemplateNameMap||(this._instanceToTemplateNameMap=new WeakMap),this._instanceToTemplateNameMap.has(e)||this._instanceToTemplateNameMap.set(e,t)}GetInstanceTemplateName(e){if(!this._instanceToTemplateNameMap)return"";const t=this._instanceToTemplateNameMap.get(e);return t||""}_OnInstanceDestroy(e){this._instanceToTemplateNameMap&&this._instanceToTemplateNameMap.has(e)&&this._instanceToTemplateNameMap.delete(e)}};
}

// flowcharts/flowchartManager.js
{
const C3=self.C3;C3.FlowchartManager=class{constructor(a){this._runtime=a,this._flowchartDataManager=new C3.FlowchartDataManager}Release(){this._flowchartDataManager.Release(),this._flowchartDataManager=null,this._runtime=null}GetRuntime(){return this._runtime}Create(a){this._flowchartDataManager.Add(a)}GetFlowchartDataItemByName(a){return this._flowchartDataManager.Get(a)}HasFlowcharts(){return this._flowchartDataManager.HasFlowcharts()}};
}

// flowcharts/state/flowchartState.js
{
const C3=self.C3;C3.FlowchartState=class{constructor(t,e,r,a,o,h,s){this._runtime=o.GetRuntime(),this._flowchartManager=o,this._flowchartName=t,this._startNodeTag=r,this._flowchartDataItem=a,this._tag=e,this._pluginInstance=h,this._pluginUID=s??h.GetInstance().GetUID(),this._SetStartFlowchartNode(),this._currentFlowchartNodeId=this._startFlowchartNode?.GetFlowchartId()??-1,this._previousFlowchartNodeIds=[],this._previousFlowchartState=null,this._previousFlowchartStateStartNodeId=NaN,this._referenceFlowchartStates=null,this._currentReferenceFlowchartState=null,this._rootFlowchartState=null,this._previousFlowchartStateTag="",this._referenceFlowchartStatesJson=null,this._currentReferenceFlowchartStateTag="",this._rootFlowchartStateTag="",this._triggerCount=0,this._markForRelease=!1,this._released=!1}Release(){this._released||(C3.clearArray(this._previousFlowchartNodeIds),this._previousFlowchartNodeIds=null,this._runtime=null,this._flowchartManager=null,this._flowchartDataItem=null,this._pluginInstance=null,this._previousFlowchartState=null,this._previousFlowchartStateStartNodeId=NaN,this._referenceFlowchartStates&&this._referenceFlowchartStates.clear(),this._referenceFlowchartStates=null,this._currentReferenceFlowchartState=null,this._rootFlowchartState=null,this._previousFlowchartStateTag="",this._referenceFlowchartStatesJson=null,this._currentReferenceFlowchartStateTag="",this._rootFlowchartStateTag="",this._released=!0)}WasReleased(){return this._released}GetFlowchartManager(){return this._flowchartManager}GetRuntime(){return this._runtime}GetName(){return this._flowchartName}GetFlowchartDataItem(){return this._flowchartDataItem}GetTag(){return this._tag}GetPluginInstance(){return this._pluginInstance||(this._pluginInstance=this._runtime.GetInstanceByUID(this._pluginUID).GetSdkInstance()),this._pluginInstance}GetCurrentNode(){return this.GetFlowchartElementById(this._currentFlowchartNodeId)}GetCurrentNodeTag(){const t=this.GetCurrentNode();return t?t.GetTag():""}GetCurrentNodeTags(){const t=this.GetCurrentNode();return t?t.GetTags():[]}CurrentNodeHasTags(t){const e=this.GetCurrentNodeTags();if(!e)return!1;if(!e.length)return!1;const r=C3.FlowchartState._GetTagArray(t);return!(!r||!r.length)&&r.every(C3.FlowchartState._HasTag,e)}CurrentNodeCompareTags(t,e){const r=this.GetCurrentNodeTags();if(!r)return!1;if(!r.length)return!1;const a=C3.FlowchartState._GetTagArray(t);return!(!a||!a.length)&&a.every((t=>C3.FlowchartState._CompareTag.call(r,t,e)))}static _HasTag(t){const e=this;return""===t?1===e.length&&""===e[0]:e.map((t=>t.trim().toLowerCase())).includes(t.trim().toLowerCase())}static _GetTagArray(t){return t.trim().split(" ")}static _CompareTag(t,e){const r=this;return""===t?1===r.length&&""===r[0]:r.some((r=>C3.compare(r.trim(),e,t.trim())))}GetCurrentNodeParent(t){const e=this.GetCurrentNode();if(e){if(C3.IsFiniteNumber(t)){const r=e.GetParentFlowchartIds(),a=r?r[t]:void 0;if(C3.IsFiniteNumber(a))return this.GetFlowchartElementById(a)}if("string"==typeof t)for(const r of e.GetParentFlowchartIds()){const e=this.GetFlowchartElementById(r);if(e.HasTags(t))return this.GetFlowchartElementById(e.GetFlowchartId())}}}GetCurrentNodeParentTag(t){const e=this.GetCurrentNodeParent(t);return e?e.GetTag():""}GetCurrentNodeParentTags(t){const e=this.GetCurrentNodeParent(t);return e?e.GetTags():""}GetCurrentNodeParentIndex(t){const e=this.GetCurrentNode();if(!e)return-1;const r=e.GetParentFlowchartIds();if(!r)return-1;const a=this.GetCurrentNodeParent(t);return a?r.indexOf(a.GetFlowchartId()):-1}GetCurrentNodeParentCount(){const t=this.GetCurrentNode();if(!t)return 0;const e=t.GetParentFlowchartIds();return e?e.length:0}GetFlowchartElementById(t){return this._flowchartDataItem.GetFlowchartElementById(t)}Reset(){this._GetRootFlowchartState()._Reset(!0)}_Reset(t){if(this._GetReferenceFlowchartStates()){for(const[t,e]of this._GetReferenceFlowchartStates().entries())e._Reset(!1);this._GetReferenceFlowchartStates().clear()}if(this._referenceFlowchartStates=null,this._previousFlowchartState=null,this._previousFlowchartStateStartNode=null,this._currentReferenceFlowchartState=null,this._previousFlowchartStateTag="",this._referenceFlowchartStatesJson=null,this._currentReferenceFlowchartStateTag="",this._rootFlowchartStateTag="",this._previousFlowchartNodeIds=[],t){this._flowchartManager.SetCurrentFlowchartState(this);const t=this._startFlowchartNode.GetFlowchartId();t!==this._currentFlowchartNodeId&&this._GotoFlowchartNode(t)}else this._currentFlowchartNodeId=this._startFlowchartNode.GetFlowchartId()}GetCurrentNodeOutputCount(){const t=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);return t?t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItemCount():0}IsIndexOfDefaultOutput(t){return!(t<0)&&t===this.GetDefaultOutputIndex()}GetDefaultOutputIndex(){const t=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);if(!t)return-1;let e=t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDefault();return e?t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems().indexOf(e):-1}GetCurrentNodeOutputNameAt(t){const e=this._GetFlowchartNodeOutputAt(t);return e?e.GetName():""}GetCurrentNodeOutputValueAt(t){let e;return C3.IsFiniteNumber(t)&&(e=this._GetFlowchartNodeOutputAt(t)),"string"==typeof t&&(e=this._GetFlowchartNodeOutputByName(t)),"number"!=typeof t&&"string"!=typeof t&&console.warn("[Flowcharts] unexpected argument type in GetCurrentNodeOutputValueAt expression"),e?e.GetValue():""}_MaybeByPassNodes(t,e){if(t.GetEnable())return t.GetFlowchartId();{const r=t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDefault();if(!r)return e.GetFlowchartId();const a=r.GetConnectedFlowchartNodeFlowchartId();if(!C3.IsFiniteNumber(a))return e.GetFlowchartId();const o=this.GetFlowchartElementById(a);return o?this._MaybeByPassNodes(o,e):e.GetFlowchartId()}}_MaybeByPassNodesInReferenceFlowchart(t,e){if(t.GetEnable()){if("reference"===t.GetType()){const e=t.GetReferenceFlowchartName(),r=t.GetReferenceFlowchartStartNodeTag(),a=this._flowchartManager.GetFlowchartDataItemByName(e);if(!a)return[-1,null];const o=a.GetFlowchartNodeByTags(r);return o?this._MaybeByPassNodesInReferenceFlowchart(o,a):this._MaybeByPassNodesInReferenceFlowchart(a.GetFlowchartStartNode(),a)}return[t.GetFlowchartId(),e]}{const r=t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDefault();if(!r)return[-1,null];const a=r.GetConnectedFlowchartNodeFlowchartId();if(!C3.IsFiniteNumber(a))return[-1,null];const o=e.GetFlowchartElementById(a);return o?this._MaybeByPassNodesInReferenceFlowchart(o,e):[-1,null]}}_ProcessAllByPasses(t,e){let r=this.GetFlowchartElementById(t);if(r){if(!r.GetEnable()){const e=this.GetFlowchartElementById(this._currentFlowchartNodeId);t=this._MaybeByPassNodes(r,e)}if(C3.IsFiniteNumber(t)&&t!==this._currentFlowchartNodeId)if(r=this.GetFlowchartElementById(t),"reference"===r.GetType()){const a=r.GetReferenceFlowchartName(),o=r.GetReferenceFlowchartStartNodeTag(),h=this._flowchartManager.GetFlowchartDataItemByName(a);let s=h.GetFlowchartNodeByTags(o);if(s){const r=this._MaybeByPassNodesInReferenceFlowchart(s,h);if(-1===r[0])return;e(this._currentFlowchartNodeId,t,r[1],r[0])}else e(this._currentFlowchartNodeId,t)}else e(this._currentFlowchartNodeId,t)}}GotoNextFlowchartNode(t){let e;if(C3.IsFiniteNumber(t)&&(e=this._GetFlowchartNodeOutputAt(t)),"string"==typeof t&&(e=this._GetFlowchartNodeOutputByName(t)),!e)return;let r=e.GetConnectedFlowchartNodeFlowchartId();C3.IsFiniteNumber(r)&&this._ProcessAllByPasses(r,((t,e,r,a)=>{this._previousFlowchartNodeIds.push(t),this._GotoFlowchartNode(e,r,a)}))}GotoNextFlowchartNodeDefault(){const t=this._GetFlowchartNodeOutputDefault();if(!t)return;const e=t.GetConnectedFlowchartNodeFlowchartId();C3.IsFiniteNumber(e)&&this._ProcessAllByPasses(e,((t,e,r,a)=>{this._previousFlowchartNodeIds.push(t),this._GotoFlowchartNode(e,r,a)}))}GotoAnyFlowchartNode(t){const e=this._flowchartDataItem.GetFlowchartNodeByTags(t);if(!e)return;const r=e.GetFlowchartId();C3.IsFiniteNumber(r)&&this._ProcessAllByPasses(r,((t,e,r,a)=>{this._previousFlowchartNodeIds.push(t),this._GotoFlowchartNode(e,r,a)}))}GotoPreviousFlowchartNode(){const t=this._previousFlowchartNodeIds.pop();C3.IsFiniteNumber(t)?this._GotoFlowchartNode(t):this._GetPreviousFlowchartState()&&(this._flowchartManager.SetCurrentFlowchartState(this._GetPreviousFlowchartState(),!0,!1,!1),this._GetPreviousFlowchartState()._GotoFlowchartNode(this._GetPreviousFlowchartStateStartNodeId()),this._GetRootFlowchartState()._SetCurrentReferenceFlowchart(this._GetPreviousFlowchartState()))}GotoParentFlowchartNode(t){if(!this.GetCurrentNode())return;const e=this.GetCurrentNodeParent(t);if(e){if(!e.GetEnable())return;const t=e.GetFlowchartId();if(!C3.IsFiniteNumber(t))return;this._previousFlowchartNodeIds.push(this._currentFlowchartNodeId),this._GotoFlowchartNode(e.GetFlowchartId())}}HasOutput(t){if(C3.IsFiniteNumber(t)){return!!this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId).GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems()[t]}if("string"==typeof t){const e=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId).GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems();for(let r=0;r<e.length;r++)if(e[r].GetName()===t)return!0;return!1}return!1}MarkForRelease(){this._markForRelease=!0}IsInTriggerState(){return this._triggerCount>0}PushIsTriggerState(){this._triggerCount++}PopIsTriggerState(){this._triggerCount--,0===this._triggerCount&&this._markForRelease&&this._flowchartManager.RemoveFlowchartState(this)}_GotoFlowchartNode(t,e,r){const a=this._currentFlowchartNodeId,o=this.GetPluginInstance().GetInstance();this.PushIsTriggerState(),this._flowchartManager.PushFlowchartState(this),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeAnyNodeChange,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeTaggedNodeChange,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeAnyNodeChangeInFlowchart,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeTaggedNodeChangeInFlowchart,o),this._currentFlowchartNodeId=t;let h=this.GetFlowchartElementById(this._currentFlowchartNodeId);if("dictionary"===h.GetType())this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChange,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChange,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChangeInFlowchart,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChangeInFlowchart,o);if(this._flowchartManager.PopFlowchartState(),this.PopIsTriggerState(),!this.WasReleased()&&(h=this.GetFlowchartElementById(this._currentFlowchartNodeId),"reference"===h.GetType())){const t=e?e.GetName():h.GetReferenceFlowchartName();if(this._HasReferenceFlowchartState(h)){this._previousFlowchartNodeIds.pop();const t=this._GetReferenceFlowchartState(h);this._flowchartManager.SetCurrentFlowchartState(t,!0,!0,!1),t._SetPreviousFlowchart(this,a);this._GetRootFlowchartState()._SetCurrentReferenceFlowchart(t)}else{const e="number"==typeof r?r:h.GetReferenceFlowchartStartNodeTag();if(t){this._previousFlowchartNodeIds.pop();let r=h.GetReferenceFlowchartTag();if(r){let t=this._flowchartManager.GetFlowchartState(r);for(;t;)r=C3.IncrementNumberAtEndOf(r),t=this._flowchartManager.GetFlowchartState(r)}else{r=`${t}-ref`;let e=this._flowchartManager.GetFlowchartState(r);for(;e;)r=C3.IncrementNumberAtEndOf(r),e=this._flowchartManager.GetFlowchartState(r)}const o=this._flowchartManager.AddFlowchartState(t,e,r,this._pluginInstance,!0);o._SetPreviousFlowchart(this,a),this._SetReferenceFlowchartState(h,o);const s=this._GetRootFlowchartState();o._SetRootFlowchartState(s),s._SetCurrentReferenceFlowchart(o)}}}}_GetFlowchartNodeOutputDefault(){const t=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);return t?t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDefault():null}_GetFlowchartNodeOutputAt(t){const e=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);if(!e)return null;const r=e.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems();if(!r)return null;const a=r[t];return a||null}_GetFlowchartNodeOutputByName(t){const e=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);if(!e)return null;const r=e.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItemByName(t);return r||null}_SetStartFlowchartNode(t){if("number"==typeof t){let e=this.GetFlowchartElementById(t);e||(e=this._flowchartDataItem.GetFlowchartStartNode()),this._startFlowchartNode=e}else if("number"==typeof this._startNodeTag){let t=this.GetFlowchartElementById(this._startNodeTag);t||(t=this._flowchartDataItem.GetFlowchartStartNode()),this._startFlowchartNode=t}else{let t=this._flowchartDataItem.GetFlowchartNodeByTags(this._startNodeTag);t||(t=this._flowchartDataItem.GetFlowchartStartNode()),this._startFlowchartNode=t}}_SaveToJson(){return this._markForRelease?null:{"flowchartName":this._flowchartName,"flowchartTag":this._tag,"startNodeTag":this._startNodeTag,"currentNodeId":this._currentFlowchartNodeId,"previousNodeIds":this._previousFlowchartNodeIds,"pluginUID":this._pluginInstance.GetInstance().GetUID(),"reference":{"previousFlowchartTag":this._GetPreviousFlowchartState()?this._GetPreviousFlowchartState().GetTag():"","previousStartNodeId":C3.IsFiniteNumber(this._GetPreviousFlowchartStateStartNodeId())?this._GetPreviousFlowchartStateStartNodeId():NaN,"referencesJson":this._GetFlowchartReferencesJson(),"currentReferenceFlowchartTag":this.GetCurrentReferenceFlowchart()?this.GetCurrentReferenceFlowchart().GetTag():"","rootFlowchartTag":this._GetRootFlowchartState()?this._GetRootFlowchartState().GetTag():""}}}_GetFlowchartReferencesJson(){if(!this._HasReferenceFlowchartStates())return null;const t=[];for(const[e,r]of this._GetReferenceFlowchartStates().entries())t.push({"flowchartElementId":e.GetFlowchartId(),"flowchartStateTag":r.GetTag()});return t.length?t:null}_LoadFromJson(t){if(t){if(this._flowchartName=t["flowchartName"],this._tag=t["flowchartTag"],this._startNodeTag=t["startNodeTag"],this._currentFlowchartNodeId=t["currentNodeId"],this._previousFlowchartNodeIds=t["previousNodeIds"],this._pluginUID=t["pluginUID"],t.hasOwnProperty("reference")){const e=t["reference"];this._previousFlowchartStateTag=e["previousFlowchartTag"],this._previousFlowchartStateStartNodeId=e["previousStartNodeId"],this._referenceFlowchartStatesJson=e["referencesJson"],this._currentReferenceFlowchartStateTag=e["currentReferenceFlowchartTag"],this._rootFlowchartStateTag=e["rootFlowchartTag"]}this._SetStartFlowchartNode()}}_GetPreviousFlowchartState(){return"string"==typeof this._previousFlowchartStateTag&&this._previousFlowchartStateTag&&(this._previousFlowchartState=this._flowchartManager.GetFlowchartState(this._previousFlowchartStateTag),this._previousFlowchartStateTag=""),this._previousFlowchartState}_GetPreviousFlowchartStateStartNodeId(){return this._previousFlowchartStateStartNodeId}_SetPreviousFlowchart(t,e){this._previousFlowchartState=t,this._previousFlowchartStateStartNodeId=e}GetCurrentReferenceFlowchart(){return"string"==typeof this._currentReferenceFlowchartStateTag&&this._currentReferenceFlowchartStateTag&&(this._currentReferenceFlowchartState=this._flowchartManager.GetFlowchartState(this._currentReferenceFlowchartStateTag),this._currentReferenceFlowchartStateTag=""),this._currentReferenceFlowchartState}_SetCurrentReferenceFlowchart(t){this._currentReferenceFlowchartState=t,this._currentReferenceFlowchartState===this&&(this._currentReferenceFlowchartState=null)}_GetRootFlowchartState(){return"string"==typeof this._rootFlowchartStateTag&&this._rootFlowchartStateTag&&(this._rootFlowchartState=this._flowchartManager.GetFlowchartState(this._rootFlowchartStateTag),this._rootFlowchartStateTag=""),this._rootFlowchartState?this._rootFlowchartState:this}_SetRootFlowchartState(t){this._rootFlowchartState=t}_HasReferenceFlowchartStates(){return this._RebuildReferenceFlowchartStates(),!!this._referenceFlowchartStates}_HasReferenceFlowchartState(t){return this._RebuildReferenceFlowchartStates(),this._referenceFlowchartStates&&this._referenceFlowchartStates.has(t)}_RebuildReferenceFlowchartStates(){if(this._referenceFlowchartStatesJson){this._referenceFlowchartStates&&this._referenceFlowchartStates.clear(),this._referenceFlowchartStates||(this._referenceFlowchartStates=new Map);for(const t of this._referenceFlowchartStatesJson){const e=this._flowchartManager.GetFlowchartState(t["flowchartStateTag"]),r=e.GetFlowchartElementById(t["flowchartElementId"]);this._referenceFlowchartStates.set(r,e)}this._referenceFlowchartStatesJson=null}}_GetReferenceFlowchartStates(){return this._RebuildReferenceFlowchartStates(),this._referenceFlowchartStates}_GetReferenceFlowchartState(t){return this._RebuildReferenceFlowchartStates(),this._referenceFlowchartStates.get(t)}_SetReferenceFlowchartState(t,e){this._referenceFlowchartStates||(this._referenceFlowchartStates=new Map),this._referenceFlowchartStates.set(t,e)}};
}

// flowcharts/state/flowchartStateManager.js
{
const C3=self.C3;C3.FlowchartStateManager=class{constructor(t){this._runtime=t,this._flowchartStates=new Map,this._currentFlowchartState=null,this._flowchartStateStack=[],this._on_after_load=()=>this._OnAfterLoad(),this._loadJson=null}Release(){C3.clearArray(this._flowchartStateStack),this._flowchartStateStack=null,this._flowchartStates.clear(),this._flowchartStates=null,this._currentFlowchartState=null,this._runtime=null,this._loadJson=null}GetRuntime(){return this._runtime}GetFlowchartDataItemByName(t){return this._runtime.GetFlowchartManager().GetFlowchartDataItemByName(t)}AddFlowchartState(t,e,a,r,h,s){const o=this._runtime.GetFlowchartManager().GetFlowchartDataItemByName(t);if(!o)return void console.warn(`[Flowcharts] no flowchart found with name '${t}'`);if(this._flowchartStates.has(a)){const t=this._flowchartStates.get(a);t&&this.RemoveFlowchartState(t)}const n=new C3.FlowchartState(t,a,e,o,this,r,s);return this._flowchartStates.set(a,n),h&&this.SetCurrentFlowchartState(n,!0),n}RemoveFlowchartState(t){if(t.MarkForRelease(),t.IsInTriggerState())return;const e=t.GetTag();this._flowchartStates.delete(e),t.Release(),this._currentFlowchartState===t&&(this._currentFlowchartState=null)}ResetFlowchartState(t){t.Reset()}GetFlowchartState(t){return this._flowchartStates.get(t)}PushFlowchartState(t){this._flowchartStateStack.push(t)}PopFlowchartState(){this._flowchartStateStack.pop()}SetCurrentFlowchartState(t,e=!1,a=!1,r=!0){if(r){const e=t.GetCurrentReferenceFlowchart();t=e||t}t!==this._currentFlowchartState&&(this._TriggerBeforeFlowchartChange(),this._TriggerAfterFlowchartChange(t,e,a))}GetCurrentFlowchartState(t){return"string"==typeof t?this.GetFlowchartState(t):this._flowchartStateStack.length?this._flowchartStateStack[this._flowchartStateStack.length-1]:this._currentFlowchartState}_TriggerBeforeFlowchartChange(){if(!this._currentFlowchartState)return;if(this._currentFlowchartState.WasReleased())return;const t=this._currentFlowchartState.GetPluginInstance().GetInstance();this._currentFlowchartState.PushIsTriggerState(),this.PushFlowchartState(this._currentFlowchartState),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeFlowchartChange,t),this.PopFlowchartState(),this._currentFlowchartState.PopIsTriggerState()}_TriggerAfterFlowchartChange(t,e=!1,a=!1){if(this._currentFlowchartState=t,!this._currentFlowchartState)return;if(this._currentFlowchartState.WasReleased())return;const r=this._currentFlowchartState.GetPluginInstance().GetInstance();this._currentFlowchartState.PushIsTriggerState(),this.PushFlowchartState(this._currentFlowchartState),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnFlowchartChange,r),!0!==a&&"number"!=typeof a||this._currentFlowchartState._SetStartFlowchartNode(a),e&&(this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChange,r),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChange,r),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChangeInFlowchart,r),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChangeInFlowchart,r)),this.PopFlowchartState(),this._currentFlowchartState.PopIsTriggerState()}_SaveToJson(){return{"flowchartJsonObjects":[...this._flowchartStates.values()].map((t=>t._SaveToJson())),"currentFlowchartTag":this._currentFlowchartState?this._currentFlowchartState.GetTag():null}}_LoadFromJson(t){if(!t)return;this._loadJson=t;const e=new Map;for(const t of this._loadJson["flowchartJsonObjects"]){const a=t["flowchartTag"];if(this._flowchartStates.has(a)){const r=this._flowchartStates.get(a);r._LoadFromJson(t),e.set(a,r)}else{const a=this.AddFlowchartState(t["flowchartName"],t["startNodeTag"],t["flowchartTag"],null,!1,t["pluginUID"]);a._LoadFromJson(t),e.set(t["flowchartTag"],a)}}for(const[t,a]of this._flowchartStates.entries())e.has(t)||a.Release();this._flowchartStates.clear(),this._flowchartStates=e,this._runtime.IsLoadingState()?this._runtime.Dispatcher().addEventListener("afterload",this._on_after_load):this._OnAfterLoad()}_OnAfterLoad(){this._runtime.Dispatcher().removeEventListener("afterload",this._on_after_load);const t=this._flowchartStates.get(this._loadJson["currentFlowchartTag"]);t&&this.SetCurrentFlowchartState(t,!0),this._loadJson=null}};
}

// flowcharts/data/flowchartDataManager.js
{
const C3=self.C3;C3.FlowchartDataManager=class{constructor(){this._flowchartDataItems=new Map}Release(){for(const t of this._flowchartDataItems.values())t.Release();this._flowchartDataItems.clear(),this._flowchartDataItems=null}Add(t){const a=new C3.FlowchartDataItem(t),s=a.GetName();this._flowchartDataItems.set(s,a)}Get(t){return this._flowchartDataItems.get(t)}HasFlowcharts(){return!!this._flowchartDataItems.size}static CreateDataItems(t,a,s,e){if(a)for(const o of a){const a=new s(o,e);t.push(a)}}};
}

// flowcharts/data/flowchartData.js
{
const C3=self.C3,NAME=0,NODES=1;C3.FlowchartDataItem=class{constructor(t){this._name=t[0],this._flowchartNodeData=new C3.FlowchartNodeData(t[1],this)}Release(){this._flowchartNodeData.Release(),this._flowchartNodeData=null}GetFlowchartNodeData(){return this._flowchartNodeData}GetFlowchartElementById(t){return this._flowchartNodeData.GetFlowchartElementById(t)}GetFlowchartNodeByTags(t){return this._flowchartNodeData.GetFlowchartNodeByTags(t)}GetFlowchartStartNode(){return this._flowchartNodeData.GetFlowchartStartNode()}GetName(){return this._name}};
}

// flowcharts/data/flowchartNodeData.js
{
const C3=self.C3,FLOWCHART_ID=0,TAG=1,PARENT_FLOWCHART_IDS=2,PARENT_OUTPUT_FLOWCHART_IDS=3,CHILDREN_FLOWCHART_IDS=4,OUTPUTS=5,IS_START=6,TYPE=7,DICTIONARY_ENABLE=8,REFERENCE_FLOWCHART=8,REFERENCE_FLOWCHART_START_NODE=9,REFERENCE_FLOWCHART_TAG=10,REFERENCE_FLOWCHART_ENABLE=11;class FlowchartNodeDataItem{constructor(t,e){this._flowchartNodeData=e,this._type=t[7],this._flowchartId=t[0],this._tag=t[1],this._tag?this._tags=this._tag.trim().split(" ").map((t=>t.trim())):this._tags=[],this._parentFlowchartIds=t[2],this._parentOutputFlowchartIds=null,this._childrenFlowchartIds=null,this._enable=!1,"dictionary"===this._type&&(this._parentOutputFlowchartIds=t[3],this._childrenFlowchartIds=t[4],this._enable=t[8]),this._isStart=t[6],this._referenceFlowchartName=null,this._referenceFlowchartStartNodeTag=null,this._referenceFlowchartTag=null,"reference"===this._type&&(this._referenceFlowchartName=t[8],this._referenceFlowchartStartNodeTag=t[9],this._referenceFlowchartTag=t[10],this._enable=t[11]),this._flowchartNodeOutputData=new C3.FlowchartNodeOutputData(t[5],this)}Release(){this._flowchartNodeData=null}GetFlowchartNodeData(){return this._flowchartNodeData}GetFlowchartNodeOutputData(){return this._flowchartNodeOutputData}GetFlowchartId(){return this._flowchartId}GetTag(){return this._tag}GetTags(){return this._tags}HasTags(t){if(!this._tags)return!1;if(!this._tags.length)return!1;const e=C3.FlowchartState._GetTagArray(t);return!(!e||!e.length)&&e.every(C3.FlowchartState._HasTag,this._tags)}GetIsStart(){return this._isStart}SetIsStart(t){this._isStart=!!t}CanBeStartNode(){if("dictionary"===this._type)return!0;if("reference"===this._type)return!1;throw new Error(`unexpected flowchart node type: ${this._type}`)}GetParentFlowchartIds(){return this._parentFlowchartIds}GetParentOutputFlowchartIds(){return this._parentOutputFlowchartIds}GetChildrenFlowchartIds(){return this._childrenFlowchartIds}GetType(){return this._type}GetEnable(){return this._enable}GetReferenceFlowchartName(){return this._referenceFlowchartName}GetReferenceFlowchartStartNodeTag(){return this._referenceFlowchartStartNodeTag}GetReferenceFlowchartTag(){return this._referenceFlowchartTag}}C3.FlowchartNodeData=class{constructor(t,e){this._flowchartDataItem=e,this._flowchartNodeItems=[],this._flowchartNodeItemsIdMap=new Map,this._flowchartNodeItemsTagMap=new Map,this._flowchartNodeStartItem=null,C3.FlowchartDataManager.CreateDataItems(this._flowchartNodeItems,t,FlowchartNodeDataItem,this);for(const t of this._flowchartNodeItems){const e=t.GetFlowchartId(),a=t.GetTag(),r=t.GetTags(),s=t.GetIsStart();if(this._flowchartNodeItemsIdMap.set(e,t),a)for(const e of r)this._flowchartNodeItemsTagMap.has(e)||this._flowchartNodeItemsTagMap.set(e,new Set),this._flowchartNodeItemsTagMap.get(e).add(t);s&&(this._flowchartNodeStartItem=t);const o=t.GetFlowchartNodeOutputData();for(const t of o.flowchartNodeOutputDataItems()){const e=t.GetFlowchartId();this._flowchartNodeItemsIdMap.set(e,t)}}this._flowchartNodeStartItem||this._SetStartNodeIfMissing()}Release(){this._flowchartDataItem=null;for(const t of this._flowchartNodeItems)t.Release();C3.clearArray(this._flowchartNodeItems),this._flowchartNodeItems=null}GetFlowchartDataItem(){return this._flowchartDataItem}GetFlowchartElementById(t){return this._flowchartNodeItemsIdMap.get(t)}GetFlowchartNodeByTags(t){if(!t||!t.length)return null;const e=[];for(const a of t.trim().split(" ")){let t=this._flowchartNodeItemsTagMap.get(a.trim())??new Set;if(0===t.size)return null;e.push(t)}return[...e.reduce(((t,e)=>e.size<t.size?e:t))].filter((t=>e.every((e=>e.has(t)))))[0]}GetFlowchartStartNode(){return this._flowchartNodeStartItem}*flowchartNodeDataItems(){for(const t of this._flowchartNodeItems)yield t}_SetStartNodeIfMissing(){let t=0;for(const e of this.flowchartNodeDataItems())e.GetIsStart()&&t++;if(0===t){for(const t of this.flowchartNodeDataItems())if(t.CanBeStartNode()&&!t.GetIsStart())return void t.SetIsStart(!0)}else{if(1===t)return;if(t>1){let t=!0;for(const e of this.flowchartNodeDataItems())e.CanBeStartNode()&&(e.GetIsStart()&&t?t=!1:e.GetIsStart()&&!t&&e.SetIsStart(!1))}}for(const t of this.flowchartNodeDataItems())if(t.CanBeStartNode()&&t.GetIsStart())return void(this._flowchartNodeStartItem=t)}};
}

// flowcharts/data/flowchartNodeOutputData.js
{
const C3=self.C3,FLOWCHART_ID=0,NAME=1,VALUE=2,CONNECTED_FLOWCHART_NODE_FLOWCHART_ID=3,ENABLE=4,DEFAULT=5;class FlowchartNodeDataOutputItem{constructor(t,e){this._flowchartNodeOutputData=e,this._flowchartId=t[0],this._name=t[1],this._value=t[2],this._connectedFlowchartNodeFlowchartId=t[3],this._enable=t[4],this._default=t[5]}Release(){this._flowchartNodeOutputData=null}GetFlowchartNodeOutputData(){return this._flowchartNodeOutputData}GetFlowchartId(){return this._flowchartId}GetName(){return this._name}GetValue(){return this._value}GetConnectedFlowchartNodeFlowchartId(){return this._connectedFlowchartNodeFlowchartId}GetEnable(){return this._enable}GetDefault(){return this._default}}C3.FlowchartNodeOutputData=class{constructor(t,e){this._flowchartDataNodeItem=e,this._flowchartNodeOutputItems=[],this._flowchartNodeOutputItemsNameMap=new Map,C3.FlowchartDataManager.CreateDataItems(this._flowchartNodeOutputItems,t,FlowchartNodeDataOutputItem,this),this._enabledFlowchartNodeOutputItems=this._flowchartNodeOutputItems.filter((t=>t.GetEnable()));for(const t of this._enabledFlowchartNodeOutputItems)this._flowchartNodeOutputItemsNameMap.set(t.GetName(),t)}Release(){this._flowchartDataNodeItem=null;for(const t of this._flowchartNodeOutputItems)t.Release();C3.clearArray(this._flowchartNodeOutputItems),this._flowchartNodeOutputItems=null,C3.clearArray(this._enabledFlowchartNodeOutputItems),this._enabledFlowchartNodeOutputItems=null}GetFlowchartNodeDataItem(){return this._flowchartDataNodeItem}GetFlowchartNodeOutputDataItemCount(){return this._enabledFlowchartNodeOutputItems.length}GetFlowchartNodeOutputDataItems(){return this._enabledFlowchartNodeOutputItems}GetFlowchartNodeOutputDataItemByName(t){return this._flowchartNodeOutputItemsNameMap.get(t)}GetFlowchartNodeOutputDefault(){for(const t of this._enabledFlowchartNodeOutputItems)if(t.GetDefault())return t}*flowchartNodeOutputDataItems(){for(const t of this._enabledFlowchartNodeOutputItems)yield t}};
}

// events/stacks/solStack.js
{
const C3=self.C3;C3.SolStack=class extends C3.DefendedBase{constructor(t){super(),this._objectClass=t,this._stack=[],this._stack.push(C3.New(C3.Sol,this)),this._index=0,this._current=this._stack[0]}Release(){for(const t of this._stack)t.Release();C3.clearArray(this._stack),this._current=null,this._objectClass=null}GetObjectClass(){return this._objectClass}GetCurrentSol(){return this._current}GetOneBelowCurrentSol(){return this._stack[this._index-1]}Clear(){this.GetCurrentSol().Clear()}PushClean(){const t=this._stack,s=++this._index;if(s===t.length){const s=C3.New(C3.Sol,this);t.push(s),this._current=s}else{const e=t[s];e.Reset(),this._current=e}}PushCopy(){const t=this._stack,s=++this._index;s===t.length&&t.push(C3.New(C3.Sol,this));const e=t[s];e.Copy(t[s-1]),this._current=e}Pop(){this._current=this._stack[--this._index]}RemoveInstances(t){const s=this._stack;for(let e=0,n=s.length;e<n;++e)s[e].RemoveInstances(t)}};
}

// events/stacks/sol.js
{
const C3=self.C3;C3.Sol=class extends C3.DefendedBase{constructor(s){super(),this._stack=s,this._objectClass=this._stack.GetObjectClass(),this._eventStack=this._objectClass.GetRuntime().GetEventStack(),this._selectAll=!0,this._instances=[],this._elseInstances=[]}Release(){this.ClearArrays(),this._stack=null,this._objectClass=null,this._eventStack=null}ClearArrays(){C3.clearArray(this._instances),C3.clearArray(this._elseInstances)}GetObjectClass(){return this._objectClass}IsSelectAll(){return this._selectAll}HasAnyInstances(){return this._selectAll?!!this._objectClass.GetInstanceCount():!!this._instances.length}GetInstances(){return this._selectAll?this._objectClass.GetInstances():this._instances}HasAnyElseInstances(){return!!this._elseInstances.length}GetElseInstances(){return this._elseInstances}GetExpressionInstances(){const s=this.GetInstances();return s.length?s:this._elseInstances}Reset(){this._selectAll=!0,C3.clearArray(this._elseInstances)}Clear(){this._selectAll=!0}Copy(s){s.IsSelectAll()?this.Reset():(this._selectAll=!1,C3.shallowAssignArray(this._instances,s._instances),C3.clearArray(this._elseInstances))}_PushInstance(s){this._instances.push(s)}_PushElseInstance(s){this._elseInstances.push(s)}_SetSelectAll(s){this._selectAll=!!s}_GetOwnInstances(){return this._instances}_GetOwnElseInstances(){return this._elseInstances}SetSinglePicked(s){this._selectAll=!1,C3.clearArray(this._instances),this._instances.push(s)}SetArrayPicked(s){this._selectAll=!1,C3.shallowAssignArray(this._instances,s)}SetSetPicked(s){this._selectAll=!1,C3.clearArray(this._instances);for(const e of s)this._instances.push(e)}AddElseInstances(s,e){for(const t of e)s.has(t)||this._elseInstances.push(t)}TransferElseInstancesToOwn(s){for(const e of s)this._instances.push(e);C3.arrayRemoveAllInSet(this._elseInstances,s)}ClearElseInstances(){C3.clearArray(this._elseInstances)}PickOne(s){if(s)if(this._eventStack.GetCurrentStackFrame().GetCurrentEvent().IsOrBlock()){this.IsSelectAll()&&(C3.clearArray(this._instances),C3.shallowAssignArray(this._elseInstances,s.GetObjectClass().GetInstances()),this._selectAll=!1);const e=this._elseInstances.indexOf(s);-1!==e&&(this._instances.push(this._elseInstances[e]),this._elseInstances.splice(e,1))}else this.SetSinglePicked(s)}RemoveInstances(s){C3.arrayRemoveAllInSet(this._instances,s),C3.arrayRemoveAllInSet(this._elseInstances,s)}};
}

// events/stacks/eventStack.js
{
const C3=self.C3;C3.EventStack=class extends C3.DefendedBase{constructor(t){super(),this._eventSheetManager=t,this._runtime=this._eventSheetManager.GetRuntime(),this._stack=[],this._stack.push(C3.New(C3.EventStackFrame,this,null)),this._index=0,this._expFuncStack=[]}Release(){for(const t of this._stack)t.Release();C3.clearArray(this._stack),C3.clearArray(this._expFuncStack),this._eventSheetManager=null,this._runtime=null}GetEventSheetManager(){return this._eventSheetManager}GetRuntime(){return this._runtime}GetCurrentStackFrame(){return this._stack[this._index]}GetAllStackFrames(){return this._stack}GetCurrentStackFrameIndex(){return this._index}Push(t){const e=this._stack,n=++this._index;if(n===e.length){const n=C3.New(C3.EventStackFrame,this,t);return e.push(n),n}{const s=e[n];return s.Reset(t),s}}Pop(){--this._index}PushExpFunc(t){this._expFuncStack.push(t)}PopExpFunc(){this._expFuncStack.pop()}GetCurrentExpFuncStackFrame(){const t=this._expFuncStack;return 0===t.length?null:t.at(-1)}};
}

// events/stacks/eventStackFrame.js
{
const C3=self.C3;C3.EventStackFrame=class extends C3.DefendedBase{constructor(t,e){super(),this._stack=t,this._runtime=this._stack.GetRuntime(),this._currentEvent=e,this._cndIndex=0,this._actIndex=0,this._lastEventTrue=!1,this._elseBranchRan=!1,this._expressionObjectClass=null,this._functionReturnType=0,this._functionReturnValue=0,this._dynamicSolModifiers=null}Release(){this.Reset(null),this._stack=null,this._runtime=null}Reset(t){this._currentEvent=t,this._cndIndex=0,this._actIndex=0,this._lastEventTrue=!1,this._elseBranchRan=!1,this._dynamicSolModifiers=null}_Restore(t,e){this._currentEvent=t,this._cndIndex=0,this._actIndex=e}ResetQuick(){this._cndIndex=0,this._actIndex=0}GetCurrentEvent(){return this._currentEvent}SetCurrentEvent(t){this._currentEvent=t}GetConditionIndex(){return this._cndIndex}SetConditionIndex(t){this._cndIndex=t}GetActionIndex(){return this._actIndex}SetActionIndex(t){this._actIndex=t}SetLastEventTrue(t){this._lastEventTrue=!!t}GetLastEventTrue(){return this._lastEventTrue}SetElseBranchRan(t){this._elseBranchRan=!!t}GetElseBranchRan(){return this._elseBranchRan}SetExpressionObjectClass(t){this._expressionObjectClass=t}GetExpressionObjectClass(){return this._expressionObjectClass}InitCallFunctionExpression(t,e){this._functionReturnType=t,this._functionReturnValue=e}GetFunctionReturnType(){return this._functionReturnType}SetFunctionReturnValue(t){this._functionReturnValue=t}GetFunctionReturnValue(){return this._functionReturnValue}IsSolModifierAfterCnds(){const t=this._currentEvent;return!!t.IsSolWriterAfterCnds()||this._cndIndex<t.GetConditionCount()-1&&!!t.GetSolModifiers().length}SetDynamicSolModifiers(t){this._dynamicSolModifiers=t}GetDynamicSolModifiers(){return this._dynamicSolModifiers}};
}

// events/stacks/localVarStack.js
{
const C3=self.C3;C3.LocalVarStack=class extends C3.DefendedBase{constructor(t){super(),this._eventSheetManager=t,this._runtime=this._eventSheetManager.GetRuntime(),this._stack=[],this._index=-1,this._current=null,this._initialValues=[]}Release(){C3.clearArray(this._stack),this._eventSheetManager=null,this._runtime=null}_SetInitialValues(t){this._initialValues=t;const e=this._initialValues.slice(0);this._stack.push(e),this._index=0,this._current=e}GetEventSheetManager(){return this._eventSheetManager}GetRuntime(){return this._runtime}GetCurrent(){return this._current}Push(){const t=++this._index,e=this._stack;t===e.length?e.push(this._initialValues.slice(0)):C3.shallowAssignArray(e[t],this._initialValues),this._current=e[t]}Pop(){this._current=this._stack[--this._index]}};
}

// events/stacks/loopStack.js
{
const C3=self.C3;C3.LoopStack=class extends C3.DefendedBase{constructor(t){super(),this._eventSheetManager=t,this._runtime=this._eventSheetManager.GetRuntime(),this._stack=[],this._index=-1}Release(){C3.clearArray(this._stack),this._eventSheetManager=null,this._runtime=null}GetEventSheetManager(){return this._eventSheetManager}GetRuntime(){return this._runtime}IsInLoop(){return this._index>=0}GetCurrent(){return this._stack[this._index]}Push(){if(++this._index,this._index===this._stack.length){const t=C3.New(C3.Loop,this);return this._stack.push(t),t}{const t=this._stack[this._index];return t.Reset(),t}}Pop(){--this._index}FindByName(t){const e=this._stack;for(let s=this._index;s>=0;--s){const n=e[s];if(n.GetName()===t)return n}return null}_GetStack(){return this._stack.slice(0,this._index+1)}};
}

// events/stacks/loop.js
{
const C3=self.C3;C3.Loop=class extends C3.DefendedBase{constructor(e){super(),this._loopStack=e,this._name="",this._index=0,this._isStopped=!1,this._end=NaN}Reset(){this._name="",this._index=0,this._isStopped=!1,this._end=NaN}SetName(e){this._name=e}GetName(){return this._name}SetIndex(e){this._index=e}GetIndex(){return this._index}Stop(){this._isStopped=!0}IsStopped(){return this._isStopped}SetEnd(e){this._end=e}GetEnd(){return this._end}};
}

// events/stacks/arrayStack.js
{
const C3=self.C3;C3.ArrayStack=class extends C3.DefendedBase{constructor(){super(),this._stack=[],this._index=-1}Release(){C3.clearArray(this._stack)}GetCurrent(){return this._stack[this._index]}Push(){if(++this._index,this._index===this._stack.length){const s=[];return this._stack.push(s),s}return this._stack[this._index]}Pop(){--this._index}};
}

// events/eventSheetManager.js
{
const C3=self.C3,assert=self.assert;function SortSolArray(t,e){return t.GetIndex()-e.GetIndex()}function IsSolArrayIdentical(t,e){for(let s=0,n=t.length;s<n;++s)if(t[s]!==e[s])return!1;return!0}C3.EventSheetManager=class extends C3.DefendedBase{constructor(t){super(),this._runtime=t,this._allSheets=[],this._sheetsByName=new Map,this._allGroups=[],this._groupsByName=new Map,this._blocksBySid=new Map,this._cndsBySid=new Map,this._actsBySid=new Map,this._allUniqueSolModifiers=new Map,this._eventVarsBySid=new Map,this._nextLocalVarIndex=0,this._allGlobalVars=[],this._allLocalVars=[],this._localVarInitialValues=[],this._functionBlocksByName=new Map,this._customActionBlocksMap=new Map,this._eventStack=C3.New(C3.EventStack,this),this._localVarStack=C3.New(C3.LocalVarStack,this),this._loopStack=C3.New(C3.LoopStack,this),this._triggersToPostInit=[],this._queuedTriggers=[],this._queuedDebugTriggers=[],this._runningEventsDepth=0,this._executingTriggerDepth=0,this._blockFlushingDepth=0,this._scheduledWaits=[],this._asyncActionPromises=[],this._signalTags=[],this._signalPromises=new Map,this._instSignals=new Map,self["c3_callFunction"]=(t,e)=>this._InvokeFunctionFromJS(t,e)}Release(){this.ClearAllScheduledWaits(),this._eventStack.Release(),this._eventStack=null,this._localVarStack.Release(),this._localVarStack=null,C3.clearArray(this._queuedTriggers),C3.clearArray(this._queuedDebugTriggers),this._runtime=null,C3.clearArray(this._allSheets),this._sheetsByName.clear()}Create(t){const e=C3.New(C3.EventSheet,this,t);this._allSheets.push(e),this._sheetsByName.set(e.GetName().toLowerCase(),e)}_AddTriggerToPostInit(t){this._triggersToPostInit.push(t)}_PostInit(){for(const t of this._customActionBlocksMap.values())t._CheckOverrideState();for(const t of this._functionBlocksByName.values())t._PostInit();for(const t of this._customActionBlocksMap.values())t._PostInit();for(const t of this._allSheets)t._PostInit();for(const t of this._allSheets)t._UpdateDeepIncludes();for(const t of this._triggersToPostInit)t._PostInit(!1);C3.clearArray(this._triggersToPostInit),this._localVarStack._SetInitialValues(this._localVarInitialValues)}GetRuntime(){return this._runtime}GetEventSheetByName(t){return this._sheetsByName.get(t.toLowerCase())||null}_RegisterGroup(t){this._allGroups.push(t),this._groupsByName.set(t.GetGroupName(),t)}_RegisterEventBlock(t){this._blocksBySid.set(t.GetSID(),t)}_RegisterCondition(t){this._cndsBySid.set(t.GetSID(),t)}_RegisterAction(t){this._actsBySid.set(t.GetSID(),t)}_RegisterFunctionBlock(t){switch(t.GetFunctionType()){case 0:this._functionBlocksByName.set(t.GetFunctionName().toLowerCase(),t);break;case 1:this._customActionBlocksMap.set(t.GetFunctionName().toLowerCase(),t)}}_RegisterEventVariable(t){this._eventVarsBySid.set(t.GetSID(),t),t.IsGlobal()?this._allGlobalVars.push(t):this._allLocalVars.push(t)}_DeduplicateSolModifierList(t){t.length>=2&&t.sort(SortSolArray);let e=this._allUniqueSolModifiers.get(t.length);e||(e=[],this._allUniqueSolModifiers.set(t.length,e));for(let s=0,n=e.length;s<n;++s){const n=e[s];if(IsSolArrayIdentical(t,n))return n}return e.push(t),t}_GetNextLocalVarIndex(t){return this._localVarInitialValues.push(t.GetInitialValue()),this._nextLocalVarIndex++}GetEventStack(){return this._eventStack}GetCurrentEventStackFrame(){return this.GetEventStack().GetCurrentStackFrame()}GetCurrentEvent(){return this.GetCurrentEventStackFrame().GetCurrentEvent()}GetCurrentCondition(){const t=this.GetCurrentEventStackFrame();return t.GetCurrentEvent().GetConditionAt(t.GetConditionIndex())}GetCurrentAction(){const t=this.GetCurrentEventStackFrame();return t.GetCurrentEvent().GetActionAt(t.GetActionIndex())}GetLocalVarStack(){return this._localVarStack}GetLoopStack(){return this._loopStack}GetAllLocalVariablesInScope(t){const e=[];for(t=t.GetScopeParent();t;)C3.appendArray(e,t._GetAllLocalVariablesInScope()),t=t.GetScopeParent();return e}_GetLocalVariablesScriptInterface(t){const e={};for(const s of this.GetAllLocalVariablesInScope(t))e[s.GetJsPropName()]=s._GetScriptInterfaceDescriptor();return Object.create(Object.prototype,e)}GetEventVariableBySID(t){return this._eventVarsBySid.get(t)||null}GetEventBlockBySID(t){return this._blocksBySid.get(t)||null}GetConditionBySID(t){return this._cndsBySid.get(t)||null}GetActionBySID(t){return this._actsBySid.get(t)||null}GetFunctionBlockByName(t){return this._functionBlocksByName.get(t.toLowerCase())||null}GetCustomActionBlockByName(t,e){let s=this._customActionBlocksMap.get((t.GetName()+"."+e).toLowerCase());if(s)return s;if(!t.IsFamily())for(const n of t.GetFamilies())if(s=this._customActionBlocksMap.get((n.GetName()+"."+e).toLowerCase()),s)return s;return null}GetAllGlobalVariables(){return this._allGlobalVars}GetAllLocalVariables(){return this._allLocalVars}ResetAllGlobalsToInitialValue(t){for(const t of this._allGlobalVars)t.ResetToInitialValue();if(t)for(const t of this._allLocalVars)t.IsStatic()&&t.ResetToInitialValue()}GetEventGroupByName(t){return this._groupsByName.get(t.toLowerCase())||null}GetEventGroupBySID(t){const e=this._blocksBySid.get(t);return e&&e.IsGroup()?e:null}GetAllGroups(){return this._allGroups}ResetAllGroupsInitialActivation(){for(const t of this._allGroups)t.ResetInitialActivation()}_ResetAllHasRunFlags(){for(const t of this._allSheets)t._ResetHasRunFlag()}RunEvents(t){this._ResetAllHasRunFlags(),this._runningEventsDepth++;for(const e of t.runningLayouts()){const t=e.GetEventSheet();t&&(this._runtime.PushCurrentLayout(e),t.Run(),this._runtime.PopCurrentLayout())}this._runningEventsDepth--}async DebugRunEvents(t){this._ResetAllHasRunFlags(),this._runningEventsDepth++;for(const e of this._DebugRunEventsGen(t))await this._runtime.DebugBreak(e);this._runningEventsDepth--}*_DebugRunEventsGen(t){for(const e of t.runningLayouts()){const t=e.GetEventSheet();t&&(this._runtime.PushCurrentLayout(e),yield*t.DebugRun(),this._runtime.PopCurrentLayout())}}_Trigger(t,e,s,n){let i=!1;if(!t.GetMainRunningLayout())return this.QueueTrigger(e,s,n);this._executingTriggerDepth++;for(const r of t.runningLayouts()){const t=r.GetEventSheet();if(!t)continue;this._runtime.PushCurrentLayout(r);for(const r of t.deepIncludes()){const t=r._Trigger(e,s,n);i=i||t}const o=t._Trigger(e,s,n);i=i||o,this._runtime.PopCurrentLayout()}return this._executingTriggerDepth--,i}*_DebugTrigger(t,e,s,n){let i=!1;if(!t.GetMainRunningLayout())return this.QueueTrigger(e,s,n);this._executingTriggerDepth++;for(const r of t.runningLayouts()){const t=r.GetEventSheet();if(!t)continue;this._runtime.PushCurrentLayout(r);for(const r of t.deepIncludes()){const t=yield*r._DebugTrigger(e,s,n);i=i||t}const o=yield*t._DebugTrigger(e,s,n);i=i||o,this._runtime.PopCurrentLayout()}return this._executingTriggerDepth--,i}QueueTrigger(t,e,s){return this._queuedTriggers.push([t,e,s]),!1}QueueDebugTrigger(t,e,s){let n=null;const i=new Promise((t=>n=t));return this._queuedDebugTriggers.push([t,e,s,n]),i}*_RunQueuedDebugTriggersGen(){if(this._runtime.HitBreakpoint())throw new Error("should not be in breakpoint");const t=this._runtime.GetLayoutManager();for(;this._queuedDebugTriggers.length;){const[e,s,n,i]=this._queuedDebugTriggers.shift();i(yield*this._DebugTrigger(t,e,s,n))}}async RunQueuedDebugTriggersAsync(){for(const t of this._RunQueuedDebugTriggersGen())await this._runtime.DebugBreak(t)}_FastTrigger(t,e,s,n){let i=!1;const r=t.GetMainRunningLayout(),o=r.GetEventSheet();if(!o)return;this._executingTriggerDepth++,this._runtime.PushCurrentLayout(r);const a=o.deepIncludes();for(let t=0,r=a.length;t<r;++t){const r=a[t]._FastTrigger(e,s,n);i=i||r}const l=o._FastTrigger(e,s,n);return i=i||l,this._runtime.PopCurrentLayout(),this._executingTriggerDepth--,i}*_DebugFastTrigger(t,e,s,n){let i=!1;const r=t.GetMainRunningLayout(),o=r.GetEventSheet();if(!o)return;this._executingTriggerDepth++,this._runtime.PushCurrentLayout(r);const a=o.deepIncludes();for(let t=0,r=a.length;t<r;++t){const r=yield*a[t]._DebugFastTrigger(e,s,n);i=i||r}const l=yield*o._DebugFastTrigger(e,s,n);return i=i||l,this._runtime.PopCurrentLayout(),this._executingTriggerDepth--,i}GetTriggerDepth(){return this._executingTriggerDepth}IsInTrigger(){return this.GetTriggerDepth()>0}_IncTriggerDepth(){return++this._executingTriggerDepth}_DecTriggerDepth(){--this._executingTriggerDepth}IsRunningEvents(){return this._runningEventsDepth>0}IsInEventEngine(){return this.IsRunningEvents()||this.IsInTrigger()}_RunQueuedTriggers(t){for(const[e,s,n]of this._queuedTriggers)this._Trigger(t,e,s,n);C3.clearArray(this._queuedTriggers)}BlockFlushingInstances(t){t?this._blockFlushingDepth++:this._blockFlushingDepth--}IsFlushingBlocked(){return this._blockFlushingDepth>0}ClearSol(t){for(let e=0,s=t.length;e<s;++e)t[e].GetSolStack().Clear()}PushCleanSol(t){for(let e=0,s=t.length;e<s;++e)t[e].GetSolStack().PushClean()}PushCopySol(t){for(let e=0,s=t.length;e<s;++e)t[e].GetSolStack().PushCopy()}PopSol(t){for(let e=0,s=t.length;e<s;++e)t[e].GetSolStack().Pop()}GetDynamicSolModifiersSet(t){const e=new Set,s=this._eventStack.GetAllStackFrames(),n=this._eventStack.GetCurrentStackFrameIndex();for(let i=0;i<=n;++i){const n=s[i].GetDynamicSolModifiers();if(n)for(const s of n)t&&t.has(s)||e.add(s)}return e}PushCleanSolDynamic(t){const e=new Set([...t]),s=this.GetDynamicSolModifiersSet(e);if(s.size>0){for(const t of s)t.GetSolStack().PushClean();return[...s]}return null}AddScheduledWait(){const t=C3.New(C3.ScheduledWait,this);return this._scheduledWaits.push(t),t}scheduledWaits(){return this._scheduledWaits}RunScheduledWaits(){if(!this._scheduledWaits.length)return;const t=this.GetCurrentEventStackFrame();let e=!1;this._runningEventsDepth++;for(let s=0,n=this._scheduledWaits.length;s<n;++s){const n=this._scheduledWaits[s];n._ShouldRun()&&n._Run(t),n.ShouldRelease()&&(e=!0)}e&&(this._FilterScheduledWaitsToRelease(),t.Reset(null)),this._runningEventsDepth--}async DebugRunScheduledWaits(){if(!this._scheduledWaits.length)return;const t=this.GetCurrentEventStackFrame();let e=!1;this._runningEventsDepth++;for(let s=0,n=this._scheduledWaits.length;s<n;++s){const n=this._scheduledWaits[s];n._ShouldRun()&&await n._DebugRun(t),n.ShouldRelease()&&(e=!0)}e&&(this._FilterScheduledWaitsToRelease(),t.Reset(null)),this._runningEventsDepth--}_FilterScheduledWaitsToRelease(){const t=C3.arrayFilterOut(this._scheduledWaits,(t=>t.ShouldRelease()));for(const e of t)e.Release()}ClearAllScheduledWaits(){for(const t of this._scheduledWaits)t.Release();C3.clearArray(this._scheduledWaits)}_OnInstancesReleased(t){for(const e of this._scheduledWaits)e.RemoveInstances(t);for(const e of t){const t=this._instSignals.get(e);if(this._instSignals.delete(e),t)for(const{resolve:e}of t.signalPromises.values())e(!0)}}AddAsyncActionPromise(t){this._asyncActionPromises.push({promise:t,triggerDepth:this.GetTriggerDepth()})}ClearAsyncActionPromises(){C3.clearArray(this._asyncActionPromises)}GetPromiseForAllAsyncActions(){const t=this.GetTriggerDepth(),e=Promise.all(this._asyncActionPromises.filter((e=>e.triggerDepth===t)).map((t=>t.promise)));return this._asyncActionPromises=this._asyncActionPromises.filter((e=>e.triggerDepth<t)),e}Signal(t){const e=t.toLowerCase();this._signalTags.push(e),this._runtime.Trigger(C3.Plugins.System.Cnds.OnSignal,null),this._signalTags.pop();for(const t of this._runtime.GetEventSheetManager().scheduledWaits())t.IsSignal()&&t.GetSignalTag()===e&&t.SetSignalled();const s=this._signalPromises.get(e);s&&(s.resolve(),this._signalPromises.delete(e))}WaitForSignal(t){const e=t.toLowerCase(),s=this._signalPromises.get(e);if(s)return s.promise;{let t=null;const s=new Promise((e=>t=e));return this._signalPromises.set(e,{promise:s,resolve:t}),s}}GetCurrentSignalTag(){if(0===this._signalTags.length)throw new Error("not in a signal");return this._signalTags.at(-1)}_GetInstanceSignalState(t){let e=this._instSignals.get(t);return e||(e={signalTags:[],signalPromises:new Map},this._instSignals.set(t,e)),e}InstanceSignal(t,e){const s=this._GetInstanceSignalState(t),n=e.toLowerCase();s.signalTags.push(n),this._runtime.Trigger(t.GetPlugin().GetConstructor().Cnds.OnInstanceSignal,t),s.signalTags.pop();for(const e of this._runtime.GetEventSheetManager().scheduledWaits())e.IsInstanceSignals()&&e.GetSignalTag()===n&&e.SetInstanceSignalled(t);const i=s.signalPromises.get(n);i&&(i.resolve(!1),s.signalPromises.delete(n)),0===s.signalTags.length&&0===s.signalPromises.size&&this._instSignals.delete(t)}WaitForInstanceSignal(t,e){const s=this._GetInstanceSignalState(t),n=e.toLowerCase(),i=s.signalPromises.get(n);if(i)return i.promise;{let t=null;const e=new Promise((e=>t=e));return s.signalPromises.set(n,{promise:e,resolve:t}),e}}GetCurrentInstanceSignalTag(t){const e=this._GetInstanceSignalState(t);if(!e||0===e.signalTags.length)throw new Error("not in a signal");return e.signalTags.at(-1)}_SaveToJson(){return{"groups":this._SaveGroupsToJson(),"cnds":this._SaveCndsToJson(),"acts":this._SaveActsToJson(),"vars":this._SaveVarsToJson(),"waits":this._SaveScheduledWaitsToJson()}}_LoadFromJson(t){this._LoadGroupsFromJson(t["groups"]),this._LoadCndsFromJson(t["cnds"]),this._LoadActsFromJson(t["acts"]),this._LoadVarsFromJson(t["vars"]),this._LoadScheduledWaitsFromJson(t["waits"])}_SaveGroupsToJson(){const t={};for(const e of this.GetAllGroups())t[e.GetSID().toString()]=e.IsGroupActive();return t}_LoadGroupsFromJson(t){for(const[e,s]of Object.entries(t)){const t=parseInt(e,10),n=this.GetEventGroupBySID(t);n&&n.SetGroupActive(s)}}_SaveCndsToJson(){const t={};for(const[e,s]of this._cndsBySid){const n=s._SaveToJson();n&&(t[e.toString()]=n)}return t}_LoadCndsFromJson(t){const e=new Map;for(const[s,n]of Object.entries(t))e.set(parseInt(s,10),n);for(const[t,s]of this._cndsBySid)s._LoadFromJson(e.get(t)||null)}_SaveActsToJson(){const t={};for(const[e,s]of this._actsBySid){const n=s._SaveToJson();n&&(t[e.toString()]=n)}return t}_LoadActsFromJson(t){const e=new Map;for(const[s,n]of Object.entries(t))e.set(parseInt(s,10),n);for(const[t,s]of this._actsBySid)s._LoadFromJson(e.get(t)||null)}_SaveVarsToJson(){const t={};for(const[e,s]of this._eventVarsBySid)s.IsConstant()||!s.IsGlobal()&&!s.IsStatic()||(t[e.toString()]=s.GetValue());return t}_LoadVarsFromJson(t){for(const[e,s]of Object.entries(t)){const t=parseInt(e,10),n=this.GetEventVariableBySID(t);n&&n.SetValue(s)}}_SaveScheduledWaitsToJson(){return this._scheduledWaits.filter((t=>!t.IsPromise())).map((t=>t._SaveToJson()))}_LoadScheduledWaitsFromJson(t){this.ClearAllScheduledWaits();for(const e of t){const t=C3.ScheduledWait._CreateFromJson(this,e);t&&this._scheduledWaits.push(t)}}_GetPerfRecords(){return[...this._runtime.GetLayoutManager().runningLayouts()].map((t=>t.GetEventSheet())).filter((t=>t)).map((t=>t._GetPerfRecord()))}FindFirstFunctionBlockParent(t){for(;t;){const e=t.GetScopeParent();if(e instanceof C3.FunctionBlock)return e;t=e}return null}_InvokeFunctionFromJS(t,e){Array.isArray(e)||(e=[]);const s=this.GetFunctionBlockByName(t.toLowerCase());if(!s)return null;if(!s.IsEnabled())return s.GetDefaultReturnValue();const n=s.GetFunctionParameters();if(e.length<n.length){e=e.slice(0);do{e.push(n[e.length].GetInitialValue())}while(e.length<n.length)}const i=s.GetEventBlock();return i.RunAsExpressionFunctionCall(i.GetSolModifiersIncludingParents(),!1,s.GetReturnType(),s.GetDefaultReturnValue(),...e)}};
}

// events/eventSheet.js
{
const C3=self.C3;C3.EventSheet=class extends C3.DefendedBase{constructor(e,t){super(),this._eventSheetManager=e,this._runtime=e.GetRuntime(),this._name=t[0],this._events=[],this._triggers=new Map,this._fastTriggers=new Map,this._eventsByDisplayNumber=new Map,this._hasRun=!1,this._shallowIncludes=[],this._deepIncludes=[],this._alreadyIncludedSheets=new Set;for(const e of t[1])this._CreateEvent(e,null,this._events);this._perfRecord=this._runtime.IsDebug()?{type:"sheet",name:this._name,totalTimeCounter:0,children:[]}:null}Release(){this._eventSheetManager=null,this._runtime=null}_CreateEvent(e,t,s){switch(e[0]){case 0:case 3:this._CreateEventBlock(e,t,s);break;case 1:this._CreateEventVariable(e,t,s);break;case 2:this._CreateInclude(e,t,s);break;case 4:this._CreateFunctionBlock(e,t);break;case 5:this._CreateScriptBlock(e,t,s);break;case 6:this._CreateCustomACEBlock(e,t);break;default:throw new Error("invalid event type")}}_CreateEventBlock(e,t,s){const n=C3.EventBlock.Create(this,t,e);if(n.IsOrBlock()){s.push(n);const e=n.GetConditions();for(let t=0,s=e.length;t<s;++t)e[t].IsTrigger()&&this._InitTrigger(n,t)}else n.IsTrigger()?this._InitTrigger(n,0):s.push(n)}_CreateFunctionBlock(e,t){const s=C3.FunctionBlock.CreateFunctionBlock(this,t,e);this._eventSheetManager._RegisterFunctionBlock(s)}_CreateCustomACEBlock(e,t){const s=C3.FunctionBlock.CreateCustomACEBlock(this,t,e);this._eventSheetManager._RegisterFunctionBlock(s)}_CreateEventVariable(e,t,s){const n=C3.EventVariable.Create(this,t,e);s.push(n)}_CreateInclude(e,t,s){const n=C3.EventInclude.Create(this,t,e);s.push(n)}_CreateScriptBlock(e,t,s){const n=C3.EventScript.Create(this,t,e);s.push(n)}_InitTrigger(e,t){e.IsOrBlock()||this._eventSheetManager._AddTriggerToPostInit(e);const s=e.GetConditionAt(t),n=s._GetFunc(),r=s.GetObjectClass();if(s.IsFastTrigger()){let i=this._fastTriggers.get(r);i||(i=new Map,this._fastTriggers.set(r,i));const l=s.GetFastTriggerValue().toLowerCase();let o=i.get(n);o||(o=new Map,i.set(n,o));let a=o.get(l);a||(a=[],o.set(l,a)),a.push([e,t])}else{let i=this._triggers.get(r);i||(i={methodMap:new Map,behaviors:new Map},this._triggers.set(r,i));const l=s.GetBehaviorType();let o;l?(o=i.behaviors.get(l),o||(o=new Map,i.behaviors.set(l,o))):o=i.methodMap;let a=o.get(n);a||(a=[],o.set(n,a)),a.push([e,t])}}_PostInit(){const e=this._events;for(let t=0,s=e.length;t<s;++t){const n=t<s-1&&e[t+1]instanceof C3.EventBlock&&e[t+1].IsElseBlock();e[t]._PostInit(n)}}_AddShallowInclude(e){this._shallowIncludes.push(e)}_UpdateDeepIncludes(){C3.clearArray(this._deepIncludes),this._AddDeepIncludes(this),this._alreadyIncludedSheets.clear()}_AddDeepIncludes(e){const t=e._deepIncludes,s=e._alreadyIncludedSheets;for(const n of this._shallowIncludes){const r=n.GetIncludeSheet();n.IsActive()&&e!==r&&!s.has(r)&&(s.add(r),r._AddDeepIncludes(e),t.push(r))}}deepIncludes(){return this._deepIncludes}GetEventSheetManager(){return this._eventSheetManager}GetRuntime(){return this._runtime}GetName(){return this._name}_RegisterEventByDisplayNumber(e,t){this._eventsByDisplayNumber.set(t,e)}_GetEventByDisplayNumber(e){return this._eventsByDisplayNumber.get(e)||null}_ResetHasRunFlag(){this._hasRun=!1}Run(){if(this._hasRun)return;const e=this._runtime,t=e.IsCPUProfiling(),s=t?performance.now():0;this._hasRun=!0;const n=this.GetEventSheetManager(),r=n.GetCurrentEventStackFrame();for(const t of this._events)t.Run(r),n.ClearSol(t.GetSolModifiers()),n.ClearAsyncActionPromises(),e.FlushPendingInstances();r.Reset(null),t&&(this._perfRecord.totalTimeCounter+=performance.now()-s)}*DebugRun(){if(this._hasRun)return;this._hasRun=!0;const e=this._runtime,t=this.GetEventSheetManager(),s=t.GetCurrentEventStackFrame();for(const n of this._events)yield*n.DebugRun(s),t.ClearSol(n.GetSolModifiers()),t.ClearAsyncActionPromises(),e.FlushPendingInstances();s.Reset(null)}_Trigger(e,t,s){if(!t)return this._TriggerForClass(e,t,null,null);{const n=t.GetObjectClass();let r=!1,i=this._TriggerForClass(e,t,n,s);r=r||i;for(const l of n.GetFamilies())i=this._TriggerForClass(e,t,l,s),r=r||i}}_TriggerForClass(e,t,s,n){const r=this._triggers.get(s);if(!r)return!1;const i=n?r.behaviors.get(n):r.methodMap;if(!i)return!1;const l=i.get(e);if(!l)return!1;let o=!1;for(const[e,s]of l){const n=this._ExecuteTrigger(t,e,s);o=o||n}return o}*_DebugTrigger(e,t,s){if(!t)return yield*this._DebugTriggerForClass(e,t,null,null);{const n=t.GetObjectClass();let r=!1,i=yield*this._DebugTriggerForClass(e,t,n,s);r=r||i;for(const l of n.GetFamilies())i=yield*this._DebugTriggerForClass(e,t,l,s),r=r||i}}*_DebugTriggerForClass(e,t,s,n){const r=this._triggers.get(s);if(!r)return!1;const i=n?r.behaviors.get(n):r.methodMap;if(!i)return!1;const l=i.get(e);if(!l)return!1;let o=!1;for(const[e,s]of l){let n;n=e.DebugCanRunFast()?this._ExecuteTrigger(t,e,s):yield*this._DebugExecuteTrigger(t,e,s),o=o||n}return o}_FastTrigger(e,t,s){const n=t.GetObjectClass(),r=this._fastTriggers.get(n);if(!r)return!1;const i=r.get(e);if(!i)return!1;const l=i.get(s);if(!l)return!1;let o=!1;for(let e=0,t=l.length;e<t;++e){const t=l[e],s=this._ExecuteTrigger(null,t[0],t[1]);o=o||s}return o}*_DebugFastTrigger(e,t,s){const n=t.GetObjectClass(),r=this._fastTriggers.get(n);if(!r)return!1;const i=r.get(e);if(!i)return!1;const l=i.get(s);if(!l)return!1;let o=!1;for(let e=0,t=l.length;e<t;++e){const t=l[e],s=t[0],n=t[1];let r;r=s.DebugCanRunFast()?this._ExecuteTrigger(null,s,n):yield*this._DebugExecuteTrigger(null,s,n),o=o||r}return o}_ExecuteTrigger(e,t,s){const n=this._runtime,r=this._eventSheetManager,i=r.GetCurrentEvent(),l=r.GetEventStack(),o=r.GetTriggerDepth();let a=!1;i&&r.PushCleanSol(i.GetSolModifiersIncludingParents()),r.PushCleanSol(t.GetSolModifiersIncludingParents());const c=o>1;c&&r.GetLocalVarStack().Push();const u=l.Push(t);if(e){t.GetConditions()[s].GetObjectClass().GetCurrentSol().SetSinglePicked(e),e.IsInContainer()&&e.SetSiblingsSinglePicked()}let g=!0;if(t.GetParent()){const e=t.GetTriggerParents();for(let t=0,s=e.length;t<s;++t)if(!e[t].RunPreTrigger(u)){g=!1;break}}return g&&(t.IsOrBlock()?t.RunOrBlockTrigger(u,s):t.Run(u),a=u.GetLastEventTrue()),l.Pop(),c&&r.GetLocalVarStack().Pop(),r.PopSol(t.GetSolModifiersIncludingParents()),i&&r.PopSol(i.GetSolModifiersIncludingParents()),i||1!==o||(r.ClearAsyncActionPromises(),r.IsFlushingBlocked()||n.FlushPendingInstances()),a}*_DebugExecuteTrigger(e,t,s){const n=this._runtime,r=this._eventSheetManager,i=r.GetCurrentEvent(),l=r.GetEventStack(),o=r.GetTriggerDepth();let a=!1;i&&r.PushCleanSol(i.GetSolModifiersIncludingParents()),r.PushCleanSol(t.GetSolModifiersIncludingParents());const c=o>1;c&&r.GetLocalVarStack().Push();const u=l.Push(t);if(e){t.GetConditions()[s].GetObjectClass().GetCurrentSol().SetSinglePicked(e),e.IsInContainer()&&e.SetSiblingsSinglePicked()}let g=!0;if(t.GetParent()){const e=t.GetTriggerParents();for(let t=0,s=e.length;t<s;++t)if(!(yield*e[t].DebugRunPreTrigger(u))){g=!1;break}}return g&&(t.IsOrBlock()?yield*t.DebugRunOrBlockTrigger(u,s):yield*t.DebugRun(u),a=u.GetLastEventTrue()),l.Pop(),c&&r.GetLocalVarStack().Pop(),r.PopSol(t.GetSolModifiersIncludingParents()),i&&r.PopSol(i.GetSolModifiersIncludingParents()),i||1!==o||(r.ClearAsyncActionPromises(),r.IsFlushingBlocked()||n.FlushPendingInstances()),a}_GetPerfRecord(){return this._perfRecord}};
}

// events/eventBlock.js
{
const C3=self.C3,EMPTY_ARRAY=[];function NoActions(t,e){return!0}function*DebugNoActions(t,e){return!0}C3.EventBlock=class extends C3.DefendedBase{constructor(t,e,n){super(),this._eventSheet=t,this._runtime=t.GetRuntime(),this._parent=e,this._scopeParent=null,this._eventStack=this._runtime.GetEventSheetManager().GetEventStack(),this._solModifiers=[],this._solModifiersIncludingParents=[],this._hasGotSolModifiersIncludingParents=!1,this._isSolWriterAfterCnds=!1,this._isTopLevelGroup=!1,this._hasElseBlock=!1,this._isOrBlock=!!n[2],this._isElseBlock=!1,this._triggerParents=null,this._conditions=[],this._actions=[],this._subEvents=[],this._RunActions=NoActions,this._DebugRunActions=DebugNoActions,this._isGroup=!1,this._isInitiallyActive=!1,this._groupName="",this._isGroupActive=!1,this._containedIncludes=null,this._perfRecord=null,this._sid=n[4],this._displayNumber=n[5],this._eventSheet._RegisterEventByDisplayNumber(this,this._displayNumber),this._debugData=this._runtime.IsDebug()?{isBreakpoint:n[3][0],isBreakable:n[3][1],canRunAllConditionsFast:!1,canRunAllActionsFast:!1,canRunAllSubEventsFast:!1,canRunSelfFast:!1}:null,this.GetEventSheetManager()._RegisterEventBlock(this),3===n[0]&&this._InitGroup(n[1]);let s=0;for(const t of n[6]){const e=C3.Condition.Create(this,t,s++);this._conditions.push(e),this._AddSolModifier(e.GetObjectClass())}s=0;for(const t of n[7]){const e=C3.Action.Create(this,t,s++);this._actions.push(e)}if(9===n.length){const t=n[8];for(const e of t)this._eventSheet._CreateEvent(e,this,this._subEvents)}this._conditions.length&&(this._isElseBlock=null===this._conditions[0].GetObjectClass()&&this._conditions[0]._GetFunc()===C3.Plugins.System.Cnds.Else),0===this._conditions.length&&(this._conditions=EMPTY_ARRAY),0===this._actions.length&&(this._actions=EMPTY_ARRAY),0===this._subEvents.length&&(this._subEvents=EMPTY_ARRAY)}static Create(t,e,n){return C3.New(C3.EventBlock,t,e,n)}_InitGroup(t){this._isGroup=!0,this._isInitiallyActive=!!t[0],this._isGroupActive=this._isInitiallyActive,this._groupName=t[1].toLowerCase(),this._containedIncludes=[],this.GetEventSheetManager()._RegisterGroup(this),this._runtime.IsDebug()&&(this._perfRecord={type:"group",name:t[1],totalTimeCounter:0,children:[]})}_AddContainedInclude(t){this._containedIncludes.push(t)}_AddContainerSolModifierToList(t,e){for(const n of t.GetContainer().objectTypes())e.includes(n)||e.push(n)}_AddSolModifierToList(t,e){if(t)if(e.includes(t)||e.push(t),t.IsFamily())for(const n of t.GetFamilyMembers())n.IsInContainer()&&this._AddContainerSolModifierToList(n,e);else t.IsInContainer()&&this._AddContainerSolModifierToList(t,e)}_AddSolModifier(t){this._AddSolModifierToList(t,this._solModifiers)}_AddParentSolModifier(t){this._AddSolModifierToList(t,this._solModifiersIncludingParents)}SetAllSolModifiers(){this._solModifiers=this._runtime.GetAllObjectClasses()}_PostInit(t){this._hasElseBlock=!!t,this._IdentifyTopLevelGroup(),this._IdentifyTriggerParents();for(const t of this._conditions)t._PostInit();if(this._actions.length>0){let t=!1;for(const e of this._actions)e._PostInit(),e.HasReturnType()&&(t=!0);t?(this._RunActions=this._RunActions_ReturnValue,this._DebugRunActions=this._DebugRunActions_ReturnValue):(this._RunActions=this._RunActions_Fast,this._DebugRunActions=this._DebugRunActions_Fast)}const e=this._subEvents;for(let t=0,n=e.length;t<n;++t){const s=t<n-1&&e[t+1]instanceof C3.EventBlock&&e[t+1].IsElseBlock();e[t]._PostInit(s)}this._debugData&&this._UpdateCanRunFast(),this._perfRecord&&this._GetPerfRecordParent()._GetPerfRecord().children.push(this._perfRecord)}_GetPerfRecord(){return this._perfRecord}_GetPerfRecordParent(){let t=this.GetParent();for(;t;){if(t.IsGroup())return t;t=t.GetParent()}return this._eventSheet}_UpdateCanRunFast(){const t=this._debugData;t.canRunAllConditionsFast=this._conditions.every((t=>t.DebugCanRunFast())),t.canRunAllActionsFast=this._actions.every((t=>t.DebugCanRunFast())),t.canRunAllSubEventsFast=this._subEvents.every((t=>t.DebugCanRunFast())),t.canRunSelfFast=t.canRunAllConditionsFast&&t.canRunAllActionsFast&&t.canRunAllSubEventsFast}_UpdateCanRunFastRecursive(){let t=this;do{t._UpdateCanRunFast(),t=t.GetParent()}while(t)}_IdentifyTopLevelGroup(){if(!this.IsGroup())return;let t=this.GetParent();for(this._isTopLevelGroup=!0;t;){if(!t.IsGroup()){this._isTopLevelGroup=!1;break}t=t.GetParent()}}_IdentifySolModifiersIncludingParents(){const t=this._runtime.GetAllObjectClasses();if(this._solModifiers===t)this._solModifiersIncludingParents=t;else{this._solModifiersIncludingParents=C3.cloneArray(this._solModifiers);let t=this.GetParent();for(;t;){for(const e of t._solModifiers)this._AddParentSolModifier(e);t=t.GetParent()}const e=this.GetEventSheetManager();this._solModifiers=e._DeduplicateSolModifierList(this._solModifiers),this._solModifiersIncludingParents=e._DeduplicateSolModifierList(this._solModifiersIncludingParents)}}_IdentifyTriggerParents(){if(!this.HasAnyTriggeredCondition())return;this._triggerParents=[];let t=this.GetParent();for(;t;)this._triggerParents.push(t),t=t.GetParent();this._triggerParents.reverse()}SetSolWriterAfterCnds(){this._isSolWriterAfterCnds=!0,this._parent&&this._parent.SetSolWriterAfterCnds()}IsSolWriterAfterCnds(){return this._isSolWriterAfterCnds}GetSolModifiers(){return this._solModifiers}GetSolModifiersIncludingParents(){return this._hasGotSolModifiersIncludingParents||(this._hasGotSolModifiersIncludingParents=!0,this._IdentifySolModifiersIncludingParents()),this._solModifiersIncludingParents}HasSolModifier(t){return this._solModifiers.includes(t)}GetTriggerParents(){return this._triggerParents}GetEventSheet(){return this._eventSheet}GetEventSheetManager(){return this._eventSheet.GetEventSheetManager()}GetRuntime(){return this._runtime}GetParent(){return this._parent}_SetScopeParent(t){this._scopeParent=t}GetScopeParent(){return this._scopeParent||this._parent}GetDisplayNumber(){return this._displayNumber}IsDebugBreakable(){return this._debugData&&this._debugData.isBreakable}IsDebugBreakpoint(){return this.IsDebugBreakable()&&this._debugData.isBreakpoint}_SetDebugBreakpoint(t){this._debugData.isBreakpoint=!!t,this._UpdateCanRunFastRecursive()}IsGroup(){return this._isGroup}IsTopLevelGroup(){return this._isTopLevelGroup}IsElseBlock(){return this._isElseBlock}HasElseBlock(){return this._hasElseBlock}GetGroupName(){return this._groupName}IsGroupActive(){return this._isGroupActive}ResetInitialActivation(){this.SetGroupActive(this._isInitiallyActive)}SetGroupActive(t){if(t=!!t,!this._isGroup)throw new Error("not a group");if(this._isGroupActive!==t){this._isGroupActive=t;for(const t of this._containedIncludes)t.UpdateActive();if(this._containedIncludes.length){const t=this._runtime.GetCurrentLayout().GetEventSheet();t&&t._UpdateDeepIncludes()}}}GetSID(){return this._sid}IsOrBlock(){return this._isOrBlock}IsTrigger(){return this._conditions.length&&this._conditions[0].IsTrigger()}IsForFunctionBlock(){return this._scopeParent&&this._scopeParent instanceof C3.FunctionBlock}HasAnyTriggeredCondition(){return this.IsForFunctionBlock()||this._conditions.some((t=>t.IsTrigger()))}GetConditions(){return this._conditions}GetConditionCount(){return this._conditions.length}GetConditionAt(t){if((t=Math.floor(t))<0||t>=this._conditions.length)throw new RangeError("invalid condition index");return this._conditions[t]}GetConditionByDebugIndex(t){return this.GetConditionAt(t)}IsFirstConditionOfType(t){let e=t.GetIndex();if(0===e)return!0;--e;const n=t.IsSystemOrSingleGlobalCondition()?t.GetFirstObjectParameterObjectClass():t.GetObjectClass();for(;e>=0;--e){const t=this._conditions[e];if(n===t.GetObjectClass()||t.IsSystemOrSingleGlobalCondition()&&t.GetFirstObjectParameterObjectClass()===n)return!1}return!0}GetActions(){return this._actions}GetActionCount(){return this._actions.length}GetActionAt(t){if((t=Math.floor(t))<0||t>=this._actions.length)throw new RangeError("invalid action index");return this._actions[t]}GetActionByDebugIndex(t){t=Math.floor(t);const e=this._actions.find((e=>e.GetDebugIndex()===t));if(!e)throw new RangeError("invalid action debug index");return e}_HasActionIndex(t){return(t=Math.floor(t))>=0&&t<this._actions.length}GetSubEvents(){return this._subEvents}_GetAllLocalVariablesInScope(){return this._subEvents.filter((t=>t instanceof C3.EventVariable))}RunPreTrigger(t){t.SetCurrentEvent(this);const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s<i;++s){const i=e[s];if(t.SetConditionIndex(s),i.IsLooping())throw new Error("trigger cannot be used as sub-event to a loop");if(i.Run())n=!0;else if(!this._isOrBlock)return!1}return!this._isOrBlock||n}RunOrBlockTrigger(t,e){t.SetCurrentEvent(this),t.SetConditionIndex(e),this._conditions[e].Run()&&(this._RunActions(t,0)&&this._RunSubEvents(t),t.SetLastEventTrue(!0))}*DebugRunPreTrigger(t){t.SetCurrentEvent(this);const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s<i;++s){const i=e[s];if(t.SetConditionIndex(s),i.IsLooping())throw new Error("trigger cannot be used as sub-event to a loop");let o;if(o=i.DebugCanRunFast()?i.Run():yield*i.DebugRun(),o)n=!0;else if(!this._isOrBlock)return!1}return!this._isOrBlock||n}*DebugRunOrBlockTrigger(t,e){t.SetCurrentEvent(this),t.SetConditionIndex(e);const n=this._conditions[e];let s;if(s=n.DebugCanRunFast()?n.Run():yield*n.DebugRun(),s){let e;e=this.DebugCanRunActionsFast()?this._RunActions(t,0):yield*this._DebugRunActions(t,0),e&&(this.DebugCanRunSubEventsFast()?this._RunSubEvents():yield*this._DebugRunSubEvents()),t.SetLastEventTrue(!0)}}Run(t){t.SetCurrentEvent(this),this._isElseBlock||t.SetElseBranchRan(!1),this._isOrBlock?this._RunOrBlock(t):this._RunAndBlock(t)}*DebugRun(t){(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),t.SetCurrentEvent(this),this._isElseBlock||t.SetElseBranchRan(!1),this._isOrBlock?yield*this._DebugRunOrBlock(t):yield*this._DebugRunAndBlock(t)}_RunOrBlock(t){const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s<i;++s){const i=e[s];if(i.IsTrigger())continue;t.SetConditionIndex(s);const o=i.Run();n=n||o}t.SetLastEventTrue(n),n&&(this._RunActions(t,0)&&this._RunSubEvents(t),this._hasElseBlock&&t.SetElseBranchRan(!0))}*_DebugRunOrBlock(t){const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s<i;++s){const i=e[s];if(i.IsTrigger())continue;let o;t.SetConditionIndex(s),o=i.DebugCanRunFast()?i.Run():yield*i.DebugRun(),n=n||o}if(t.SetLastEventTrue(n),n){let e;e=this.DebugCanRunActionsFast()?this._RunActions(t,0):yield*this._DebugRunActions(t,0),e&&(this.DebugCanRunSubEventsFast()?this._RunSubEvents():yield*this._DebugRunSubEvents()),this._hasElseBlock&&t.SetElseBranchRan(!0)}}_RunAndBlock(t){const e=this._conditions;for(let n=0,s=e.length;n<s;++n){const s=e[n];t.SetConditionIndex(n);if(!s.Run())return void t.SetLastEventTrue(!1)}t.SetLastEventTrue(!0),this._RunActions(t,0)&&this._RunSubEvents(t),t.GetLastEventTrue()&&this._hasElseBlock&&t.SetElseBranchRan(!0)}*_DebugRunAndBlock(t){const e=this._conditions;for(let n=0,s=e.length;n<s;++n){const s=e[n];let i;if(t.SetConditionIndex(n),i=s.DebugCanRunFast()?s.Run():yield*s.DebugRun(),!i)return void t.SetLastEventTrue(!1)}let n;t.SetLastEventTrue(!0),n=this.DebugCanRunActionsFast()?this._RunActions(t,0):yield*this._DebugRunActions(t,0),n&&(this.DebugCanRunSubEventsFast()?this._RunSubEvents():yield*this._DebugRunSubEvents()),t.GetLastEventTrue()&&this._hasElseBlock&&t.SetElseBranchRan(!0)}_RunActions_Fast(t,e){const n=this._actions;for(let s=e,i=n.length;s<i;++s){const e=n[s];t.SetActionIndex(s),e.Run()}return!0}*_DebugRunActions_Fast(t,e){const n=this._actions;for(let s=e,i=n.length;s<i;++s){const e=n[s];t.SetActionIndex(s),e.DebugCanRunFast()?e.Run():yield*e.DebugRun()}return!0}_RunActions_ReturnValue(t,e){const n=this.GetEventSheetManager(),s=this._actions;for(let i=e,o=s.length;i<o;++i){const e=s[i];t.SetActionIndex(i);const o=e.Run();if(e.CanBailOut()&&!0===o)return!1;e.IsAsync()&&o instanceof Promise&&n.AddAsyncActionPromise(o)}return!0}*_DebugRunActions_ReturnValue(t,e){const n=this.GetEventSheetManager(),s=this._actions;for(let i=e,o=s.length;i<o;++i){const e=s[i];let o;if(t.SetActionIndex(i),o=e.DebugCanRunFast()?e.Run():yield*e.DebugRun(),e.CanBailOut()&&!0===o)return!1;e.IsAsync()&&o instanceof Promise&&n.AddAsyncActionPromise(o)}return!0}_ResumeActionsAndSubEvents(t){this._RunActions(t,t.GetActionIndex())&&this._RunSubEvents()}*_DebugResumeActionsAndSubEvents(t){(yield*this._DebugRunActions(t,t.GetActionIndex()))&&(yield*this._DebugRunSubEvents())}_RunSubEvents(){if(!this._subEvents.length)return;const t=this.IsGroup()&&this._runtime.IsCPUProfiling(),e=t?performance.now():0,n=this._eventStack,s=n.Push(this);this._isSolWriterAfterCnds?this._RunSubEvents_SolWriterAfterCnds(s):this._RunSubEvents_Fast(s),n.Pop(),t&&(this._perfRecord.totalTimeCounter+=performance.now()-e)}_RunSubEvents_SolWriterAfterCnds(t){const e=this._isGroup,n=this._isTopLevelGroup,s=this.GetEventSheetManager(),i=this._subEvents;for(let o=0,r=i.length,u=r-1;o<r;++o){const r=i[o],l=r.GetSolModifiers(),a=!n||!e&&o<u;a&&s.PushCopySol(l),r.Run(t),a?s.PopSol(l):s.ClearSol(l)}}_RunSubEvents_Fast(t){const e=this._subEvents;for(let n=0,s=e.length;n<s;++n)e[n].Run(t)}*_DebugRunSubEvents(){if(!this._subEvents.length)return;const t=this._eventStack,e=t.Push(this);this._isSolWriterAfterCnds?yield*this._DebugRunSubEvents_SolWriterAfterCnds(e):yield*this._DebugRunSubEvents_Fast(e),t.Pop()}*_DebugRunSubEvents_SolWriterAfterCnds(t){const e=this._isGroup,n=this._isTopLevelGroup,s=this.GetEventSheetManager(),i=this._subEvents;for(let o=0,r=i.length,u=r-1;o<r;++o){const r=i[o],l=r.GetSolModifiers(),a=!n||!e&&o<u;a&&s.PushCopySol(l),yield*r.DebugRun(t),a?s.PopSol(l):s.ClearSol(l)}}*_DebugRunSubEvents_Fast(t){const e=this._subEvents;for(let n=0,s=e.length;n<s;++n)yield*e[n].DebugRun(t)}Retrigger(t,e){e.ResetQuick();const n=this._conditions;if(!this.IsOrBlock())for(let s=t.GetConditionIndex()+1,i=n.length;s<i;++s){const t=n[s];e.SetConditionIndex(s);if(!t.Run())return!1}return this._RunActions(e,0)&&this._RunSubEvents(e),!0}*DebugRetrigger(t,e){e.ResetQuick();const n=this._conditions;if(!this.IsOrBlock())for(let s=t.GetConditionIndex()+1,i=n.length;s<i;++s){const t=n[s];let i;if(e.SetConditionIndex(s),i=t.DebugCanRunFast()?t.Run():yield*t.DebugRun(),!i)return!1}let s;return s=this.DebugCanRunActionsFast()?this._RunActions(e,0):yield*this._DebugRunActions(e,0),s&&(this.DebugCanRunSubEventsFast()?this._RunSubEvents():yield*this._DebugRunSubEvents()),!0}DebugCanRunFast(){return!this.IsDebugBreakpoint()&&!this._runtime.DebugBreakNext()&&this._debugData.canRunSelfFast}DebugCanRunActionsFast(){return!this._runtime.DebugBreakNext()&&this._debugData.canRunAllActionsFast}DebugCanRunSubEventsFast(){return!this._runtime.DebugBreakNext()&&this._debugData.canRunAllSubEventsFast}_CheckParentsOKToRun(t){if(this.GetParent()){const e=this.GetTriggerParents();for(let n=0,s=e.length;n<s;++n)if(!e[n].RunPreTrigger(t))return!1}return!0}*_DebugCheckParentsOKToRun(t){if(this.GetParent()){const e=this.GetTriggerParents();for(let n=0,s=e.length;n<s;++n)if(!(yield*e[n].DebugRunPreTrigger(t)))return!1}return!0}_EvaluateFunctionCallParameters(t,e,n){if(e.length>0)if(n){const n=e.map((t=>t.Get(0)));t.GetLocalVarStack().Push(),this._scopeParent.SetFunctionParameters(n)}else this._scopeParent.EvaluateFunctionParameters(e);else n&&t.GetLocalVarStack().Push()}RunAsFunctionCall(t,e,n,s){let i,o;const r=t.length>0;let u=null;const l=this._runtime,a=this._eventStack,h=l.GetEventSheetManager(),c=this._scopeParent,_=c.IsAsync(),d=h._IncTriggerDepth()>1;if(this._EvaluateFunctionCallParameters(h,e,d),r&&(n?h.PushCopySol(t):h.PushCleanSol(t)),null!==s){if(s.copyFromObjectClass){const t=n?s.copyFromObjectClass.GetCurrentSol():s.copyFromObjectClass.GetSolStack().GetOneBelowCurrentSol(),e=s.copyToObjectClass.GetCurrentSol();e.SetArrayPicked(t.GetInstances()),e.ClearElseInstances(),n||s.copyToObjectClass.ApplySolToContainer()}else if(s.pickObjectClass){const t=s.pickObjectClass.GetCurrentSol();t.SetArrayPicked(s.pickInstances),t.ClearElseInstances()}s.pushCleanSolDynamic&&(u=h.PushCleanSolDynamic(t))}const g=a.Push(this);return n&&g.SetDynamicSolModifiers(t),this._CheckParentsOKToRun(g)&&(g.SetCurrentEvent(this),_&&([o,i]=c.StartAsyncFunctionCall()),this._RunAndBlock(g),_&&c.MaybeFinishAsyncFunctionCall(o)),a.Pop(),d&&h.GetLocalVarStack().Pop(),null!==u&&h.PopSol(u),r&&h.PopSol(t),h._DecTriggerDepth(),i}*DebugRunAsFunctionCall(t,e,n,s){let i,o;(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())&&(yield this);const r=t.length>0;let u=null;const l=this._runtime,a=this._eventStack,h=l.GetEventSheetManager(),c=this._scopeParent,_=c.IsAsync(),d=h._IncTriggerDepth()>1;if(this._EvaluateFunctionCallParameters(h,e,d),r&&(n?h.PushCopySol(t):h.PushCleanSol(t)),null!==s){if(s.copyFromObjectClass){const t=n?s.copyFromObjectClass.GetCurrentSol():s.copyFromObjectClass.GetSolStack().GetOneBelowCurrentSol(),e=s.copyToObjectClass.GetCurrentSol();e.SetArrayPicked(t.GetInstances()),e.ClearElseInstances(),n||s.copyToObjectClass.ApplySolToContainer()}else if(s.pickObjectClass){const t=s.pickObjectClass.GetCurrentSol();t.SetArrayPicked(s.pickInstances),t.ClearElseInstances()}s.pushCleanSolDynamic&&(u=h.PushCleanSolDynamic(t))}const g=a.Push(this);return n&&g.SetDynamicSolModifiers(t),(yield*this._DebugCheckParentsOKToRun(g))&&(g.SetCurrentEvent(this),_&&([o,i]=c.StartAsyncFunctionCall()),yield*this._DebugRunAndBlock(g),_&&c.MaybeFinishAsyncFunctionCall(o)),a.Pop(),d&&h.GetLocalVarStack().Pop(),null!==u&&h.PopSol(u),r&&h.PopSol(t),h._DecTriggerDepth(),i}RunAsMappedFunctionCall(t,e){const n=this.GetSolModifiersIncludingParents(),s=n.length>0,i=this._runtime,o=this._eventStack,r=i.GetEventSheetManager(),u=r._IncTriggerDepth()>1;u&&r.GetLocalVarStack().Push(),this._scopeParent.SetFunctionParameters(t),s&&(e?r.PushCopySol(n):r.PushCleanSol(n));const l=o.Push(this);this._CheckParentsOKToRun(l)&&(l.SetCurrentEvent(this),this._RunAndBlock(l)),o.Pop(),u&&r.GetLocalVarStack().Pop(),s&&r.PopSol(n),r._DecTriggerDepth()}*DebugRunAsMappedFunctionCall(t,e){(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())&&(yield this);const n=this.GetSolModifiersIncludingParents(),s=n.length>0,i=this._runtime,o=this._eventStack,r=i.GetEventSheetManager(),u=r._IncTriggerDepth()>1;u&&r.GetLocalVarStack().Push(),this._scopeParent.SetFunctionParameters(t),s&&(e?r.PushCopySol(n):r.PushCleanSol(n));const l=o.Push(this);(yield*this._DebugCheckParentsOKToRun(l))&&(l.SetCurrentEvent(this),yield*this._DebugRunAndBlock(l)),o.Pop(),u&&r.GetLocalVarStack().Pop(),s&&r.PopSol(n),r._DecTriggerDepth()}RunAsExpressionFunctionCall(t,e,n,s,...i){let o,r;const u=t.length>0,l=this._runtime,a=this._eventStack,h=l.GetEventSheetManager(),c=this._scopeParent,_=c.IsAsync(),d=h._IncTriggerDepth()>1;d&&h.GetLocalVarStack().Push(),i.length>0&&this._scopeParent.SetFunctionParameters(i),u&&(e?h.PushCopySol(t):h.PushCleanSol(t));const g=a.Push(this);return g.InitCallFunctionExpression(n,s),a.PushExpFunc(g),l.SetDebuggingEnabled(!1),this._CheckParentsOKToRun(g)&&(g.SetCurrentEvent(this),_&&([r,o]=c.StartAsyncFunctionCall()),this._RunAndBlock(g),_&&c.MaybeFinishAsyncFunctionCall(r)),l.SetDebuggingEnabled(!0),a.Pop(),a.PopExpFunc(),d&&h.GetLocalVarStack().Pop(),u&&h.PopSol(t),h._DecTriggerDepth(),o||g.GetFunctionReturnValue()}};
}

// events/eventScript.js
{
const C3=self.C3,EMPTY_SOL_MODIFIERS=[];let hadUserScriptException=!1;C3.EventScript=class extends C3.DefendedBase{constructor(e,t,i){super();const r=e.GetRuntime(),n=e.GetEventSheetManager();this._eventSheet=e,this._eventSheetManager=n,this._runtime=e.GetRuntime(),this._parent=t;const s=r.GetObjectReference(i[1]);this._func=s,this._displayNumber=i[2],this._eventSheet._RegisterEventByDisplayNumber(this,this._displayNumber),this._debugData=r.IsDebug()?{isBreakpoint:i[3][0],isBreakable:i[3][1]}:null}static Create(e,t,i){return C3.New(C3.EventScript,e,t,i)}_PostInit(){const e=this._func,t=this._runtime.GetEventSheetManager()._GetLocalVariablesScriptInterface(this);this._func=e.bind(null,this._runtime.GetIRuntime(),t)}GetParent(){return this._parent}GetScopeParent(){return this._parent}GetEventSheet(){return this._eventSheet}GetDisplayNumber(){return this._displayNumber}IsDebugBreakable(){return this._debugData&&this._debugData.isBreakable}IsDebugBreakpoint(){return this.IsDebugBreakable()&&this._debugData.isBreakpoint}_SetDebugBreakpoint(e){this._debugData.isBreakpoint=!!e}IsElseBlock(){return!1}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}GetSolModifiersIncludingParents(){return this._parent?this._parent.GetSolModifiersIncludingParents():EMPTY_SOL_MODIFIERS}Run(e){e.SetCurrentEvent(this),this._eventSheetManager.AddAsyncActionPromise(this._RunUserScript())}async _RunUserScript(){try{await this._func()}catch(e){console.error(`Unhandled exception running script %c${this.GetEventSheet().GetName()}, event ${this.GetDisplayNumber()}:`,"font-size: 1.2em; font-weight: bold;",e),self.C3Debugger&&self.C3Debugger._SetLastErrorScript(this),hadUserScriptException||(console.info("%cTip:%c run this to highlight in Construct the last script that had an error: %cgoToLastErrorScript()","font-weight: bold; text-decoration: underline","","font-weight: bold"),hadUserScriptException=!0)}}*DebugRun(e){e.SetCurrentEvent(this),(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this.Run(e)}DebugCanRunFast(){return!this.IsDebugBreakpoint()&&!this._runtime.DebugBreakNext()}static HadUserScriptException(){return hadUserScriptException}static SetHadUserScriptException(){hadUserScriptException=!0}};
}

// events/functionBlock.js
{
const C3=self.C3,assert=self.assert;C3.FunctionBlock=class extends C3.DefendedBase{constructor(t,e,s){super(),this._eventSheet=t,this._runtime=t.GetRuntime(),this._parent=e,this._functionType=0,this._functionName="",this._returnType=0,this._functionParameters=[],this._isEnabled=!0,this._aceName="",this._objectClass=null,this._hasOverrides=!1,this._innerLocalVariables=[],this._isCopyPicked=!1,this._isAsync=!1,this._nextAsyncId=0,this._currentAsyncId=-1,this._asyncMap=new Map,this._eventBlock=C3.EventBlock.Create(t,e,s),this._eventBlock._SetScopeParent(this)}InitFunctionBlock(t){this._functionType=0,this._functionName=t[0],this._returnType=t[1],this._functionParameters=t[2].map((t=>C3.EventVariable.Create(this._eventSheet,this,t))),this._isEnabled=t[3],this._isAsync=t[4],this._isCopyPicked=t[5]}InitCustomACEBlock(t){this._functionType=1,this._aceName=t[1],this._objectClass=this._runtime.GetObjectClassByIndex(t[2]),this._eventBlock._AddSolModifier(this._objectClass),this._functionName=this._objectClass.GetName()+"."+this._aceName,this._returnType=t[3],this._functionParameters=t[4].map((t=>C3.EventVariable.Create(this._eventSheet,this,t))),this._isEnabled=t[5],this._isAsync=t[6],this._isCopyPicked=t[7],this._objectClass.AddCustomAction(this)}static CreateFunctionBlock(t,e,s){const n=C3.New(C3.FunctionBlock,t,e,s),i=s[1];return n.InitFunctionBlock(i),n}static CreateCustomACEBlock(t,e,s){const n=C3.New(C3.FunctionBlock,t,e,s),i=s[1];return n.InitCustomACEBlock(i),n}_CheckOverrideState(){if(this._objectClass&&this._objectClass.IsFamily())for(const t of this._objectClass.GetFamilyMembers())if(t.HasOwnCustomActionByName(this._aceName)){this._hasOverrides=!0;break}}_PostInit(){for(const t of this._functionParameters)t._PostInit();this._eventBlock._PostInit(!1)}GetFunctionType(){return this._functionType}_GetAllLocalVariablesInScope(){return this._functionParameters}GetFunctionParameters(){return this._functionParameters}GetFunctionParameterCount(){return this._functionParameters.length}_RegisterLocalVariable(t){this._innerLocalVariables.push(t)}_GetAllInnerLocalVariables(){return this._innerLocalVariables}EvaluateFunctionParameters(t){const e=this._functionParameters;for(let s=0,n=e.length;s<n;++s)e[s].SetValue(t[s].Get(0))}SetFunctionParameters(t){const e=this._functionParameters;for(let s=0,n=e.length;s<n;++s)e[s].SetValue(t[s])}CaptureFunctionParameters(){return this._functionParameters.map((t=>t.GetValue()))}GetParent(){return this._parent}GetScopeParent(){return this._parent}GetFunctionName(){return this._functionName}GetACEName(){return this._aceName}HasCustomACEOverrides(){return this._hasOverrides}GetReturnType(){return this._returnType}GetObjectClass(){return this._objectClass}IsEnabled(){return this._isEnabled}GetDefaultReturnValue(){switch(this._returnType){case 0:return null;case 2:return"";default:return 0}}GetEventBlock(){return this._eventBlock}IsCopyPicked(){return this._isCopyPicked}IsAsync(){return this._isAsync}StartAsyncFunctionCall(){const t=this._nextAsyncId++;let e;this._currentAsyncId=t;const s=new Promise((t=>e=t));return this._asyncMap.set(t,{resolve:e,pauseCount:0}),[t,s]}MaybeFinishAsyncFunctionCall(t){const e=this._asyncMap.get(t);0===e.pauseCount&&(e.resolve(),this._asyncMap.delete(t)),this._currentAsyncId=-1}PauseCurrentAsyncFunction(){return this._asyncMap.get(this._currentAsyncId).pauseCount++,this._currentAsyncId}ResumeAsyncFunction(t){this._currentAsyncId=t;this._asyncMap.get(t).pauseCount--}RunAsFamilyCustomActionWithOverrides(t,e){const s=new Map,n=[];for(const t of this._objectClass.GetCurrentSol().GetInstances()){const e=t.GetObjectClass();if(e.HasOwnCustomActionByName(this._aceName)){const n=s.get(e);Array.isArray(n)?n.push(t):s.set(e,[t])}else n.push(t)}if(n.length>0&&this._eventBlock.RunAsFunctionCall(t,e,this._isCopyPicked,{pickObjectClass:this._objectClass,pickInstances:n}),s.size>0)for(const[n,i]of s){const s=n.GetOwnCustomActionByName(this._aceName).GetEventBlock(),a=[...new Set([...t,...s.GetSolModifiers()])];s.RunAsFunctionCall(a,e,this._isCopyPicked,{pickObjectClass:n,pickInstances:i})}}*DebugRunAsFamilyCustomActionWithOverrides(t,e){const s=new Map,n=[];for(const t of this._objectClass.GetCurrentSol().GetInstances()){const e=t.GetObjectClass();if(e.HasOwnCustomActionByName(this._aceName)){const n=s.get(e);Array.isArray(n)?n.push(t):s.set(e,[t])}else n.push(t)}if(n.length>0&&(yield*this._eventBlock.DebugRunAsFunctionCall(t,e,this._isCopyPicked,{pickObjectClass:this._objectClass,pickInstances:n})),s.size>0)for(const[n,i]of s){const s=n.GetOwnCustomActionByName(this._aceName).GetEventBlock(),a=[...new Set([...t,...s.GetSolModifiers()])];yield*s.DebugRunAsFunctionCall(a,e,this._isCopyPicked,{pickObjectClass:n,pickInstances:i})}}};
}

// events/eventVariable.js
{
const C3=self.C3,EMPTY_SOL_MODIFIERS=[];C3.EventVariable=class extends C3.DefendedBase{constructor(t,e,s){super();const i=t.GetEventSheetManager();this._eventSheet=t,this._eventSheetManager=i,this._runtime=t.GetRuntime(),this._parent=e,this._localVarStack=i.GetLocalVarStack(),this._name=s[1],this._type=s[2],this._initialValue=s[3],this._isStatic=!!s[4],this._isConstant=!!s[5],this._isFunctionParameter=e instanceof C3.FunctionBlock,this._sid=s[6],this._jsPropName=this._runtime.GetJsPropName(s[8]),this._scriptSetter=t=>this.SetValue(t),this._scriptGetter=()=>this.GetValue(),this._hasSingleValue=!this._parent||this._isStatic||this._isConstant,this._value=this._initialValue,this._localIndex=-1,this.IsBoolean()&&(this._value=this._value?1:0),!this.IsLocal()||this.IsStatic()||this.IsConstant()||(this._localIndex=i._GetNextLocalVarIndex(this)),i._RegisterEventVariable(this)}static Create(t,e,s){return C3.New(C3.EventVariable,t,e,s)}_PostInit(){if(this.IsLocal()&&!this.IsStatic()&&!this.IsConstant()&&!this.IsFunctionParameter()){const t=this._eventSheetManager.FindFirstFunctionBlockParent(this);t&&t._RegisterLocalVariable(this)}}GetName(){return this._name}GetJsPropName(){return this._jsPropName}GetParent(){return this._parent}GetScopeParent(){return this.GetParent()}IsGlobal(){return!this.GetParent()}IsLocal(){return!this.IsGlobal()}IsFunctionParameter(){return this._isFunctionParameter}IsStatic(){return this._isStatic}IsConstant(){return this._isConstant}IsNumber(){return 0===this._type}IsString(){return 1===this._type}IsBoolean(){return 2===this._type}IsElseBlock(){return!1}GetSID(){return this._sid}GetInitialValue(){return this._initialValue}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}Run(t){!this.IsLocal()||this.IsStatic()||this.IsConstant()||this.SetValue(this.GetInitialValue())}DebugCanRunFast(){return!0}*DebugRun(t){this.Run(t)}SetValue(t){this.IsNumber()?"number"!=typeof t&&(t=parseFloat(t)):this.IsString()?"string"!=typeof t&&(t=t.toString()):this.IsBoolean()&&(t=t?1:0),this._hasSingleValue?this._value=t:this._localVarStack.GetCurrent()[this._localIndex]=t}GetValue(){return this._hasSingleValue?this._value:this._localVarStack.GetCurrent()[this._localIndex]}GetTypedValue(){let t=this.GetValue();return this.IsBoolean()&&(t=!!t),t}ResetToInitialValue(){this._value=this._initialValue}_GetScriptInterfaceDescriptor(){return{configurable:!1,enumerable:!0,get:this._scriptGetter,set:this._scriptSetter}}};
}

// events/eventInclude.js
{
const C3=self.C3,assert=self.assert,EMPTY_SOL_MODIFIERS=[];C3.EventInclude=class extends C3.DefendedBase{constructor(e,t,n){super();const s=e.GetEventSheetManager();this._eventSheet=e,this._eventSheetManager=s,this._runtime=e.GetRuntime(),this._parent=t,this._includeSheet=null,this._includeSheetName=n[1],this._isActive=!0}static Create(e,t,n){return C3.New(C3.EventInclude,e,t,n)}_PostInit(){this._includeSheet=this._eventSheetManager.GetEventSheetByName(this._includeSheetName),this._eventSheet._AddShallowInclude(this);let e=this.GetParent();for(;e;)e instanceof C3.EventBlock&&e.IsGroup()&&e._AddContainedInclude(this),e=e.GetParent();this.UpdateActive(),this._runtime.IsDebug()&&this._eventSheet._GetPerfRecord().children.push(this._includeSheet._GetPerfRecord())}GetParent(){return this._parent}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}GetIncludeSheet(){return this._includeSheet}Run(e){const t=!!this.GetParent(),n=this._runtime.GetAllObjectClasses();t&&this._eventSheetManager.PushCleanSol(n),this._includeSheet.Run(),t&&this._eventSheetManager.PopSol(n)}*DebugRun(e){const t=!!this.GetParent(),n=this._runtime.GetAllObjectClasses();t&&this._eventSheetManager.PushCleanSol(n),yield*this._includeSheet.DebugRun(),t&&this._eventSheetManager.PopSol(n)}DebugCanRunFast(){return!1}IsActive(){return this._isActive}UpdateActive(){let e=this.GetParent();for(;e;){if(e instanceof C3.EventBlock&&e.IsGroup()&&!e.IsGroupActive())return void(this._isActive=!1);e=e.GetParent()}this._isActive=!0}};
}

// events/expNode.js
{
const C3=self.C3,assert=self.assert;C3.ExpNode=class extends C3.DefendedBase{constructor(e){super(),this._owner=e,this._runtime=e.GetRuntime()}_PostInit(){}static CreateNode(e,t){const s=t[0],n=[BehaviorExpressionNode,ObjectExpressionNode,InstVarExpressionNode,EventVarExpNode,SystemExpressionExpNode,CallFunctionExpressionExpNode];return C3.New(n[s],e,t)}};class SystemExpressionExpNode extends C3.ExpNode{constructor(e,t){super(e),this._systemPlugin=this._runtime.GetSystemPlugin(),this._func=this._runtime.GetObjectReference(t[1]),this._func!==C3.Plugins.System.Exps.random&&this._func!==C3.Plugins.System.Exps.choose||this._owner.SetVariesPerInstance()}GetBoundMethod(){return this._systemPlugin._GetBoundACEMethod(this._func,this._systemPlugin)}}class CallFunctionExpressionExpNode extends C3.ExpNode{constructor(e,t){super(e),this._functionBlock=null,this._functionName=t[1],this._owner.SetVariesPerInstance()}_PostInit(){const e=this._runtime.GetEventSheetManager();this._functionBlock=e.GetFunctionBlockByName(this._functionName),this._functionName=null;const t=this._owner.GetEventBlock(),s=this._functionBlock.GetEventBlock();this._combinedSolModifiers=[...new Set([...t.GetSolModifiersIncludingParents(),...s.GetSolModifiersIncludingParents()])],this._combinedSolModifiers=e._DeduplicateSolModifierList(this._combinedSolModifiers)}GetBoundMethod(){const e=this._functionBlock;if(e.IsEnabled()){const t=e.GetEventBlock();return C3.EventBlock.prototype.RunAsExpressionFunctionCall.bind(t,this._combinedSolModifiers,e.IsCopyPicked(),e.GetReturnType(),e.GetDefaultReturnValue())}{const t=e.GetDefaultReturnValue();return()=>t}}}function WrapIndex(e,t){return e>=t?e%t:e<0?(e<=-t&&(e%=t),e<0&&(e+=t),e):e}class ObjectExpressionNode extends C3.ExpNode{constructor(e,t){super(e),this._objectClass=this._runtime.GetObjectClassByIndex(t[1]),this._func=this._runtime.GetObjectReference(t[2]),this._returnsString=!!t[3],this._eventStack=this._runtime.GetEventSheetManager().GetEventStack(),this._owner._MaybeVaryFor(this._objectClass)}GetBoundMethod(){return this._objectClass.GetPlugin()._GetBoundACEMethod(this._func,this._objectClass.GetSingleGlobalInstance().GetSdkInstance())}ExpObject(...e){const t=this._objectClass,s=t.GetCurrentSol().GetExpressionInstances(),n=s.length;if(0===n)return this._returnsString?"":0;const r=WrapIndex(this._owner.GetSolIndex(),n);return this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(t),this._func.apply(s[r].GetSdkInstance(),e)}ExpObject_InstExpr(e,...t){const s=this._objectClass,n=s.GetInstances(),r=n.length;if(0===r||"number"!=typeof e)return this._returnsString?"":0;const i=WrapIndex(e,r);return this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(s),this._func.apply(n[i].GetSdkInstance(),t)}}class InstVarExpressionNode extends C3.ExpNode{constructor(e,t){super(e),this._objectClass=this._runtime.GetObjectClassByIndex(t[1]),this._varIndex=t[3],this._returnsString=!!t[2],this._owner._MaybeVaryFor(this._objectClass)}ExpInstVar(){const e=this._objectClass.GetCurrentSol().GetExpressionInstances(),t=e.length;if(0===t)return this._returnsString?"":0;return e[WrapIndex(this._owner.GetSolIndex(),t)]._GetInstanceVariableValueUnchecked(this._varIndex)}ExpInstVar_Family(){const e=this._objectClass,t=e.GetCurrentSol().GetExpressionInstances(),s=t.length;if(0===s)return this._returnsString?"":0;const n=t[WrapIndex(this._owner.GetSolIndex(),s)],r=n.GetObjectClass().GetFamilyInstanceVariableOffset(e.GetFamilyIndex());return n._GetInstanceVariableValueUnchecked(this._varIndex+r)}ExpInstVar_InstExpr(e){const t=this._objectClass,s=t.GetInstances(),n=s.length;if(0===n||"number"!=typeof e)return this._returnsString?"":0;const r=s[WrapIndex(e,n)];let i=0;return t.IsFamily()&&(i=r.GetObjectClass().GetFamilyInstanceVariableOffset(t.GetFamilyIndex())),r._GetInstanceVariableValueUnchecked(this._varIndex+i)}}class BehaviorExpressionNode extends C3.ExpNode{constructor(e,t){super(e),this._objectClass=this._runtime.GetObjectClassByIndex(t[1]),this._behaviorType=this._objectClass.GetBehaviorTypeByName(t[2]),this._behaviorIndex=this._objectClass.GetBehaviorIndexByName(t[2]),this._func=this._runtime.GetObjectReference(t[3]),this._returnsString=!!t[4],this._eventStack=this._runtime.GetEventSheetManager().GetEventStack(),this._owner._MaybeVaryFor(this._objectClass)}ExpBehavior(...e){const t=this._objectClass,s=t.GetCurrentSol().GetExpressionInstances(),n=s.length;if(0===n)return this._returnsString?"":0;const r=WrapIndex(this._owner.GetSolIndex(),n);this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(t);const i=s[r];let o=0;return t.IsFamily()&&(o=i.GetObjectClass().GetFamilyBehaviorOffset(t.GetFamilyIndex())),this._func.apply(i.GetBehaviorInstances()[this._behaviorIndex+o].GetSdkInstance(),e)}ExpBehavior_InstExpr(e,...t){const s=this._objectClass,n=s.GetInstances(),r=n.length;if(0===r||"number"!=typeof e)return this._returnsString?"":0;const i=WrapIndex(e,r);this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(s);const o=n[i];let a=0;return s.IsFamily()&&(a=o.GetObjectClass().GetFamilyBehaviorOffset(s.GetFamilyIndex())),this._func.apply(o.GetBehaviorInstances()[this._behaviorIndex+a].GetSdkInstance(),t)}}class EventVarExpNode extends C3.ExpNode{constructor(e,t){super(e),this._eventVar=null,this._eventVarSid=t[1]}_PostInit(){this._eventVar=this._runtime.GetEventSheetManager().GetEventVariableBySID(this._eventVarSid)}GetVar(){return this._eventVar}}
}

// events/parameter.js
{
const C3=self.C3,assert=self.assert;function GetExpressionFunc(t){const e=self.C3_ExpressionFuncs[t];if(!e)throw new Error("invalid expression number");return e}C3.Parameter=class extends C3.DefendedBase{constructor(t,e,s){super(),this._owner=t,this._index=s,this._type=e,this.Get=null,this._variesPerInstance=!1,this._isConstant=!1}static Create(t,e,s){const r=e[0],n=[ExpressionParameter,StringExpressionParameter,FileParameter,ComboParameter,ObjectParameter,LayerExpressionParameter,LayoutParameter,ExpressionParameter,ComboParameter,ComboParameter,InstVarParameter,EventVarParameter,FileParameter,VariadicParameter,StringExpressionParameter,TimelineParameter,BooleanParameter,FunctionParameter,EaseParameter,TilemapBrushParameter,TemplateExpressionParameter,FlowchartParameter];return C3.New(n[r],t,r,s,e)}_PostInit(){}SetVariesPerInstance(){this._variesPerInstance=!0}_MaybeVaryFor(t){this._variesPerInstance||t&&(t.GetPlugin().IsSingleGlobal()||(this._variesPerInstance=!0))}VariesPerInstance(){return this._variesPerInstance}GetIndex(){return this._index}GetRuntime(){return this._owner.GetRuntime()}GetEventBlock(){return this._owner.GetEventBlock()}IsConstant(){return this._isConstant}IsObjectParameter(){return 4===this._type}};class ExpressionParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._solIndex=0;const n=r[1];this._expressionNumber=n[0],this._numberedNodes=[],this._expressionFunc=null;for(let t=1,e=n.length;t<e;++t)this._numberedNodes.push(C3.ExpNode.CreateNode(this,n[t]));this._numberedNodes.length?this.Get=this.GetExpression:(this.Get=GetExpressionFunc(this._expressionNumber),this._isConstant=!0)}_GetNode(t){if(t<0||t>=this._numberedNodes.length)throw new RangeError("invalid numbered node");return this._numberedNodes[t]}_PostInit(){for(const t of this._numberedNodes)t._PostInit();const t=GetExpressionFunc(this._expressionNumber);this._numberedNodes.length?this._expressionFunc=t(this):this._expressionFunc=t}GetSolIndex(){return this._solIndex}GetExpression(t){return this._solIndex=t,this._expressionFunc()}}class StringExpressionParameter extends ExpressionParameter{constructor(t,e,s,r){super(t,e,s,r),this.Get=this.GetStringExpression,14===e&&(this.GetEventBlock().SetAllSolModifiers(),this._owner instanceof C3.Action&&this.GetEventBlock().SetSolWriterAfterCnds())}GetStringExpression(t){this._solIndex=t;const e=this._expressionFunc();return"string"==typeof e?e:""}_GetFastTriggerValue(){return GetExpressionFunc(this._expressionNumber)()}}class LayerExpressionParameter extends ExpressionParameter{constructor(t,e,s,r){super(t,e,s,r),t.GetImplementationSdkVersion()>=2?this.Get=this.GetILayer:this.Get=this.GetLayer,this._isConstant=!1}GetLayer(t){this._solIndex=t;const e=this._expressionFunc();return this.GetRuntime().GetCurrentLayout().GetLayer(e)}GetILayer(t){const e=this.GetLayer(t);return e?e.GetILayer():null}}class ComboParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._combo=r[1],this.Get=this.GetCombo,this._isConstant=!0}GetCombo(){return this._combo}}class BooleanParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._bool=r[1],this.Get=this.GetBoolean,this._isConstant=!0}GetBoolean(){return this._bool}}class ObjectParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._objectClass=this.GetRuntime().GetObjectClassByIndex(r[1]),t.GetImplementationSdkVersion()>=2?this.Get=this.GetIObjectClass:this.Get=this.GetObjectClass;const n=this.GetEventBlock();n._AddSolModifier(this._objectClass),this._owner instanceof C3.Action?n.SetSolWriterAfterCnds():n.GetParent()&&n.GetParent().SetSolWriterAfterCnds(),this._isConstant=!0}GetObjectClass(){return this._objectClass}GetIObjectClass(){return this._objectClass?this._objectClass.GetIObjectClass():null}}class LayoutParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._layout=this.GetRuntime().GetLayoutManager().GetLayoutByName(r[1]),t.GetImplementationSdkVersion()>=2?this.Get=this.GetILayout:this.Get=this.GetLayout,this._isConstant=!0}GetLayout(){return this._layout}GetILayout(){return this._layout?this._layout.GetILayout():null}}class TimelineParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._timeline=this.GetRuntime().GetTimelineManager().GetTimelineByName(r[1]),t.GetImplementationSdkVersion()>=2?this.Get=this.GetITimelineState:this.Get=this.GetTimeline,this._isConstant=!0}GetTimeline(){return this._timeline}GetITimelineState(){return this._timeline?this._timeline.GetITimelineState():null}}class FileParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._fileInfo=r[1],this.Get=this.GetFile,this._isConstant=!0}GetFile(){return this._fileInfo}}class InstVarParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._instVarIndex=r[1];const n=this._owner.GetObjectClass();this._owner instanceof C3.Condition&&this._owner.IsStatic()?(this.Get=this.GetInstanceVariable,this._isConstant=!0):n&&n.IsFamily()?(this.Get=this.GetFamilyInstanceVariable,this.SetVariesPerInstance()):(this.Get=this.GetInstanceVariable,this._isConstant=!0)}GetInstanceVariable(){return this._instVarIndex}GetFamilyInstanceVariable(t){t=t||0;const e=this._owner.GetObjectClass(),s=e.GetCurrentSol(),r=s.GetInstances();let n=null;if(r.length)n=r[t%r.length].GetObjectClass();else if(s.HasAnyElseInstances()){const e=s.GetElseInstances();n=e[t%e.length].GetObjectClass()}else{if(!(e.GetInstanceCount()>0))return 0;{const s=e.GetInstances();n=s[t%s.length].GetObjectClass()}}return this._instVarIndex+n.GetFamilyInstanceVariableOffset(e.GetFamilyIndex())}}class EventVarParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._eventVarSid=r[1],this._eventVar=null,t.GetImplementationSdkVersion()>=2?this.Get=this.GetIEventVariable:this.Get=this.GetEventVariable,this._isConstant=!0}_PostInit(){this._eventVar=this.GetRuntime().GetEventSheetManager().GetEventVariableBySID(this._eventVarSid)}GetEventVariable(){return this._eventVar}GetIEventVariable(){return null}}class FunctionParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._functionBlockName=r[1],this._functionBlock=null,t.GetImplementationSdkVersion()>=2?this.Get=this.GetIFunction:this.Get=this.GetFunction,this._isConstant=!0}_PostInit(){this._functionBlock=this.GetRuntime().GetEventSheetManager().GetFunctionBlockByName(this._functionBlockName),this._functionBlockName=null}GetFunction(){return this._functionBlock}GetIFunction(){return null}}class VariadicParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._subParams=[],this._variadicRet=[],this._isConstant=!0;for(let t=1,e=r.length;t<e;++t){const e=C3.Parameter.Create(this._owner,r[t],0);this._subParams.push(e),this._variadicRet.push(0),e.IsConstant()||(this._isConstant=!1)}this.Get=this.GetVariadic}_PostInit(){for(const t of this._subParams)t._PostInit()}GetVariadic(){const t=this._subParams,e=this._variadicRet;for(let s=0,r=t.length;s<r;++s)e[s]=t[s].Get(0);return e}}class EaseParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._easeIndex=r[1],this.Get=this.GetEase,this._isConstant=!0}GetEase(){return this._easeIndex}}class TilemapBrushParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._brushIndex=r[1],this.Get=this.GetTilemapBrush,this._isConstant=!0}GetTilemapBrush(){return this._brushIndex}}class TemplateExpressionParameter extends ExpressionParameter{constructor(t,e,s,r){super(t,e,s,r),this.Get=this.GetTemplateName,this._isConstant=!1}GetTemplateName(){return this._expressionFunc()}}class FlowchartParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._flowchartDataItem=this.GetRuntime().GetFlowchartManager().GetFlowchartDataItemByName(r[1]),this.Get=this.GetFlowchartName,this._isConstant=!0}GetFlowchartName(){return this._flowchartDataItem.GetName()}}
}

// events/condition.js
{
const C3=self.C3,assert=self.assert;function EvalParams(t,e){for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(0)}const EMPTY_PARAMS_ARRAY=[],noop=function(){};C3.Condition=class extends C3.DefendedBase{constructor(t,e,s){if(super(),this._eventBlock=t,this._runtime=t.GetRuntime(),this._index=s,this._func=this._runtime.GetObjectReference(e[1]),this._isTrigger=e[3]>0,this._isFastTrigger=2===e[3],this._isLooping=!!e[4],this._isInverted=!!e[5],this._isStatic=!!e[6],this._sid=e[7],this._isInOrBlock=this._eventBlock.IsOrBlock(),this._objectClass=null,this._behaviorType=null,this._behaviorIndex=-1,this._systemPlugin=null,this.Run=noop,this.DebugRun=noop,this._parameters=[],this._results=[],this._anyParamVariesPerInstance=!1,this._savedData=null,this._unsavedData=null,this._debugData=this._runtime.IsDebug()?{isBreakpoint:e[8][0],canDebug:e[8][1]}:null,-1===e[0]?this._systemPlugin=this._runtime.GetSystemPlugin():(this._objectClass=this._runtime.GetObjectClassByIndex(e[0]),e[2]&&(this._behaviorType=this._objectClass.GetBehaviorTypeByName(e[2]),this._behaviorIndex=this._objectClass.GetBehaviorIndexByName(e[2])),this._eventBlock.GetParent()&&this._eventBlock.GetParent().SetSolWriterAfterCnds()),10===e.length){let t=e[9];for(let e of t)this._parameters.push(C3.Parameter.Create(this,e,this._parameters.length)),this._results.push(0)}0===this._parameters.length&&(this._parameters=EMPTY_PARAMS_ARRAY,this._results=EMPTY_PARAMS_ARRAY),this._eventBlock.GetEventSheetManager()._RegisterCondition(this)}static Create(t,e,s){return C3.New(C3.Condition,t,e,s)}_PostInit(){for(const t of this._parameters)t._PostInit(),t.VariesPerInstance()&&(this._anyParamVariesPerInstance=!0);this._isFastTrigger?(this.Run=this._RunFastTrigger,this.DebugRun=this._DebugRunFastTrigger):this._systemPlugin?(this._SetSystemRunMethod(),this.DebugRun=this._DebugRunSystem):this._objectClass.GetPlugin().IsSingleGlobal()?(this._SetSingleGlobalRunMethod(),this.DebugRun=this._DebugRunSingleGlobal):this._isStatic?(this.Run=this._RunStatic,this.DebugRun=this._DebugRunStatic):(this.Run=this._RunObject,this.DebugRun=this._DebugRunObject)}_SetSystemRunMethod(){const t=this._systemPlugin,e=this._systemPlugin;this._SetRunMethodForBoundFunc(t,e,this._RunSystem)}_SetSingleGlobalRunMethod(){const t=this._objectClass.GetPlugin(),e=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();this._SetRunMethodForBoundFunc(t,e,this._RunSingleGlobal)}_SetRunMethodForBoundFunc(t,e,s){const n=this._func,i=this._isInverted,r=this._parameters;if(0===r.length){const s=t._GetBoundACEMethod(n,e);this.Run=i?function(){return C3.xor(s(),i)}:s}else if(1===r.length){const s=r[0];if(!i&&s.IsConstant())this.Run=t._GetBoundACEMethod_1param(n,e,s.Get(0));else{const r=t._GetBoundACEMethod(n,e);this.Run=function(){return C3.xor(r(s.Get(0)),i)}}}else if(2===r.length){const s=r[0],a=r[1];if(!i&&s.IsConstant()&&a.IsConstant())this.Run=t._GetBoundACEMethod_2params(n,e,s.Get(0),a.Get(0));else{const r=t._GetBoundACEMethod(n,e);this.Run=function(){return C3.xor(r(s.Get(0),a.Get(0)),i)}}}else if(3===r.length){const s=r[0],a=r[1],h=r[2];if(!i&&s.IsConstant()&&a.IsConstant()&&h.IsConstant())this.Run=t._GetBoundACEMethod_3params(n,e,s.Get(0),a.Get(0),h.Get(0));else{const r=t._GetBoundACEMethod(n,e);this.Run=function(){return C3.xor(r(s.Get(0),a.Get(0),h.Get(0)),i)}}}else this.Run=s}GetSID(){return this._sid}_GetFunc(){return this._func}GetObjectClass(){return this._objectClass}GetBehaviorType(){return this._behaviorType}GetImplementationAddon(){return this._behaviorType?this._behaviorType.GetBehavior():this._objectClass?this._objectClass.GetPlugin():null}GetImplementationSdkVersion(){const t=this.GetImplementationAddon();return t?t.GetSdkVersion():1}GetEventBlock(){return this._eventBlock}GetRuntime(){return this._runtime}GetIndex(){return this._index}GetDebugIndex(){return this.GetIndex()}IsTrigger(){return this._isTrigger}IsFastTrigger(){return this._isFastTrigger}IsInverted(){return this._isInverted}IsLooping(){return this._isLooping}IsStatic(){return this._isStatic}IsBreakpoint(){return this._debugData.isBreakpoint}IsSystemCondition(){return!!this._systemPlugin}IsSystemOrSingleGlobalCondition(){return this.IsSystemCondition()||this._objectClass.GetPlugin().IsSingleGlobal()}GetFirstObjectParameterObjectClass(){for(const t of this._parameters)if(t.IsObjectParameter())return t.GetObjectClass();return null}_SetBreakpoint(t){this._debugData.isBreakpoint=!!t,this._eventBlock._UpdateCanRunFastRecursive()}_DebugReturnsGenerator(){return this._debugData.canDebug}DebugCanRunFast(){return!this.IsBreakpoint()&&!this._runtime.DebugBreakNext()&&!this._DebugReturnsGenerator()}GetSavedDataMap(){return this._savedData||(this._savedData=new Map),this._savedData}GetUnsavedDataMap(){return this._unsavedData||(this._unsavedData=new Map),this._unsavedData}_RunSystem(){const t=this._results;return EvalParams(this._parameters,t),C3.xor(this._func.apply(this._systemPlugin,t),this._isInverted)}*_DebugRunSystem(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);let e=this._func.apply(this._systemPlugin,t);return C3.IsIterator(e)&&(e=yield*e),C3.xor(e,this._isInverted)}return this.Run()}_RunSingleGlobal(){const t=this._results;EvalParams(this._parameters,t);const e=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();return C3.xor(this._func.apply(e,t),this._isInverted)}*_DebugRunSingleGlobal(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);const e=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();let s=this._func.apply(e,t);return C3.IsIterator(s)&&(s=yield*s),C3.xor(s,this._isInverted)}return this.Run()}_RunFastTrigger(){return!0}*_DebugRunFastTrigger(){return(this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),!0}_GetStaticConditionThis(){return this._behaviorType?this._behaviorType.GetBehavior().GetSdkVersion()>=2?this._behaviorType.GetIBehaviorType():this._behaviorType:this._objectClass.GetPlugin().GetSdkVersion()>=2?this._objectClass.GetIObjectClass():this._objectClass}_RunStatic(){const t=this._results;EvalParams(this._parameters,t);const e=this._func.apply(this._GetStaticConditionThis(),t);return this._objectClass.ApplySolToContainer(),e}*_DebugRunStatic(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);let e=this._func.apply(this._GetStaticConditionThis(),t);return C3.IsIterator(e)&&(e=yield*e),this._objectClass.ApplySolToContainer(),e}return this.Run()}_RunObject(){const t=this._parameters,e=this._results,s=this._objectClass.GetCurrentSol();for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()||(e[s]=n.Get(0))}return s.IsSelectAll()?this._RunObject_FirstFilter(s):this._RunObject_NextFilter(s)}*_DebugRunObject(){return(this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._RunObject()}_EvaluateVaryingParameters(t){const e=this._parameters,s=this._results;for(let n=0,i=e.length;n<i;++n){const i=e[n];i.VariesPerInstance()&&(s[n]=i.Get(t))}}_RunObject_FirstFilter(t){const e=this._objectClass,s=e.IsFamily(),n=e.GetFamilyIndex(),i=this._behaviorIndex,r=i>=0,a=e.GetInstances(),h=this._anyParamVariesPerInstance,o=this._results,l=this._func,u=this._isInverted,_=this._isInOrBlock&&!this._isTrigger;t.ClearArrays();for(let e=0,c=a.length;e<c;++e){const c=a[e];let g;if(h&&this._EvaluateVaryingParameters(e),r){const t=s?c.GetObjectClass().GetFamilyBehaviorOffset(n):0;g=l.apply(c.GetBehaviorInstances()[i+t].GetSdkInstance(),o)}else g=l.apply(c.GetSdkInstance(),o);C3.xor(g,u)?t._PushInstance(c):_&&t._PushElseInstance(c)}return e.FinishCondition(!0),t._SetSelectAll(!1),e.ApplySolToContainer(),t.HasAnyInstances()}_RunObject_NextFilter(t){const e=this._objectClass,s=e.IsFamily(),n=e.GetFamilyIndex(),i=e.IsInContainer(),r=this._behaviorIndex,a=r>=0,h=this._anyParamVariesPerInstance,o=this._results,l=this._func,u=this._isInverted,_=this._isInOrBlock&&!this._isTrigger,c=t._GetOwnInstances(),g=t._GetOwnElseInstances(),d=_&&!this._eventBlock.IsFirstConditionOfType(this),I=d?g:c;let G=0,b=!1;for(let t=0,e=I.length;t<e;++t){const e=I[t];let m;if(h&&this._EvaluateVaryingParameters(t),a){const t=s?e.GetObjectClass().GetFamilyBehaviorOffset(n):0;m=l.apply(e.GetBehaviorInstances()[r+t].GetSdkInstance(),o)}else m=l.apply(e.GetSdkInstance(),o);C3.xor(m,u)?(b=!0,d?(c.push(e),i&&e._PushSiblingsToSolInstances()):(I[G]=e,i&&e._SetSiblingsToSolInstancesIndex(G),++G)):d?(I[G]=e,i&&e._SetSiblingsToSolElseInstancesIndex(G),++G):_&&(g.push(e),i&&e._PushSiblingsToSolElseInstances())}C3.truncateArray(I,G),i&&e._TruncateContainerSols(d,G);const m=b;return d&&!b&&(b=this._OrBlockCheckInstances(c)),e.FinishCondition(m||_),_?b:t.HasAnyInstances()}_OrBlockCheckInstances(t){const e=this._objectClass,s=e.IsFamily(),n=e.GetFamilyIndex(),i=this._anyParamVariesPerInstance,r=this._behaviorIndex,a=r>=0,h=this._results,o=this._func,l=this._isInverted;for(let e=0,u=t.length;e<u;++e){const u=t[e];let _;if(i&&this._EvaluateVaryingParameters(e),a){const t=s?u.GetObjectClass().GetFamilyBehaviorOffset(n):0;_=o.apply(u.GetBehaviorInstances()[r+t].GetSdkInstance(),h)}else _=o.apply(u.GetSdkInstance(),h);if(C3.xor(_,l))return!0}return!1}ReevaluateParameter(t,e){return this._parameters[t].Get(e)}GetFastTriggerValue(){const t=this._parameters;if(!t.length)throw new Error("no parameters");return t[0]._GetFastTriggerValue()}_SaveToJson(){if(!this._savedData||!this._savedData.size)return null;const t={};for(const[e,s]of this._savedData.entries()){let n=s;"collmemory"===e&&(n=[...s.entries()].map((t=>[t[0].GetUID(),t[1].GetUID(),t[2]]))),t[e]=n}return{"ex":t}}_LoadFromJson(t){if(this._savedData&&(this._savedData.clear(),this._savedData=null),!t)return;const e=this._runtime,s=t["ex"];if(s){const t=this.GetSavedDataMap();t.clear();for(const[n,i]of Object.entries(s)){let s=i;"collmemory"===n&&(s=C3.New(C3.PairMap,i.map((t=>[e.GetInstanceByUID(t[0]),e.GetInstanceByUID(t[1]),t[2]])).filter((t=>t[0]&&t[1])))),t.set(n,s)}}}};
}

// events/action.js
{
const C3=self.C3,assert=self.assert;function EvalParams(t,e){for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(0)}const EMPTY_PARAMS_ARRAY=[],noop=function(){},noopGenerator=function*(){},FLAG_CANPICKANYOBJECTCLASS=1,FLAG_COPYPICKED=2,FLAG_CUSTOM_ACE=4,FLAG_IS_ASYNC=8,FLAG_CAN_BAIL_OUT=16;C3.Action=class extends C3.DefendedBase{constructor(t,e,s){super(),this._eventBlock=t;const n=t.GetRuntime();this._runtime=n,this._index=s,this._sid=e.length>=4?e[3]:-1,this._actionType=e.length>=5?255&e[4]:0,this._flags=e.length>=5?e[4]>>8:0,this._func=null,this._objectClass=null,this._behaviorType=null,this._behaviorIndex=-1,this._systemPlugin=null,this._callFunctionName="",this._callCustomAceObjectClass=null,this._callEventBlock=null,this.Run=noop,this.DebugRun=noop,this._parameters=[],this._results=[],this._anyParamVariesPerInstance=!1,this._savedData=null,this._unsavedData=null;const i=-3===e[0],a=i?e[2]:e[5];if(this._debugData=n.IsDebug()||i?{isBreakpoint:a[0],canDebug:a[1],index:a[2]}:null,-1===e[0])this._systemPlugin=n.GetSystemPlugin(),this._func=n.GetObjectReference(e[1]);else if(-2===e[0])this._callFunctionName=e[1];else if(i){const t=n.GetObjectReference(e[1]);this._func=t,this.Run=this.RunUserScript,this.DebugRun=this.DebugRunUserScript,this._flags|=8}else this._objectClass=n.GetObjectClassByIndex(e[0]),4&this._flags?(this._callFunctionName=e[1],this._callCustomAceObjectClass=n.GetObjectClassByIndex(e[2])):(e[2]&&(this._behaviorType=this._objectClass.GetBehaviorTypeByName(e[2]),this._behaviorIndex=this._objectClass.GetBehaviorIndexByName(e[2])),this._func=n.GetObjectReference(e[1]));if(7===e.length){const t=e[6];for(const e of t)this._parameters.push(C3.Parameter.Create(this,e,this._parameters.length)),this._results.push(0)}0===this._parameters.length&&(this._parameters=EMPTY_PARAMS_ARRAY,this._results=EMPTY_PARAMS_ARRAY),this.CanPickAnyObjectClass()&&(this._eventBlock.SetAllSolModifiers(),this._eventBlock.SetSolWriterAfterCnds()),this._eventBlock.GetEventSheetManager()._RegisterAction(this)}static Create(t,e,s){return C3.New(C3.Action,t,e,s)}_PostInit(){for(const t of this._parameters)t._PostInit(),t.VariesPerInstance()&&(this._anyParamVariesPerInstance=!0);if(this._systemPlugin)this._SetSystemRunMethod(),this.DebugRun=this._DebugRunSystem;else if(this._callFunctionName)4&this._flags?this._SetCallCustomActionRunMethod():this._SetCallFunctionRunMethod(),this._callFunctionName="",this._callCustomAceObjectClass=null;else if(this.Run===this.RunUserScript){const t=this._func,e=this._runtime.GetEventSheetManager()._GetLocalVariablesScriptInterface(this._eventBlock);this._func=t.bind(null,this._runtime.GetIRuntime(),e)}else this._behaviorType?this.IsAsync()?(this.Run=this._RunBehavior_Async,this.DebugRun=this._DebugRunBehavior_Async):(this.Run=this._RunBehavior,this.DebugRun=this._DebugRunBehavior):this._objectClass.GetPlugin().IsSingleGlobal()?(this._SetSingleGlobalRunMethod(),this.DebugRun=this._DebugRunSingleGlobal):this.IsStatic()?(this.Run=this._RunObject_Static,this.DebugRun=this._DebugRunObject_Static):this.IsAsync()?(this.Run=this._RunObject_Async,this.DebugRun=this._DebugRunObject_Async):this.CallBeforeAfterHooks()?(this.Run=this._RunObject_BeforeAfterHooks,this.DebugRun=this._DebugRunObject_BeforeAfterHooks):this._parameters.length?this._parameters.every((t=>t.VariesPerInstance()))?(this.Run=this._RunObject_AllParamsVary,this.DebugRun=this._DebugRunObject_AllParamsVary):this._anyParamVariesPerInstance?(this.Run=this._RunObject_SomeParamsVary,this.DebugRun=this._DebugRunObject_SomeParamsVary):this._parameters.every((t=>t.IsConstant()))?(EvalParams(this._parameters,this._results),this.Run=this._RunObject_ParamsConst,this.DebugRun=this._DebugRunObject_ParamsConst):(this.Run=this._RunObject_ParamsDontVary,this.DebugRun=this._DebugRunObject_ParamsDontVary):(this.Run=this._RunObject_ParamsConst,this.DebugRun=this._DebugRunObject_ParamsConst)}_SetSystemRunMethod(){const t=this._systemPlugin,e=this._systemPlugin;this._SetRunMethodForBoundFunc(t,e,this._RunSystem)}_SetSingleGlobalRunMethod(){const t=this._objectClass.GetPlugin(),e=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();this._SetRunMethodForBoundFunc(t,e,this._RunSingleGlobal)}_SetCallFunctionRunMethod(){const t=this._eventBlock.GetEventSheetManager(),e=t.GetFunctionBlockByName(this._callFunctionName);if(e.IsEnabled()){const s=!!(2&this._flags);this._callEventBlock=e.GetEventBlock();let n=[...new Set([...this._eventBlock.GetSolModifiersIncludingParents(),...this._callEventBlock.GetSolModifiersIncludingParents()])];n=t._DeduplicateSolModifierList(n);const i=!e.IsCopyPicked()&&this._HasCopyPickedParent()?{pushCleanSolDynamic:!0}:null;if(this.Run=C3.EventBlock.prototype.RunAsFunctionCall.bind(this._callEventBlock,n,this._parameters,s,i),this._runtime.IsDebug()){const t=this;this.DebugRun=function*(){(t.IsBreakpoint()||t._runtime.DebugBreakNext())&&(yield t);return yield*t._callEventBlock.DebugRunAsFunctionCall(n,t._parameters,s,i)}}else this.DebugRun=noopGenerator}else this.Run=noop,this.DebugRun=noopGenerator}_SetCallCustomActionRunMethod(){const t=this._eventBlock.GetEventSheetManager(),e=t.GetCustomActionBlockByName(this._callCustomAceObjectClass,this._callFunctionName);if(e.IsEnabled()){const s=!!(2&this._flags);this._callEventBlock=e.GetEventBlock();let n=[...new Set([...this._eventBlock.GetSolModifiersIncludingParents(),...this._callEventBlock.GetSolModifiersIncludingParents(),this._objectClass,e.GetObjectClass()])];n=t._DeduplicateSolModifierList(n);const i=!this._objectClass.IsFamily()&&!e.GetObjectClass().IsFamily(),a=!this._objectClass.IsFamily()&&e.GetObjectClass().IsFamily(),r=this._objectClass.IsFamily();let o=null;if(!e.IsCopyPicked()&&this._HasCopyPickedParent()&&(o=o||{},o.pushCleanSolDynamic=!0),!a&&s||(o=o||{},o.copyFromObjectClass=this._objectClass,o.copyToObjectClass=e.GetObjectClass()),i||a||r&&!e.HasCustomACEOverrides()?this.Run=C3.EventBlock.prototype.RunAsFunctionCall.bind(this._callEventBlock,n,this._parameters,s,o):r&&(this.Run=C3.FunctionBlock.prototype.RunAsFamilyCustomActionWithOverrides.bind(e,n,this._parameters)),this._runtime.IsDebug()){const t=this;i||a||r&&!e.HasCustomACEOverrides()?this.DebugRun=function*(){(t.IsBreakpoint()||t._runtime.DebugBreakNext())&&(yield t);return yield*t._callEventBlock.DebugRunAsFunctionCall(n,t._parameters,s,o)}:r&&(this.DebugRun=function*(){(t.IsBreakpoint()||t._runtime.DebugBreakNext())&&(yield t);return yield*e.DebugRunAsFamilyCustomActionWithOverrides(n,t._parameters)})}else this.DebugRun=noopGenerator}else this.Run=noop,this.DebugRun=noopGenerator}_SetRunMethodForBoundFunc(t,e,s){const n=this._func,i=this._parameters;if(0===i.length)this.Run=t._GetBoundACEMethod(n,e);else if(1===i.length){const s=i[0];if(s.IsConstant())this.Run=t._GetBoundACEMethod_1param(n,e,s.Get(0));else{const i=t._GetBoundACEMethod(n,e);this.Run=function(){return i(s.Get(0))}}}else if(2===i.length){const s=i[0],a=i[1];if(s.IsConstant()&&a.IsConstant())this.Run=t._GetBoundACEMethod_2params(n,e,s.Get(0),a.Get(0));else{const i=t._GetBoundACEMethod(n,e);this.Run=function(){return i(s.Get(0),a.Get(0))}}}else if(3===i.length){const s=i[0],a=i[1],r=i[2];if(s.IsConstant()&&a.IsConstant()&&r.IsConstant())this.Run=t._GetBoundACEMethod_3params(n,e,s.Get(0),a.Get(0),r.Get(0));else{const i=t._GetBoundACEMethod(n,e);this.Run=function(){return i(s.Get(0),a.Get(0),r.Get(0))}}}else this.Run=s}GetSID(){return this._sid}IsAsync(){return!!(8&this._flags)}CanBailOut(){return!!(16&this._flags)}CallBeforeAfterHooks(){return 1===this._actionType}IsStatic(){return 2===this._actionType}CanPickAnyObjectClass(){return!!(1&this._flags)}HasReturnType(){return this.IsAsync()||this.CanBailOut()}GetObjectClass(){return this._objectClass}GetImplementationAddon(){return this._behaviorType?this._behaviorType.GetBehavior():this._objectClass?this._objectClass.GetPlugin():null}GetImplementationSdkVersion(){const t=this.GetImplementationAddon();return t?t.GetSdkVersion():1}GetEventBlock(){return this._eventBlock}_HasCopyPickedParent(){let t=this._eventBlock;do{if(t instanceof C3.FunctionBlock&&t.IsCopyPicked())return!0;t=t.GetScopeParent()}while(t);return!1}GetRuntime(){return this._runtime}GetIndex(){return this._index}GetDebugIndex(){return this._debugData.index}IsBreakpoint(){return this._debugData.isBreakpoint}_SetBreakpoint(t){this._debugData.isBreakpoint=!!t,this._eventBlock._UpdateCanRunFastRecursive()}_DebugReturnsGenerator(){return this._debugData.canDebug}DebugCanRunFast(){return!this.IsBreakpoint()&&!this._runtime.DebugBreakNext()&&!this._DebugReturnsGenerator()}GetSavedDataMap(){return this._savedData||(this._savedData=new Map),this._savedData}GetUnsavedDataMap(){return this._unsavedData||(this._unsavedData=new Map),this._unsavedData}_RunSystem(){const t=this._results;return EvalParams(this._parameters,t),this._func.apply(this._systemPlugin,t)}*_DebugRunSystem(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);return yield*this._func.apply(this._systemPlugin,t)}return this.Run()}_RunSingleGlobal(){const t=this._results;return EvalParams(this._parameters,t),this._func.apply(this._objectClass.GetSingleGlobalInstance().GetSdkInstance(),t)}*_DebugRunSingleGlobal(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);return yield*this._func.apply(this._objectClass.GetSingleGlobalInstance().GetSdkInstance(),t)}return this.Run()}_RunObject_ParamsConst(){const t=this._results,e=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=e.length;s<n;++s)this._func.apply(e[s].GetSdkInstance(),t)}*_DebugRunObject_ParamsConst(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results,e=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=e.length;s<n;++s)yield*this._func.apply(e[s].GetSdkInstance(),t)}else this._RunObject_ParamsConst()}_RunObject_ParamsDontVary(){const t=this._results;EvalParams(this._parameters,t);const e=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=e.length;s<n;++s)this._func.apply(e[s].GetSdkInstance(),t)}*_DebugRunObject_ParamsDontVary(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);const e=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=e.length;s<n;++s)yield*this._func.apply(e[s].GetSdkInstance(),t)}else this._RunObject_ParamsDontVary()}_RunObject_AllParamsVary(){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances();for(let i=0,a=n.length;i<a;++i){const a=n[i];for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(i);s.apply(a.GetSdkInstance(),e)}}*_DebugRunObject_AllParamsVary(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances();for(let i=0,a=n.length;i<a;++i){const a=n[i];for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(i);yield*s.apply(a.GetSdkInstance(),e)}}else this._RunObject_AllParamsVary()}_RunObject_SomeParamsVary(){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()||(e[s]=n.Get(0))}for(let i=0,a=n.length;i<a;++i){const a=n[i];for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()&&(e[s]=n.Get(i))}s.apply(a.GetSdkInstance(),e)}}*_DebugRunObject_SomeParamsVary(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()||(e[s]=n.Get(0))}for(let i=0,a=n.length;i<a;++i){const a=n[i];for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()&&(e[s]=n.Get(i))}yield*s.apply(a.GetSdkInstance(),e)}}else this._RunObject_SomeParamsVary()}_RunObject_BeforeAfterHooks(){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass,i=n.GetSdkType(),a=n.GetCurrentSol().GetInstances();i.BeforeRunAction(s);for(let n=0,i=a.length;n<i;++n){const i=a[n];for(let s=0,i=t.length;s<i;++s)e[s]=t[s].Get(n);s.apply(i.GetSdkInstance(),e)}i.AfterRunAction(s)}*_DebugRunObject_BeforeAfterHooks(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass,i=n.GetSdkType(),a=n.GetCurrentSol().GetInstances();i.BeforeRunAction(s);for(let n=0,i=a.length;n<i;++n){const i=a[n];for(let s=0,i=t.length;s<i;++s)e[s]=t[s].Get(n);yield*s.apply(i.GetSdkInstance(),e)}i.AfterRunAction(s)}else this._RunObject_BeforeAfterHooks()}_GetStaticActionThis(){return this._behaviorType?this._behaviorType.GetBehavior().GetSdkVersion()>=2?this._behaviorType.GetIBehaviorType():this._behaviorType:this._objectClass.GetPlugin().GetSdkVersion()>=2?this._objectClass.GetIObjectClass():this._objectClass}_RunObject_Static(){const t=this._results;return EvalParams(this._parameters,t),this._func.apply(this._GetStaticActionThis(),t)}*_DebugRunObject_Static(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);let e=this._func.apply(this._GetStaticActionThis(),t);return C3.IsIterator(e)&&(e=yield*e),e}return this._RunObject_Static()}_RunBehavior(){const t=this._objectClass,e=t.IsFamily(),s=t.GetFamilyIndex(),n=this._parameters,i=this._anyParamVariesPerInstance,a=this._results,r=this._func,o=this._behaviorIndex,l=t.GetCurrentSol().GetInstances();for(let t=0,e=n.length;t<e;++t){const e=n[t];e.VariesPerInstance()||(a[t]=e.Get(0))}for(let t=0,h=l.length;t<h;++t){const h=l[t];if(i)for(let e=0,s=n.length;e<s;++e){const s=n[e];s.VariesPerInstance()&&(a[e]=s.Get(t))}const u=e?h.GetObjectClass().GetFamilyBehaviorOffset(s):0;r.apply(h.GetBehaviorInstances()[o+u].GetSdkInstance(),a)}}*_DebugRunBehavior(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._objectClass,e=t.IsFamily(),s=t.GetFamilyIndex(),n=this._parameters,i=this._anyParamVariesPerInstance,a=this._results,r=this._func,o=this._behaviorIndex,l=t.GetCurrentSol().GetInstances();for(let t=0,e=n.length;t<e;++t){const e=n[t];e.VariesPerInstance()||(a[t]=e.Get(0))}for(let t=0,h=l.length;t<h;++t){const h=l[t];if(i)for(let e=0,s=n.length;e<s;++e){const s=n[e];s.VariesPerInstance()&&(a[e]=s.Get(t))}const u=e?h.GetObjectClass().GetFamilyBehaviorOffset(s):0;yield*r.apply(h.GetBehaviorInstances()[o+u].GetSdkInstance(),a)}}else this._RunBehavior()}_RunObject_Async(){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances(),i=[];for(let a=0,r=n.length;a<r;++a){const r=n[a];for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(a);i.push(s.apply(r.GetSdkInstance(),e))}return Promise.all(i)}*_DebugRunObject_Async(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances(),i=[];for(let a=0,r=n.length;a<r;++a){const r=n[a];for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(a);i.push(yield*s.apply(r.GetSdkInstance(),e))}return Promise.all(i)}return this._RunObject_Async()}_RunBehavior_Async(){const t=this._objectClass,e=t.IsFamily(),s=t.GetFamilyIndex(),n=this._parameters,i=this._results,a=this._func,r=this._behaviorIndex,o=t.GetCurrentSol().GetInstances(),l=[];for(let t=0,h=o.length;t<h;++t){const h=o[t];for(let e=0,s=n.length;e<s;++e)i[e]=n[e].Get(t);const u=e?h.GetObjectClass().GetFamilyBehaviorOffset(s):0;l.push(a.apply(h.GetBehaviorInstances()[r+u].GetSdkInstance(),i))}return Promise.all(l)}*_DebugRunBehavior_Async(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._objectClass,e=t.IsFamily(),s=t.GetFamilyIndex(),n=this._parameters,i=this._results,a=this._func,r=this._behaviorIndex,o=t.GetCurrentSol().GetInstances(),l=[];for(let t=0,h=o.length;t<h;++t){const h=o[t];for(let e=0,s=n.length;e<s;++e)i[e]=n[e].Get(t);const u=e?h.GetObjectClass().GetFamilyBehaviorOffset(s):0;l.push(yield*a.apply(h.GetBehaviorInstances()[r+u].GetSdkInstance(),i))}return Promise.all(l)}return this._RunBehavior_Async()}async RunUserScript(){try{await this._func()}catch(t){console.error(`Unhandled exception running script %c${this._eventBlock.GetEventSheet().GetName()}, event ${this._eventBlock.GetDisplayNumber()}, action ${this.GetDebugIndex()+1}:`,"font-size: 1.2em; font-weight: bold;",t),self.C3Debugger&&self.C3Debugger._SetLastErrorScript(this),C3.EventScript.HadUserScriptException()||(console.info("%cTip:%c run this to highlight in Construct the last script that had an error: %cgoToLastErrorScript()","font-weight: bold; text-decoration: underline","","font-weight: bold"),C3.EventScript.SetHadUserScriptException())}}*DebugRunUserScript(){return(this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this.RunUserScript()}_SaveToJson(){return this._savedData&&this._savedData.size?{"ex":C3.ToSuperJSON(this._savedData)}:null}_LoadFromJson(t){if(this._savedData&&(this._savedData.clear(),this._savedData=null),!t)return;const e=t["ex"];e&&(this._savedData=C3.FromSuperJSON(e))}};
}

// events/commonACEs.js
{
const C3=self.C3,tempColor=new C3.Color,AnySDK={},SDKv1={},SDKv2={};let runtime=null;C3.CommonACES_SetRuntime=function(t){runtime=t};const IInstance=self.IInstance,IObjectClass=self.IObjectClass,ILayer=self.ILayer;function GetInst(t){return t instanceof IInstance?runtime._UnwrapScriptInterface(t):t.GetInstance()}function GetWorldInfo(t){return GetInst(t).GetWorldInfo()}function GetInst_SDKv2(t){return runtime._UnwrapScriptInterface(t)}function GetWorldInfo_SDKv2(t){return GetInst_SDKv2(t).GetWorldInfo()}function GetObjectClass(t){return t instanceof IObjectClass?runtime._UnwrapScriptInterface(t):t}function GetLayer(t){return t instanceof ILayer?runtime._UnwrapScriptInterface(t):t}SDKv1.CompareX=function(t,e){return C3.compare(this.GetWorldInfo().GetX(),t,e)},SDKv2.CompareX=function(t,e){return C3.compare(this.x,t,e)},SDKv1.CompareY=function(t,e){return C3.compare(this.GetWorldInfo().GetY(),t,e)},SDKv2.CompareY=function(t,e){return C3.compare(this.y,t,e)},SDKv1.IsOnScreen=function(){return this.GetWorldInfo().IsInViewport2()},SDKv2.IsOnScreen=function(){return this.isOnScreen()},AnySDK.IsOutsideLayout=function(){const t=GetWorldInfo(this),e=t.GetLayout(),n=t.GetBoundingBox();return n.getRight()<0||n.getBottom()<0||n.getLeft()>e.GetWidth()||n.getTop()>e.GetHeight()},AnySDK.PickDistance=function(t,e,n){const o=GetObjectClass(this).GetCurrentSol(),s=o.GetInstances();if(!s.length)return!1;let i=s[0],r=i.GetWorldInfo(),a=i,l=C3.distanceSquared(r.GetX(),r.GetY(),e,n);for(let o=1,c=s.length;o<c;++o){i=s[o],r=i.GetWorldInfo();const c=C3.distanceSquared(r.GetX(),r.GetY(),e,n);(0===t&&c<l||1===t&&c>l)&&(l=c,a=i)}return o.PickOne(a),!0},SDKv1.SetX=function(t){const e=this.GetWorldInfo();e.GetX()!==t&&(e.SetX(t),e.SetBboxChanged())},SDKv2.SetX=function(t){this.x=+t},SDKv1.SetY=function(t){const e=this.GetWorldInfo();e.GetY()!==t&&(e.SetY(t),e.SetBboxChanged())},SDKv2.SetY=function(t){this.y=+t},SDKv1.SetPos=function(t,e){const n=this.GetWorldInfo();n.EqualsXY(t,e)||(n.SetXY(t,e),n.SetBboxChanged())},SDKv2.SetPos=function(t,e){this.setPosition(t,e)},AnySDK.SetPosToObject=function(t,e){if(!(t=GetObjectClass(t)))return;const n=GetInst(this),o=t.GetPairedInstance(n);if(!o)return;const[s,i]=o.GetImagePoint(e),r=n.GetWorldInfo();r.GetX()===s&&r.GetY()===i||(r.SetXY(s,i),r.SetBboxChanged())},AnySDK.MoveForward=function(t){if(0===t)return;const e=GetWorldInfo(this);e.OffsetXY(e.GetCosAngle()*t,e.GetSinAngle()*t),e.SetBboxChanged()},SDKv1.MoveAtAngle=function(t,e){if(0===e)return;const n=this.GetWorldInfo();t=C3.toRadians(t),n.OffsetXY(Math.cos(t)*e,Math.sin(t)*e),n.SetBboxChanged()},SDKv2.MoveAtAngle=function(t,e){0!==e&&(t=C3.toRadians(t),this.offsetPosition(Math.cos(t)*e,Math.sin(t)*e))},SDKv1.GetX=function(){return this.GetWorldInfo().GetX()},SDKv2.GetX=function(){return this.x},SDKv1.GetY=function(){return this.GetWorldInfo().GetY()},SDKv2.GetY=function(){return this.y},AnySDK.GetDt=function(){return runtime.GetDt(GetInst(this))},SDKv1.CompareWidth=function(t,e){return C3.compare(this.GetWorldInfo().GetWidth(),t,e)},SDKv2.CompareWidth=function(t,e){return C3.compare(this.width,t,e)},SDKv1.CompareHeight=function(t,e){return C3.compare(this.GetWorldInfo().GetHeight(),t,e)},SDKv2.CompareHeight=function(t,e){return C3.compare(this.height,t,e)},SDKv1.SetWidth=function(t){const e=this.GetWorldInfo();e.GetWidth()!==t&&(e.SetWidth(t),e.SetBboxChanged())},SDKv2.SetWidth=function(t){this.width=t},SDKv1.SetHeight=function(t){const e=this.GetWorldInfo();e.GetHeight()!==t&&(e.SetHeight(t),e.SetBboxChanged())},SDKv2.SetHeight=function(t){this.height=t},SDKv1.SetSize=function(t,e){const n=GetWorldInfo(this);n.GetWidth()===t&&n.GetHeight()===e||(n.SetSize(t,e),n.SetBboxChanged())},SDKv2.SetSize=function(t,e){this.setSize(t,e)},SDKv1.GetWidth=function(){return this.GetWorldInfo().GetWidth()},SDKv2.GetWidth=function(){return this.width},SDKv1.GetHeight=function(){return this.GetWorldInfo().GetHeight()},SDKv2.GetHeight=function(){return this.height},AnySDK.GetBboxLeft=function(){return GetWorldInfo(this).GetBoundingBox().getLeft()},AnySDK.GetBboxTop=function(){return GetWorldInfo(this).GetBoundingBox().getTop()},AnySDK.GetBboxRight=function(){return GetWorldInfo(this).GetBoundingBox().getRight()},AnySDK.GetBboxBottom=function(){return GetWorldInfo(this).GetBoundingBox().getBottom()},AnySDK.GetBboxMidX=function(){const t=GetWorldInfo(this).GetBoundingBox();return(t.getLeft()+t.getRight())/2},AnySDK.GetBboxMidY=function(){const t=GetWorldInfo(this).GetBoundingBox();return(t.getTop()+t.getBottom())/2},AnySDK.IsAngleWithin=function(t,e){return C3.angleDiff(GetWorldInfo(this).GetAngle(),C3.toRadians(e))<=C3.toRadians(t)},AnySDK.IsAngleClockwiseFrom=function(t){return C3.angleClockwise(GetWorldInfo(this).GetAngle(),C3.toRadians(t))},AnySDK.IsBetweenAngles=function(t,e){const n=C3.toRadians(t),o=C3.toRadians(e),s=GetWorldInfo(this).GetAngle();return!C3.angleClockwise(o,n)?!(!C3.angleClockwise(s,n)&&C3.angleClockwise(s,o)):C3.angleClockwise(s,n)&&!C3.angleClockwise(s,o)},SDKv1.SetAngle=function(t){const e=this.GetWorldInfo(),n=C3.clampAngle(C3.toRadians(t));isNaN(n)||e.GetAngle()===n||(e.SetAngle(n),e.SetBboxChanged())},SDKv2.SetAngle=function(t){this.angleDegrees=t},AnySDK.RotateClockwise=function(t){if(isNaN(t)||0===t)return;const e=GetWorldInfo(this);e.SetAngle(e.GetAngle()+C3.toRadians(t)),e.SetBboxChanged()},AnySDK.RotateCounterclockwise=function(t){if(isNaN(t)||0===t)return;const e=GetWorldInfo(this);e.SetAngle(e.GetAngle()-C3.toRadians(t)),e.SetBboxChanged()},AnySDK.RotateTowardAngle=function(t,e){const n=GetWorldInfo(this),o=n.GetAngle(),s=C3.angleRotate(o,C3.toRadians(e),C3.toRadians(t));isNaN(s)||o===s||(n.SetAngle(s),n.SetBboxChanged())},AnySDK.RotateTowardPosition=function(t,e,n){const o=GetWorldInfo(this),s=o.GetAngle(),i=e-o.GetX(),r=n-o.GetY(),a=Math.atan2(r,i),l=C3.angleRotate(s,a,C3.toRadians(t));isNaN(l)||s===l||(o.SetAngle(l),o.SetBboxChanged())},AnySDK.SetTowardPosition=function(t,e){const n=GetWorldInfo(this),o=n.GetAngle(),s=t-n.GetX(),i=e-n.GetY(),r=Math.atan2(i,s);isNaN(r)||o===r||(n.SetAngle(r),n.SetBboxChanged())},SDKv1.GetAngle=function(){return C3.toDegrees(this.GetWorldInfo().GetAngle())},SDKv2.GetAngle=function(){return this.angleDegrees},AnySDK.CompareOpacity=function(t,e){return C3.compare(C3.roundToDp(100*GetWorldInfo(this).GetOpacity(),6),t,e)},SDKv1.IsVisible=function(){return this.GetWorldInfo().IsVisible()},SDKv2.IsVisible=function(){return this.isVisible},AnySDK.SetVisible=function(t){const e=GetWorldInfo(this);t=2===t?!e.IsVisible():0!==t,e.IsVisible()!==t&&(e.SetVisible(t),runtime.UpdateRender())},AnySDK.SetOpacity=function(t){const e=C3.clamp(t/100,0,1),n=GetWorldInfo(this);if(n.GetTransformWithParentOpacity()){if(n._GetSceneGraphInfo().GetOwnOpacity()===e)return}else if(n.GetOpacity()===e)return;n.SetOpacity(e),runtime.UpdateRender()},AnySDK.SetDefaultColor=function(t){tempColor.setFromRgbValue(t);const e=GetWorldInfo(this);e.GetUnpremultipliedColor().equalsIgnoringAlpha(tempColor)||(e.SetUnpremultipliedColor(tempColor),runtime.UpdateRender())},AnySDK.GetColor=function(){const t=GetWorldInfo(this).GetUnpremultipliedColor();return C3.PackRGBAEx(t.getR(),t.getG(),t.getB(),t.getA())},AnySDK.GetOpacity=function(){return C3.roundToDp(100*GetWorldInfo(this).GetOpacity(),6)},AnySDK.IsOnLayer=function(t){return!!(t=GetLayer(t))&&GetWorldInfo(this).GetLayer()===t},AnySDK.PickTopBottom=function(t){const e=GetObjectClass(this).GetCurrentSol(),n=e.GetInstances();if(!n.length)return!1;let o=n[0];for(let e=1,s=n.length;e<s;++e){const s=n[e],i=s.GetWorldInfo(),r=o.GetWorldInfo(),a=i.GetLayer().GetIndex(),l=r.GetLayer().GetIndex();0===t?(a>l||a===l&&i.GetZIndex()>r.GetZIndex())&&(o=s):(a<l||a===l&&i.GetZIndex()<r.GetZIndex())&&(o=s)}return e.PickOne(o),!0},SDKv1.CompareZElevation=function(t,e,n){const o=this.GetWorldInfo(),s=0===t?o.GetZElevation():o.GetTotalZElevation();return C3.compare(s,e,n)},SDKv2.CompareZElevation=function(t,e,n){const o=0===t?this.zElevation:this.totalZElevation;return C3.compare(o,e,n)},SDKv1.MoveToTop=function(){this.GetWorldInfo().ZOrderMoveToTop()},SDKv2.MoveToTop=function(){this.moveToTop()},SDKv1.MoveToBottom=function(){this.GetWorldInfo().ZOrderMoveToBottom()},SDKv2.MoveToBottom=function(){this.moveToBottom()},AnySDK.MoveToLayer=function(t){(t=GetLayer(t))&&GetWorldInfo(this).ZOrderMoveToLayer(t)},AnySDK.ZMoveToObject=function(t,e){const n=0===t;if(!(e=GetObjectClass(e)))return;const o=GetInst(this),s=e.GetFirstPicked(o);s&&o.GetWorldInfo().ZOrderMoveAdjacentToInstance(s,n)},SDKv1.SetZElevation=function(t){const e=this.GetWorldInfo();e.GetZElevation()!==t&&(e.SetZElevation(t),runtime.UpdateRender())},SDKv2.SetZElevation=function(t){this.zElevation=t},AnySDK.LayerNumber=function(){return GetWorldInfo(this).GetLayer().GetIndex()},AnySDK.LayerName=function(){return GetWorldInfo(this).GetLayer().GetName()},SDKv1.ZIndex=function(){return this.GetWorldInfo().GetZIndex()},SDKv2.ZIndex=function(){return this.zIndex},SDKv1.ZElevation=function(){return this.GetWorldInfo().GetZElevation()},SDKv2.ZElevation=function(){return this.zElevation},SDKv1.TotalZElevation=function(){return this.GetWorldInfo().GetTotalZElevation()},SDKv2.TotalZElevation=function(){return this.totalZElevation},AnySDK.IsEffectEnabled=function(t){const e=GetInst(this),n=e.GetObjectClass().GetEffectList().GetEffectTypeByName(t);if(!n)return;const o=n.GetIndex();return e.GetWorldInfo().GetInstanceEffectList().IsEffectIndexActive(o)},AnySDK.SetEffectEnabled=function(t,e){const n=GetInst(this),o=n.GetObjectClass().GetEffectList().GetEffectTypeByName(e);if(!o)return;const s=o.GetIndex(),i=1===t,r=n.GetWorldInfo().GetInstanceEffectList();r.IsEffectIndexActive(s)!==i&&(r.SetEffectIndexActive(s,i),r.UpdateActiveEffects(),runtime.UpdateRender())},AnySDK.SetEffectParam=function(t,e,n){const o=GetInst(this),s=o.GetObjectClass().GetEffectList().GetEffectTypeByName(t);if(!s)return;e=Math.floor(e);const i=s.GetShaderProgram().GetParameterType(e);if(!i)return;"color"===i?(tempColor.setFromRgbValue(n),n=tempColor):"percent"===i&&(n/=100);const r=s.GetIndex(),a=o.GetWorldInfo().GetInstanceEffectList();a.SetEffectParameter(r,e,n)&&a.IsEffectIndexActive(r)&&runtime.UpdateRender()};const tempRect=C3.New(C3.Rect),tempCandidates1=[],tempCandidates2=[];let needsCollisionFinish=!1,rPickType=null,rPickFromElseInstances=!1;const rToPick=new Set;function CollMemory_Add(t,e,n,o){e.GetUID()<n.GetUID()?t.Set(e,n,o):t.Set(n,e,o)}function CollMemory_Remove(t,e,n){e.GetUID()<n.GetUID()?t.Delete(e,n):t.Delete(n,e)}function CollMemory_RemoveInstance(t,e){t.DeleteEither(e)}function CollMemory_Get(t,e,n){return e.GetUID()<n.GetUID()?t.Get(e,n):t.Get(n,e)}function DoOverlapCondition(t,e,n,o){if(!e)return!1;const s=0!==n||0!==o,i=t.GetWorldInfo(),r=runtime.GetCollisionEngine(),a=runtime.GetCurrentCondition(),l=a.GetEventBlock().IsOrBlock(),c=a.GetObjectClass(),u=a.IsInverted(),S=e.GetCurrentSol(),f=c!==e;let G;rPickType=e,needsCollisionFinish=f&&!u,rPickFromElseInstances=!1;let d=0,I=0,C=!1;S.IsSelectAll()?(tempRect.copy(i.GetBoundingBox()),tempRect.offset(n,o),r.GetCollisionCandidates(i.GetLayer(),e,tempRect,tempCandidates2),G=tempCandidates2):l?runtime.IsCurrentConditionFirst()&&!S._GetOwnElseInstances().length&&S._GetOwnInstances().length?G=S._GetOwnInstances():(G=S._GetOwnElseInstances(),rPickFromElseInstances=!0):G=S._GetOwnInstances(),s&&(d=i.GetX(),I=i.GetY(),i.OffsetXY(n,o),i.SetBboxChanged());for(const e of G)if(r.TestOverlap(t,e)){if(C=!0,u)break;f&&rToPick.add(e)}return s&&(i.SetXY(d,I),i.SetBboxChanged()),C3.clearArray(tempCandidates2),C}function FinishCollisionConditionPicking(t){const e=runtime.GetCurrentEvent().IsOrBlock(),n=rPickType.GetCurrentSol(),o=n._GetOwnInstances(),s=n._GetOwnElseInstances();n.IsSelectAll()?(n.SetSetPicked(rToPick),e&&(C3.clearArray(s),n.AddElseInstances(rToPick,rPickType.GetInstances()))):e?rPickFromElseInstances?n.TransferElseInstancesToOwn(rToPick):(n.AddElseInstances(rToPick,o),n.SetSetPicked(rToPick)):n.SetSetPicked(rToPick),rPickType.ApplySolToContainer()}function FinishCollisionCondition(t,e){needsCollisionFinish&&(e&&FinishCollisionConditionPicking(t),rToPick.clear(),rPickType=null,needsCollisionFinish=!1)}function*DebugOnCollision(t){if(!t)return!1;const e=this.GetRuntime(),n=e.GetCollisionEngine(),o=e.GetEventSheetManager(),s=o.GetEventStack(),i=o.GetCurrentCondition(),r=i.GetObjectClass(),a=i.GetSavedDataMap(),l=i.GetUnsavedDataMap(),c=s.GetCurrentStackFrame(),u=e.GetTickCount(),S=u-1,f=c.GetCurrentEvent(),G=s.Push(f);let d=a.get("collmemory");d||(d=C3.New(C3.PairMap),a.set("collmemory",d)),l.get("collisionCreatedDestroyCallback")||(l.set("collisionCreatedDestroyCallback",!0),e.Dispatcher().addEventListener("instancedestroy",(t=>CollMemory_RemoveInstance(d,t.instance))));const I=r.GetCurrentSol(),C=t.GetCurrentSol(),h=I.GetInstances();let m=null;for(let e=0;e<h.length;++e){const s=h[e];C.IsSelectAll()?(n.GetCollisionCandidates(s.GetWorldInfo().GetLayer(),t,s.GetWorldInfo().GetBoundingBox(),tempCandidates1),m=tempCandidates1,n.AddRegisteredCollisionCandidates(s,t,m)):m=C.GetInstances();for(let e=0;e<m.length;++e){const i=m[e];if(n.TestOverlap(s,i)||n.CheckRegisteredCollision(s,i)){const e=CollMemory_Get(d,s,i);let n=!1,a=-2;"number"==typeof e&&(n=!0,a=e);const l=!n||a<S;if(CollMemory_Add(d,s,i,u),l){const e=f.GetSolModifiers();o.PushCopySol(e);const n=r.GetCurrentSol(),a=t.GetCurrentSol();if(n._SetSelectAll(!1),a._SetSelectAll(!1),r===t){const t=n._GetOwnInstances();C3.clearArray(t),t.push(s),t.push(i),r.ApplySolToContainer()}else{const e=n._GetOwnInstances(),o=a._GetOwnInstances();C3.clearArray(e),C3.clearArray(o),e.push(s),o.push(i),r.ApplySolToContainer(),t.ApplySolToContainer()}yield*f.DebugRetrigger(c,G),o.PopSol(e)}}else CollMemory_Remove(d,s,i)}C3.clearArray(tempCandidates1)}return s.Pop(),!1}function PickByUID_Normal(t,e){const n=runtime.GetInstanceByUID(e);if(!n)return!1;const o=t.GetCurrentSol();if(!o.IsSelectAll()&&!o._GetOwnInstances().includes(n))return!1;if(t.IsFamily()){if(n.GetObjectClass().BelongsToFamily(t))return o.PickOne(n),t.ApplySolToContainer(),!0}else if(n.GetObjectClass()===t)return o.PickOne(n),t.ApplySolToContainer(),!0;return!1}function PickByUID_Inverted(t,e){const n=t.GetCurrentSol();if(n.IsSelectAll()){n._SetSelectAll(!1),n.ClearArrays();const o=t.GetInstances();for(let t=0,s=o.length;t<s;++t){const s=o[t];s.GetUID()===e?n._PushElseInstance(s):n._PushInstance(s)}return t.ApplySolToContainer(),!!n._GetOwnInstances().length}{const o=n._GetOwnInstances();let s=0;for(let t=0,i=o.length;t<i;++t){const i=o[t];o[s]=i,i.GetUID()===e?n._PushElseInstance(i):++s}return C3.truncateArray(o,s),t.ApplySolToContainer(),!!o.length}}AnySDK.OnCollision=function(t){const e=GetObjectClass(this);t=GetObjectClass(t);const n=e.GetRuntime();if(n.IsDebugging())return DebugOnCollision.call(e,t);if(!t)return!1;const o=n.GetCollisionEngine(),s=n.GetEventSheetManager(),i=s.GetEventStack(),r=s.GetCurrentCondition(),a=r.GetObjectClass(),l=r.GetSavedDataMap(),c=r.GetUnsavedDataMap(),u=i.GetCurrentStackFrame(),S=n.GetTickCount(),f=S-1,G=u.GetCurrentEvent(),d=i.Push(G);let I=l.get("collmemory");I||(I=C3.New(C3.PairMap),l.set("collmemory",I)),c.get("collisionCreatedDestroyCallback")||(c.set("collisionCreatedDestroyCallback",!0),n.Dispatcher().addEventListener("instancedestroy",(t=>CollMemory_RemoveInstance(I,t.instance))));const C=a.GetCurrentSol(),h=t.GetCurrentSol(),m=C.GetInstances();let g=null;for(let e=0;e<m.length;++e){const n=m[e];h.IsSelectAll()?(o.GetCollisionCandidates(n.GetWorldInfo().GetLayer(),t,n.GetWorldInfo().GetBoundingBox(),tempCandidates1),g=tempCandidates1,o.AddRegisteredCollisionCandidates(n,t,g)):g=h.GetInstances();for(let e=0;e<g.length;++e){const i=g[e];if(o.TestOverlap(n,i)||o.CheckRegisteredCollision(n,i)){const e=CollMemory_Get(I,n,i);let o=!1,r=-2;"number"==typeof e&&(o=!0,r=e);const l=!o||r<f;if(CollMemory_Add(I,n,i,S),l){const e=G.GetSolModifiers();s.PushCopySol(e);const o=a.GetCurrentSol(),r=t.GetCurrentSol();if(o._SetSelectAll(!1),r._SetSelectAll(!1),a===t){const t=o._GetOwnInstances();C3.clearArray(t),t.push(n),t.push(i),a.ApplySolToContainer()}else{const e=o._GetOwnInstances(),s=r._GetOwnInstances();C3.clearArray(e),C3.clearArray(s),e.push(n),s.push(i),a.ApplySolToContainer(),t.ApplySolToContainer()}G.Retrigger(u,d),s.PopSol(e)}}else CollMemory_Remove(I,n,i)}C3.clearArray(tempCandidates1)}return i.Pop(),!1},AnySDK.IsOverlapping=function(t){return t=GetObjectClass(t),DoOverlapCondition(GetInst(this),t,0,0)},AnySDK.IsOverlappingOffset=function(t,e,n){return t=GetObjectClass(t),DoOverlapCondition(GetInst(this),t,e,n)},AnySDK.OnHierarchyReady=function(){return!0},AnySDK.HasParent=function(){return GetWorldInfo(this).HasParent()},AnySDK.HasChildren=function(){return GetWorldInfo(this).HasChildren()},AnySDK.PickParent=function(t,e){const n=GetObjectClass(this);t=GetObjectClass(t);const o=n.GetRuntime(),s=this.GetCurrentSol().GetInstances();if(0===s.length)return!1;const i=t.GetCurrentSol();let r=i.GetInstances();if(i.IsSelectAll()){const e=[...o.instancesPendingCreateForObjectClass(t)];e.length>0&&(r=r.concat(e))}if(0===r.length)return!1;const a=i.IsSelectAll()?null:new Set(r),l=new Set;for(let n=0,o=s.length;n<o;++n){const o=s[n];if(1===e)for(const e of o.parents())e.BelongsToObjectClass(t)&&(null===a||a.has(e))&&l.add(e);else{let n;if(0===e){if(n=o.GetParent(),null===n)continue}else n=o.GetTopParent();n.BelongsToObjectClass(t)&&(null===a||a.has(n))&&l.add(n)}}return 0!==l.size&&(i.SetSetPicked(l),t.ApplySolToContainer(),!0)},AnySDK.PickChildren=function(t,e){const n=GetObjectClass(this);t=GetObjectClass(t);const o=n.GetRuntime(),s=n.GetCurrentSol().GetInstances();if(0===s.length)return!1;const i=t.GetCurrentSol();let r=i.GetInstances();if(i.IsSelectAll()){const e=[...o.instancesPendingCreateForObjectClass(t)];e.length>0&&(r=r.concat(e))}if(0===r.length)return!1;const a=i.IsSelectAll()?null:new Set(r),l=new Set;for(let n=0,o=s.length;n<o;++n){const o=s[n];2!==e||o.HasChildren()||!o.BelongsToObjectClass(t)||null!==a&&!a.has(o)||l.add(o);for(const n of 0===e?o.children():o.allChildren())2===e&&n.HasChildren()||n.BelongsToObjectClass(t)&&(null===a||a.has(n))&&l.add(n)}return 0!==l.size&&(i.SetSetPicked(l),t.ApplySolToContainer(),!0)},AnySDK.PickNthChild=function(t,e,n){const o=GetObjectClass(this);t=GetObjectClass(t);const s=o.GetRuntime(),i=o.GetCurrentSol().GetInstances();if(0===i.length)return!1;const r=t.GetCurrentSol();let a=r.GetInstances();if(r.IsSelectAll()){const e=[...s.instancesPendingCreateForObjectClass(t)];e.length>0&&(a=a.concat(e))}if(0===a.length)return!1;const l=r.IsSelectAll()?null:new Set(a),c=[];for(let o=0,s=i.length;o<s;++o){const s=i[o];if(0===e){const e=s.GetChildAt(n);null!==e&&e.BelongsToObjectClass(t)&&(null===l||l.has(e))&&c.push(e)}else if(1===e)for(const e of s.children())if(e.BelongsToObjectClass(t)){if(0===n){(null===l||l.has(e))&&c.push(e);break}--n}}return 0!==c.length&&(r.SetArrayPicked(c),t.ApplySolToContainer(),!0)},AnySDK.CompareChildCount=function(t,e,n){const o=GetInst(this);switch(t){case 0:default:return C3.compare(o.GetChildCount(),e,n);case 1:return C3.compare(o.GetAllChildCount(),e,n)}},AnySDK.AddChild=function(t,e,n,o,s,i,r,a,l,c){t=GetObjectClass(t);const u=GetInst(this),S=runtime.GetCurrentAction().GetObjectClass();for(const f of t.allCorrespondingInstances(u,S)){if(!f.GetPlugin().SupportsSceneGraph())return;u.AddChild(f,{transformX:e,transformY:n,transformWidth:o,transformHeight:s,transformAngle:i,transformOpacity:r,transformZElevation:a,transformVisibility:l,destroyWithParent:c})}},AnySDK.RemoveChild=function(t){t=GetObjectClass(t);const e=GetInst(this),n=runtime.GetCurrentAction().GetObjectClass();for(const o of t.allCorrespondingInstances(e,n))e.RemoveChild(o)},AnySDK.RemoveFromParent=function(){const t=GetInst(this);if(!t.HasParent())return;t.GetParent().RemoveChild(t)},AnySDK.ParentUID=function(){const t=GetInst(this).GetParent();return t?t.GetUID():-1},AnySDK.ChildCount=function(){return GetInst(this).GetChildCount()},AnySDK.AllChildCount=function(){return GetInst(this).GetAllChildCount()},AnySDK.SetMeshSize=function(t,e){t=Math.floor(t),e=Math.floor(e);const n=GetWorldInfo(this);t<2||e<2||!isFinite(t)||!isFinite(e)?(n.ReleaseMesh(),n.SetBboxChanged()):n.CreateMesh(t,e)},AnySDK.SetMeshPoint=function(t,e,n,o,s,i,r,a){const l=GetWorldInfo(this);l.SetMeshPoint(t,e,{mode:0===n?"absolute":"relative",x:o,y:s,zElevation:i,u:r,v:a})&&l.SetBboxChanged()},AnySDK.MeshColumns=function(){const t=GetWorldInfo(this);return t.HasMesh()?t.GetSourceMesh().GetHSize():0},AnySDK.MeshRows=function(){const t=GetWorldInfo(this);return t.HasMesh()?t.GetSourceMesh().GetVSize():0},AnySDK.SetElementVisible=function(t){const e=GetWorldInfo(this);t=2===t?!e.IsVisible():0!==t,e.IsVisible()!==t&&e.SetVisible(t)},AnySDK.SetElementCSSStyle=function(t,e){this instanceof self.IInstance?this.setElementCSSStyle(t,e):this.SetElementCSSStyle(t,e)},AnySDK.SetElementAttribute=function(t,e){this instanceof self.IInstance?this.setElementAttribute(t,""+e):this.SetElementAttribute(t,""+e)},AnySDK.RemoveElementAttribute=function(t){this instanceof self.IInstance?this.removeElementAttribute(t):this.RemoveElementAttribute(t)},AnySDK.SetElementFocus=function(){this instanceof self.IInstance?this.focusElement():this.FocusElement()},AnySDK.SetElementBlur=function(){this instanceof self.IInstance?this.blurElement():this.BlurElement()},AnySDK.IsElementFocused=function(){return this instanceof self.IInstance?this.isElementFocused():this.IsElementFocused()},AnySDK.SetElementEnabled=function(t){this instanceof self.IInstance?this._setEnabled(0!==t):this._SetEnabled(0!==t)},AnySDK.IsElementEnabled=function(){return this instanceof self.IInstance?this._isEnabled():this._IsEnabled()},SDKv1.CompareInstanceVar=function(t,e,n){return C3.compare(this.GetInstance().GetInstanceVariableValue(t),e,n)},SDKv2.CompareInstanceVar=function(t,e,n){return C3.compare(GetInst_SDKv2(this).GetInstanceVariableValue(t),e,n)},SDKv1.IsBoolInstanceVarSet=function(t){return!!this.GetInstance().GetInstanceVariableValue(t)},SDKv2.IsBoolInstanceVarSet=function(t){return!!GetInst_SDKv2(this).GetInstanceVariableValue(t)},AnySDK.PickInstVarHiLow=function(t,e){const n=GetObjectClass(this),o=n.GetCurrentSol(),s=o.GetInstances();if(!s.length)return!1;const i=n.IsFamily();let r=null,a=0;for(let o=0,l=s.length;o<l;++o){const l=s[o],c=i?l.GetObjectClass().GetFamilyInstanceVariableOffset(n.GetFamilyIndex()):0,u=l.GetInstanceVariableValue(c+e);(null===r||0===t&&u<a||1===t&&u>a)&&(a=u,r=l)}return o.PickOne(r),!0},AnySDK.PickByUID=function(t){const e=GetObjectClass(this);return e.GetRuntime().GetCurrentCondition().IsInverted()?PickByUID_Inverted(e,t):PickByUID_Normal(e,t)},AnySDK.HasTags=function(t){const e=new Set(C3.splitStringAndNormalize(t)),n=GetInst(this).GetTagsSet();return e.isSubsetOf(n)},AnySDK.Tags=function(){return GetInst(this).GetTagsString()},AnySDK.TagsCount=function(){return GetInst(this).GetTagsSet().size},AnySDK.TagAt=function(t){return GetInst(this).GetTagAt(t)},AnySDK.ChangeTags=function(t,e){const n=C3.splitStringAndNormalize(e);if(0===n.length)return;const o=GetInst(this),s=new Set(o.GetTagsSet());if(0===t)for(const t of n)s.add(t);else if(1===t)for(const t of n)s.delete(t);o.SetTagsSet(s)},AnySDK.Destroy=function(){runtime.DestroyInstance(GetInst(this))},AnySDK.OnCreated=function(){return!0},AnySDK.OnDestroyed=function(){return!0},SDKv1.SetInstanceVar=function(t,e){this.GetInstance().SetInstanceVariableValue(t,e)},SDKv2.SetInstanceVar=function(t,e){GetInst_SDKv2(this).SetInstanceVariableValue(t,e)},SDKv1.AddInstanceVar=function(t,e){const n=this.GetInstance(),o=n.GetInstanceVariableValue(t);"number"==typeof o&&"number"!=typeof e?e=parseFloat(e):"string"==typeof o&&"string"!=typeof e&&(e=e.toString()),n.SetInstanceVariableValue(t,o+e)},SDKv2.AddInstanceVar=function(t,e){const n=GetInst_SDKv2(this),o=n.GetInstanceVariableValue(t);"number"==typeof o&&"number"!=typeof e?e=parseFloat(e):"string"==typeof o&&"string"!=typeof e&&(e=e.toString()),n.SetInstanceVariableValue(t,o+e)},SDKv1.SubInstanceVar=function(t,e){const n=this.GetInstance(),o=n.GetInstanceVariableValue(t);"number"==typeof o&&("number"!=typeof e&&(e=parseFloat(e)),n.SetInstanceVariableValue(t,o-e))},SDKv2.SubInstanceVar=function(t,e){const n=GetInst_SDKv2(this),o=n.GetInstanceVariableValue(t);"number"==typeof o&&("number"!=typeof e&&(e=parseFloat(e)),n.SetInstanceVariableValue(t,o-e))},SDKv1.SetBoolInstanceVar=function(t,e){this.GetInstance().SetInstanceVariableValue(t,e?1:0)},SDKv2.SetBoolInstanceVar=function(t,e){GetInst_SDKv2(this).SetInstanceVariableValue(t,e?1:0)},SDKv1.ToggleBoolInstanceVar=function(t){const e=this.GetInstance();e.SetInstanceVariableValue(t,0===e.GetInstanceVariableValue(t)?1:0)},SDKv2.ToggleBoolInstanceVar=function(t){const e=GetInst_SDKv2(this);e.SetInstanceVariableValue(t,0===e.GetInstanceVariableValue(t)?1:0)},AnySDK.LoadFromJsonString=function(t){let e;try{e=JSON.parse(t)}catch(t){return void console.error("Failed to load from JSON string: ",t)}const n=GetInst(this),o="state";runtime.ClearIntancesNeedingAfterLoad(),n._OnBeforeLoad(o),n.LoadFromJson(e,o),runtime.DoAfterLoad(o,{setFromJson:!0})},AnySDK.AsJSON=function(){return JSON.stringify(GetInst(this).SaveToJson("state"))},AnySDK.ObjectTypeName=function(){return GetInst(this).GetObjectClass().GetName()},AnySDK.Count=function(){const t=runtime.GetCurrentEventStackFrame().GetExpressionObjectClass();let e=t.GetInstanceCount();for(const n of runtime.instancesPendingCreateForObjectClass(t))++e;return e},AnySDK.PickedCount=function(){return runtime.GetCurrentEventStackFrame().GetExpressionObjectClass().GetCurrentSol().GetInstances().length},SDKv1.GetIID=function(){return this.GetInstance().GetIID()},SDKv2.GetIID=function(){return GetInst_SDKv2(this).GetIID()},SDKv1.GetUID=function(){return this.GetInstance().GetUID()},SDKv2.GetUID=function(){return GetInst_SDKv2(this).GetUID()},AnySDK.OnInstanceSignal=function(t){const e=GetInst(this);return t.toLowerCase()===runtime.GetEventSheetManager().GetCurrentInstanceSignalTag(e)},AnySDK.InstanceSignal=function(t){const e=GetInst(this);runtime.GetEventSheetManager().InstanceSignal(e,t)},AnySDK.InstanceWaitForSignal=function(t){const e=GetObjectClass(this);return runtime.GetEventSheetManager().AddScheduledWait().InitInstanceSignals(e.GetCurrentSol().GetInstances(),t),!0},AnySDK.TemplateName=function(){return GetInst(this).GetTemplateName()},C3.AddCommonACEs=function(t,e,n){const o=t[1],s=t[3],i=t[4],r=t[5],a=t[6],l=t[7],c=t[8],u=t[10],S=t[11],f=t[12],G=t[13],d=t[14],I=t[15],C=t[16],h=e.Cnds,m=e.Acts,g=e.Exps,y=Object.assign({},AnySDK,n>=2?SDKv2:SDKv1);s&&(h.CompareX=y.CompareX,h.CompareY=y.CompareY,h.IsOnScreen=y.IsOnScreen,h.IsOutsideLayout=y.IsOutsideLayout,h.PickDistance=y.PickDistance,m.SetX=y.SetX,m.SetY=y.SetY,m.SetPos=y.SetPos,m.SetPosToObject=y.SetPosToObject,m.MoveForward=y.MoveForward,m.MoveAtAngle=y.MoveAtAngle,g.X=y.GetX,g.Y=y.GetY,g.dt=y.GetDt),i&&(h.CompareWidth=y.CompareWidth,h.CompareHeight=y.CompareHeight,m.SetWidth=y.SetWidth,m.SetHeight=y.SetHeight,m.SetSize=y.SetSize,g.Width=y.GetWidth,g.Height=y.GetHeight,g.BBoxLeft=y.GetBboxLeft,g.BBoxTop=y.GetBboxTop,g.BBoxRight=y.GetBboxRight,g.BBoxBottom=y.GetBboxBottom,g.BBoxMidX=y.GetBboxMidX,g.BBoxMidY=y.GetBboxMidY),r&&(h.AngleWithin=y.IsAngleWithin,h.IsClockwiseFrom=y.IsAngleClockwiseFrom,h.IsBetweenAngles=y.IsBetweenAngles,m.SetAngle=y.SetAngle,m.RotateClockwise=y.RotateClockwise,m.RotateCounterclockwise=y.RotateCounterclockwise,m.RotateTowardAngle=y.RotateTowardAngle,m.RotateTowardPosition=y.RotateTowardPosition,m.SetTowardPosition=y.SetTowardPosition,g.Angle=y.GetAngle),a&&(h.IsVisible=y.IsVisible,h.CompareOpacity=y.CompareOpacity,m.SetVisible=y.SetVisible,m.SetOpacity=y.SetOpacity,m.SetDefaultColor=y.SetDefaultColor,g.Opacity=y.GetOpacity,g.ColorValue=y.GetColor),l&&(h.IsOnLayer=y.IsOnLayer,h.PickTopBottom=y.PickTopBottom,h.CompareZElevation=y.CompareZElevation,m.MoveToTop=y.MoveToTop,m.MoveToBottom=y.MoveToBottom,m.MoveToLayer=y.MoveToLayer,m.ZMoveToObject=y.ZMoveToObject,m.SetZElevation=y.SetZElevation,g.LayerNumber=y.LayerNumber,g.LayerName=y.LayerName,g.ZIndex=y.ZIndex,g.ZElevation=y.ZElevation,g.TotalZElevation=y.TotalZElevation),c&&(h.IsEffectEnabled=y.IsEffectEnabled,m.SetEffectEnabled=y.SetEffectEnabled,m.SetEffectParam=y.SetEffectParam),G&&(h.OnHierarchyReady=y.OnHierarchyReady,h.HasParent=y.HasParent,h.HasChildren=y.HasChildren,h.PickParent=y.PickParent,h.PickChildren=y.PickChildren,h.PickNthChild=y.PickNthChild,h.CompareChildCount=y.CompareChildCount,m.AddChild=y.AddChild,m.RemoveChild=y.RemoveChild,m.RemoveFromParent=y.RemoveFromParent,g.ParentUID=y.ParentUID,g.ChildCount=y.ChildCount,g.AllChildCount=y.AllChildCount),d&&(m.SetMeshSize=y.SetMeshSize,m.SetMeshPoint=y.SetMeshPoint,g.MeshColumns=y.MeshColumns,g.MeshRows=y.MeshRows),u&&(h.IsVisible=y.IsVisible,m.SetVisible=y.SetElementVisible,m.SetCSSStyle=y.SetElementCSSStyle,m.SetElemAttribute=y.SetElementAttribute,m.RemoveElemAttribute=y.RemoveElementAttribute),S&&(h.IsFocused=y.IsElementFocused,m.SetFocus=y.SetElementFocus,m.SetBlur=y.SetElementBlur),f&&(h.IsEnabled=y.IsElementEnabled,m.SetEnabled=y.SetElementEnabled),I&&(h.OnCollision=y.OnCollision,h.IsOverlapping=y.IsOverlapping,h.IsOverlappingOffset=y.IsOverlappingOffset,e.FinishCollisionCondition=FinishCollisionCondition),o||(h.CompareInstanceVar=y.CompareInstanceVar,h.IsBoolInstanceVarSet=y.IsBoolInstanceVarSet,h.PickInstVarHiLow=y.PickInstVarHiLow,h.PickByUID=y.PickByUID,h.HasTags=y.HasTags,m.SetInstanceVar=y.SetInstanceVar,m.AddInstanceVar=y.AddInstanceVar,m.SubInstanceVar=y.SubInstanceVar,m.SetBoolInstanceVar=y.SetBoolInstanceVar,m.ToggleBoolInstanceVar=y.ToggleBoolInstanceVar,m.ChangeTags=y.ChangeTags,h.OnCreated=y.OnCreated,h.OnDestroyed=y.OnDestroyed,m.Destroy=y.Destroy,m.LoadFromJsonString||(m.LoadFromJsonString=y.LoadFromJsonString),g.AsJSON||(g.AsJSON=y.AsJSON),g.Count=y.Count,g.PickedCount=y.PickedCount,g.IID=y.GetIID,g.UID=y.GetUID,g.ObjectTypeName=y.ObjectTypeName,g.Tags=y.Tags,g.TagsCount=y.TagsCount,g.TagAt=y.TagAt,h.OnInstanceSignal=y.OnInstanceSignal,m.InstanceSignal=y.InstanceSignal,m.InstanceWaitForSignal=y.InstanceWaitForSignal),C&&(g.TemplateName=y.TemplateName)};
}

// events/scheduledWait.js
{
const C3=self.C3;C3.ScheduledWait=class extends C3.DefendedBase{constructor(t){super(),this._eventSheetManager=t,this._type="",this._time=-1,this._signalTag="",this._isSignalled=!1,this._event=null,this._actIndex=0,this._solModifiers=[],this._dynamicSolModifiers=null,this._sols=new Map,this._pendingInstances=null,this._callingFunctionBlock=null,this._asyncId=-1,this._functionParameters=null,this._functionInnerLocalVars=null,this._shouldRelease=!1}Release(){this._type="",this._time=-1,this._signalTag="",this._event=null,this._callingFunctionBlock=null,this._functionParameters=null,this._functionInnerLocalVars=null,this._asyncId=-1,C3.clearArray(this._solModifiers),this._dynamicSolModifiers&&(this._dynamicSolModifiers.clear(),this._dynamicSolModifiers=null);for(const t of this._sols.values())t.Release();this._sols.clear(),this._pendingInstances=null}_Init(){const t=this._eventSheetManager,e=t.GetRuntime().GetAllObjectClasses(),s=t.GetCurrentEventStackFrame();this._event=s.GetCurrentEvent(),this._actIndex=s.GetActionIndex()+1;const i=t.FindFirstFunctionBlockParent(this._event);i&&(this._callingFunctionBlock=i,this._functionParameters=i.CaptureFunctionParameters(),this._functionInnerLocalVars=i._GetAllInnerLocalVariables().map((t=>t.GetValue())),i.IsAsync()&&(this._asyncId=i.PauseCurrentAsyncFunction()));for(const t of e){const e=t.GetCurrentSol();e.IsSelectAll()&&!this._event.HasSolModifier(t)||(this._solModifiers.push(t),this._sols.set(t,C3.New(C3.SolState,e)))}const n=t.GetDynamicSolModifiersSet();this._dynamicSolModifiers=n.size>0?n:null}InitTimer(t){this._type="timer",this._Init(),this._time=this._eventSheetManager.GetRuntime().GetGameTime()+t}InitWallTimer(t){this._type="walltimer",this._Init(),this._time=this._eventSheetManager.GetRuntime().GetWallTime()+t}InitSignal(t){this._type="signal",this._Init(),this._signalTag=t.toLowerCase()}InitInstanceSignals(t,e){this._type="instance-signals",this._Init(),this._signalTag=e.toLowerCase(),this._pendingInstances=new Set(t)}InitPromise(t){this._type="promise",this._Init(),t.then((()=>this.SetSignalled())).catch((t=>{console.warn("[C3 runtime] Promise rejected in 'Wait for previous actions to complete': ",t),this.SetSignalled()}))}IsTimer(){return"timer"===this._type}IsWallTimer(){return"walltimer"===this._type}IsSignal(){return"signal"===this._type}IsInstanceSignals(){return"instance-signals"===this._type}IsPromise(){return"promise"===this._type}GetSignalTag(){return this._signalTag}IsSignalled(){return this._isSignalled}SetSignalled(){this._isSignalled=!0}SetInstanceSignalled(t){this._pendingInstances.delete(t),0===this._pendingInstances.size&&this.SetSignalled()}_ShouldRun(){return this.IsTimer()?this._time<=this._eventSheetManager.GetRuntime().GetGameTime():this.IsWallTimer()?this._time<=this._eventSheetManager.GetRuntime().GetWallTime():this.IsSignalled()}_RestoreState(t){t._Restore(this._event,this._actIndex);for(const[t,e]of this._sols.entries()){const s=t.GetCurrentSol();e._Restore(s)}this._dynamicSolModifiers&&t.SetDynamicSolModifiers([...this._dynamicSolModifiers]);const e=this._callingFunctionBlock;e&&(e.SetFunctionParameters(this._functionParameters),e._GetAllInnerLocalVariables().map(((t,e)=>t.SetValue(this._functionInnerLocalVars[e]))),e.IsAsync()&&e.ResumeAsyncFunction(this._asyncId))}_Run(t){this._RestoreState(t),this._event._ResumeActionsAndSubEvents(t),this._callingFunctionBlock&&this._callingFunctionBlock.IsAsync()&&this._callingFunctionBlock.MaybeFinishAsyncFunctionCall(this._asyncId),this._eventSheetManager.ClearSol(this._solModifiers),this._shouldRelease=!0}async _DebugRun(t){this._RestoreState(t);for(const e of this._event._DebugResumeActionsAndSubEvents(t))await this._eventSheetManager.GetRuntime().DebugBreak(e);this._callingFunctionBlock&&this._callingFunctionBlock.IsAsync()&&this._callingFunctionBlock.MaybeFinishAsyncFunctionCall(this._asyncId),this._eventSheetManager.ClearSol(this._solModifiers),this._shouldRelease=!0}ShouldRelease(){return this._shouldRelease}RemoveInstances(t){for(const e of this._sols.values())e.RemoveInstances(t);if("instance-signals"===this._type){for(const e of t)this._pendingInstances.delete(e);0===this._pendingInstances.size&&this.SetSignalled()}}_SaveToJson(){const t={},e={"wt":this._type,"t":this._time,"st":this._signalTag,"s":this._isSignalled,"ev":this._event.GetSID(),"sm":this._solModifiers.map((t=>t.GetSID())),"dsm":this._dynamicSolModifiers?[...this._dynamicSolModifiers].map((t=>t.GetSID())):null,"sols":t};this._event._HasActionIndex(this._actIndex)&&(e["act"]=this._event.GetActionAt(this._actIndex).GetSID());for(const[e,s]of this._sols)t[e.GetSID().toString()]=s._SaveToJson();return"instance-signals"===this._type&&(e["pi"]=[...this._pendingInstances].map((t=>t.GetUID()))),e}static _CreateFromJson(t,e){const s=t.GetRuntime(),i=t.GetEventBlockBySID(e["ev"]);if(!i)return null;let n=0;if(e.hasOwnProperty("act")){const s=t.GetActionBySID(e["act"]);if(!s)return null;n=s.GetIndex()}const a=C3.New(C3.ScheduledWait,t);a._time=e["t"],e.hasOwnProperty("wt")?a._type=e["wt"]:a._type=-1===a._time?"signal":"timer",a._signalTag=e["st"],a._isSignalled=e["s"],a._event=i,a._actIndex=n;for(const t of e["sm"]){const e=s.GetObjectClassBySID(t);e&&a._solModifiers.push(e)}if(Array.isArray(e["dsm"]))for(const t of e["dsm"]){const e=s.GetObjectClassBySID(t);e&&(a._dynamicSolModifiers||(a._dynamicSolModifiers=new Set),a._dynamicSolModifiers.add(e))}for(const[i,n]of Object.entries(e["sols"])){const e=parseInt(i,10),l=s.GetObjectClassBySID(e);if(!l)continue;const o=C3.New(C3.SolState,null);o._LoadFromJson(t,n),a._sols.set(l,o)}if("instance-signals"===a._type){a._pendingInstances=new Set;for(const t of e["pi"]){const e=s.GetInstanceByUID(t);e&&a._pendingInstances.add(e)}}return a}};
}

// events/solState.js
{
const C3=self.C3;C3.SolState=class extends C3.DefendedBase{constructor(s){super(),this._objectClass=null,this._isSelectAll=!0,this._instances=[],s&&(this._objectClass=s.GetObjectClass(),this._isSelectAll=s.IsSelectAll(),C3.shallowAssignArray(this._instances,s._GetOwnInstances()))}Release(){this._objectClass=null,C3.clearArray(this._instances)}_Restore(s){s._SetSelectAll(this._isSelectAll),C3.shallowAssignArray(s._GetOwnInstances(),this._instances)}RemoveInstances(s){C3.arrayRemoveAllInSet(this._instances,s)}_SaveToJson(){return{"sa":this._isSelectAll,"insts":this._instances.map((s=>s.GetUID()))}}_LoadFromJson(s,e){const t=s.GetRuntime();this._isSelectAll=!!e["sa"],C3.clearArray(this._instances);for(const s of e["insts"]){const e=t.GetInstanceByUID(s);e&&this._instances.push(e)}}};
}

// sdk/sdkPluginBase.js
{
const C3=self.C3;function GetNextParamMap(t,e){let s=t.get(e);return s||(s=new Map,t.set(e,s)),s}C3.SDKPluginBase=class extends C3.DefendedBase{constructor(t){super(),this._runtime=t.runtime,this._id=t.id,this._name=t.name??"",this._isSingleGlobal=!!t.isSingleGlobal,this._isWorldType=!!t.isWorld,this._isRotatable=!!t.isRotatable,this._mustPredraw=!!t.mustPredraw,this._hasEffects=!!t.hasEffects,this._supportsSceneGraph=!!t.supportsSceneGraph,this._supportsMesh=!!t.supportsMesh,this._isHTMLElementType=!!t.isHTMLElementType,this._is3d=!!t.is3d,this._sdkVersion=t.sdkVersion,this._singleGlobalObjectClass=null,this._boundACEMethodCache=new Map,this._boundACEMethodCache_1param=new Map,this._boundACEMethodCache_2params=new Map,this._boundACEMethodCache_3params=new Map,this._scriptInterfaceClass=t.scriptInterfaceClass,this._iPlugin=null}Release(){this._runtime=null}GetRuntime(){return this._runtime}GetID(){return this._id}GetName(){return this._name}OnCreate(){}GetConstructor(){return this.GetSdkVersion()>=2?this._iPlugin.constructor:this.constructor}GetSdkVersion(){return this._sdkVersion}GetScriptInterfaceClass(t=!1){let e=this._scriptInterfaceClass;return t&&"function"!=typeof e&&this.GetSdkVersion()>=2&&(e=globalThis.ISDKPluginBase),e}IsSingleGlobal(){return this._isSingleGlobal}IsWorldType(){return this._isWorldType}IsHTMLElementType(){return this._isHTMLElementType}Is3D(){return this._is3d}IsRotatable(){return this._isRotatable}MustPreDraw(){return this._mustPredraw}HasEffects(){return this._hasEffects}SupportsSceneGraph(){return this._supportsSceneGraph}SupportsMesh(){return this._supportsMesh}_GetBoundACEMethod(t,e){if(!e)throw new Error("missing 'this' binding");let s=this._boundACEMethodCache.get(t);return s||(s=t.bind(e),this._boundACEMethodCache.set(t,s),s)}_GetBoundACEMethod_1param(t,e,s){if(!e)throw new Error("missing 'this' binding");const i=GetNextParamMap(this._boundACEMethodCache_1param,t);let n=i.get(s);return n||(n=t.bind(e,s),i.set(s,n),n)}_GetBoundACEMethod_2params(t,e,s,i){if(!e)throw new Error("missing 'this' binding");const n=GetNextParamMap(this._boundACEMethodCache_2params,t),r=GetNextParamMap(n,s);let a=r.get(i);return a||(a=t.bind(e,s,i),r.set(i,a),a)}_GetBoundACEMethod_3params(t,e,s,i,n){if(!e)throw new Error("missing 'this' binding");const r=GetNextParamMap(this._boundACEMethodCache_3params,t),a=GetNextParamMap(r,s),l=GetNextParamMap(a,i);let o=l.get(n);return o||(o=t.bind(e,s,i,n),l.set(n,o),o)}_SetSingleGlobalObjectClass(t){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");this._singleGlobalObjectClass=t}GetSingleGlobalObjectClass(){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");return this._singleGlobalObjectClass}GetSingleGlobalInstance(){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");return this._singleGlobalObjectClass.GetSingleGlobalInstance()}_InitScriptInterface(){const t=this.GetSdkVersion();C3.AddonManager._PushInitObject(this,t);const e=this.GetScriptInterfaceClass(!0);if(e){if(this._iPlugin=new e,!(this._iPlugin instanceof self.IPlugin))throw new TypeError("plugin class must derive from IPlugin")}else this._iPlugin=new self.IPlugin;C3.AddonManager._PopInitObject(t)}GetIPlugin(){return this._iPlugin}};
}

// sdk/sdkDOMPluginBase.js
{
const C3=self.C3;C3.SDKDOMPluginBase=class extends C3.SDKPluginBase{constructor(e,s){super(e),this._domComponentId=s,this._nextElementId=0,this._instMap=new Map,this.AddElementMessageHandler("elem-focused",(e=>e._OnElemFocused())),this.AddElementMessageHandler("elem-blurred",(e=>{e&&e._OnElemBlurred()}))}Release(){super.Release()}_AddElement(e){const s=this._nextElementId++;return this._instMap.set(s,e),s}_RemoveElement(e){this._instMap.delete(e)}AddElementMessageHandler(e,s){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,e,(e=>{const t=this._instMap.get(e["elementId"]);s(t,e)}))}};
}

// sdk/sdkTypeBase.js
{
const C3=self.C3;C3.SDKTypeBase=class extends C3.DefendedBase{constructor(e){super(),this._objectClass=e,this._runtime=e.GetRuntime(),this._plugin=e.GetPlugin()}Release(){this._objectClass=null,this._runtime=null,this._plugin=null}GetObjectClass(){return this._objectClass}GetRuntime(){return this._runtime}GetPlugin(){return this._plugin}GetImageInfo(){return this._objectClass.GetImageInfo()}OnCreate(){}FinishCondition(e){}BeforeRunAction(e){}AfterRunAction(e){}LoadTextures(e){}ReleaseTextures(){}OnDynamicTextureLoadComplete(){}PreloadTexturesWithInstances(e){}LoadTilemapData(){}GetScriptInterfaceClass(){return null}DispatchScriptEvent(e,t,s){const n=C3.New(C3.Event,e,t);n.objectClass=this,s&&Object.assign(n,s),this.GetObjectClass().DispatchUserScriptEvent(n)}};
}

// sdk/sdkInstanceBase.js
{
const C3=self.C3;C3.SDKInstanceBase=class extends C3.DefendedBase{constructor(e,t){super(),this._inst=e,this._domComponentId=t,this._wrapperComponentId=null,this._runtime=e.GetRuntime(),this._objectClass=this._inst.GetObjectClass(),this._sdkType=this._objectClass.GetSdkType(),this._tickFunc=null,this._tick2Func=null,this._isTicking=!1,this._isTicking2=!1,this._disposables=null,this._wasReleased=!1}Release(){this._wasReleased=!0,this._StopTicking(),this._StopTicking2(),this._tickFunc=null,this._tick2Func=null,this._disposables&&(this._disposables.Release(),this._disposables=null),this._inst=null,this._runtime=null,this._objectClass=null,this._sdkType=null}WasReleased(){return this._wasReleased}GetInstance(){return this._inst}GetRuntime(){return this._runtime}GetObjectClass(){return this._objectClass}GetPlugin(){return this._sdkType.GetPlugin()}GetSdkType(){return this._sdkType}GetScriptInterface(){return this._inst.GetInterfaceClass()}Trigger(e){return this._runtime.Trigger(e,this._inst,null)}DebugTrigger(e){return this._runtime.DebugTrigger(e,this._inst,null)}TriggerAsync(e){return this._runtime.TriggerAsync(e,this._inst,null)}FastTrigger(e,t){return this._runtime.FastTrigger(e,this._inst,t)}DebugFastTrigger(e,t){return this._runtime.DebugFastTrigger(e,this._inst,t)}ScheduleTriggers(e){return this._runtime.ScheduleTriggers(e)}AddDOMMessageHandler(e,t){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,e,t)}AddDOMMessageHandlers(e){for(const[t,i]of e)this.AddDOMMessageHandler(t,i)}PostToDOM(e,t){this._runtime.PostComponentMessageToDOM(this._domComponentId,e,t)}PostToDOMAsync(e,t){return this._runtime.PostComponentMessageToDOMAsync(this._domComponentId,e,t)}_PostToDOMMaybeSync(e,t){if(!this._runtime.IsInWorker())return window["c3_runtimeInterface"]["_OnMessageFromRuntime"]({"type":"event","component":this._domComponentId,"handler":e,"data":t,"responseId":null});this.PostToDOM(e,t)}SetWrapperExtensionComponentId(e){if(!e)throw new Error("cannot set empty component id");this._wrapperComponentId=e}IsWrapperExtensionAvailable(){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");return this._runtime.HasWrapperComponentId(this._wrapperComponentId)}AddWrapperExtensionMessageHandler(e,t){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");this._runtime.AddWrapperExtensionMessageHandler(this._wrapperComponentId,e,t)}AddWrapperExtensionMessageHandlers(e){for(const[t,i]of e)this.AddWrapperExtensionMessageHandler(t,i)}SendWrapperExtensionMessage(e,t){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");this._runtime.SendWrapperExtensionMessage(this._wrapperComponentId,e,t)}SendWrapperExtensionMessageAsync(e,t){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");return this._runtime.SendWrapperExtensionMessageAsync(this._wrapperComponentId,e,t)}Tick(){}Tick2(){}_StartTicking(){if(!this._isTicking){if(!this._tickFunc)if(this._runtime.IsDebug()){const e=globalThis.C3Debugger,t=this.GetPlugin();this._tickFunc=()=>{const i=performance.now();this.Tick(),e.AddIndividualPluginTickTime(t,performance.now()-i)}}else this._tickFunc=()=>this.Tick();this._runtime.Dispatcher().addEventListener("tick",this._tickFunc),this._isTicking=!0}}_StopTicking(){this._isTicking&&(this._runtime.Dispatcher().removeEventListener("tick",this._tickFunc),this._isTicking=!1)}IsTicking(){return this._isTicking}_StartTicking2(){if(!this._isTicking2){if(!this._tick2Func)if(this._runtime.IsDebug()){const e=globalThis.C3Debugger,t=this.GetPlugin();this._tick2Func=()=>{const i=performance.now();this.Tick2(),e.AddIndividualPluginTickTime(t,performance.now()-i)}}else this._tick2Func=()=>this.Tick2();this._runtime.Dispatcher().addEventListener("tick2",this._tick2Func),this._isTicking2=!0}}_StopTicking2(){this._isTicking2&&(this._runtime.Dispatcher().removeEventListener("tick2",this._tick2Func),this._isTicking2=!1)}IsTicking2(){return this._isTicking2}GetDebuggerProperties(){return[]}SaveToJson(){return null}LoadFromJson(e){}GetPropertyValueByIndex(e){}SetPropertyValueByIndex(e,t){}OffsetPropertyValueByIndex(e,t,i){if(0===t)return;const n=this.GetPropertyValueByIndex(e);if("number"!=typeof n)throw new Error("expected number");this.SetPropertyValueByIndex(e,n+t,i)}SetPropertyColorOffsetValueByIndex(e,t,i,n){}CallAction(e,...t){e.call(this,...t)}CallExpression(e,...t){return e.call(this,...t)}GetScriptInterfaceClass(){return null}DispatchScriptEvent(e,t,i){if(!this._inst.HasScriptInterface())return;const n=this.GetScriptInterface(),s=C3.New(C3.Event,e,t);s.instance=n,i&&Object.assign(s,i),n.dispatchEvent(s)}MustPreDraw(){return!1}};
}

// sdk/sdkWorldInstanceBase.js
{
const C3=self.C3;C3.SDKWorldInstanceBase=class extends C3.SDKInstanceBase{constructor(e,t){super(e,t),this._worldInfo=e.GetWorldInfo(),this._renderercontextlost_handler=null,this._renderercontextrestored_handler=null}Release(){if(this._renderercontextlost_handler){const e=this._runtime.Dispatcher();e.removeEventListener("renderercontextlost",this._renderercontextlost_handler),e.removeEventListener("renderercontextrestored",this._renderercontextrestored_handler),this._renderercontextlost_handler=null,this._renderercontextrestored_handler=null}this._worldInfo=null,super.Release()}HandleWebGLContextLoss(){this.HandleRendererContextLoss()}OnWebGLContextLost(){}OnWebGLContextRestored(){}HandleRendererContextLoss(){if(this._renderercontextlost_handler)return;this._renderercontextlost_handler=()=>this.OnRendererContextLost(),this._renderercontextrestored_handler=()=>this.OnRendererContextRestored();const e=this._runtime.Dispatcher();e.addEventListener("renderercontextlost",this._renderercontextlost_handler),e.addEventListener("renderercontextrestored",this._renderercontextrestored_handler)}OnRendererContextLost(){this.OnWebGLContextLost()}OnRendererContextRestored(){this.OnWebGLContextRestored()}GetWorldInfo(){return this._worldInfo}IsOriginalSizeKnown(){return!1}GetOriginalWidth(){if(!this.IsOriginalSizeKnown())throw new Error("original size not known");const e=this.GetCurrentImageInfo();if(e)return e.GetWidth()}GetOriginalHeight(){if(!this.IsOriginalSizeKnown())throw new Error("original size not known");const e=this.GetCurrentImageInfo();if(e)return e.GetHeight()}GetCurrentImageInfo(){return null}GetCurrentSurfaceSize(){const e=this.GetCurrentImageInfo();if(e){const t=e.GetTexture();if(t)return[t.GetWidth(),t.GetHeight()]}return[100,100]}GetCurrentTexRect(){const e=this.GetCurrentImageInfo();return e?e.GetTexRect():null}GetCurrentTexQuad(){const e=this.GetCurrentImageInfo();return e?e.GetTexQuad():null}IsCurrentTexRotated(){const e=this.GetCurrentImageInfo();return!!e&&e.IsRotated()}GetImagePoint(e){const t=this._inst.GetWorldInfo();return[t.GetX(),t.GetY(),t.GetTotalZElevation()]}LoadTilemapData(e,t,r){}TestPointOverlapTile(e,t){}RendersToOwnZPlane(){return!0}};
}

// sdk/sdkDOMInstanceBase.js
{
const C3=self.C3,tempRect=C3.New(C3.Rect);C3.SDKDOMInstanceBase=class extends C3.SDKWorldInstanceBase{constructor(t,e){super(t,e),this._elementId=this.GetPlugin()._AddElement(this),this._isElementShowing=!0,this._elemHasFocus=!1,this._autoFontSize=!1,this._autoFontSizeOffset=-.2,this._lastRect=C3.New(C3.Rect,0,0,-1,-1);const s=this._runtime.GetCanvasManager();this._lastWindowWidth=s.GetLastWidth(),this._lastWindowHeight=s.GetLastHeight(),this._lastHTMLIndex=-1,this._lastHTMLZIndex=-1,this._isPendingUpdateState=!1,this._StartTicking()}Release(){this.GetPlugin()._RemoveElement(this._elementId),this.PostToDOMElement("destroy"),this._elementId=-1,super.Release()}_GetElementInDOMMode(){if(this._runtime.IsInWorker())throw new Error("not valid in worker mode");return this._PostToDOMElementMaybeSync("get-element")}PostToDOMElement(t,e){e||(e={}),e["elementId"]=this._elementId,this.PostToDOM(t,e)}_PostToDOMElementMaybeSync(t,e){return e||(e={}),e["elementId"]=this._elementId,this._PostToDOMMaybeSync(t,e)}PostToDOMElementAsync(t,e){return e||(e={}),e["elementId"]=this._elementId,this.PostToDOMAsync(t,e)}CreateElement(t){t||(t={});const e=this.GetWorldInfo();t["elementId"]=this._elementId,t["isVisible"]=e.IsVisible(),t["htmlIndex"]=e.GetLayer().GetHTMLIndex(),t["htmlZIndex"]=e.GetHTMLZIndex(),Object.assign(t,this.GetElementState()),this._isElementShowing=!!t["isVisible"],this._PostToDOMMaybeSync("create",t),this._UpdatePosition(!0)}SetElementVisible(t){t=!!t,this._isElementShowing!==t&&(this._isElementShowing=t,this.PostToDOMElement("set-visible",{"isVisible":t}))}Tick(){this._UpdatePosition(!1)}_ShouldPreserveElement(){const t=this._runtime.GetCanvasManager().GetFullscreenMode();return"Android"===C3.Platform.OS&&("scale-inner"===t||"scale-outer"===t||"crop"===t)}_UpdatePosition(t){if(this.GetInstance().IsDestroyed())return;const e=this.GetWorldInfo(),s=e.GetLayer(),i=e.GetBoundingBox();let[n,l]=s.LayerToCanvasCss(i.getLeft(),i.getTop()),[o,h]=s.LayerToCanvasCss(i.getRight(),i.getBottom());const a=this._runtime.GetCanvasManager(),d=a.GetCssWidth(),m=a.GetCssHeight();if(!e.IsVisible()||!s.IsVisible())return void this.SetElementVisible(!1);if(!this._ShouldPreserveElement()&&(o<=0||h<=0||n>=d||l>=m))return void this.SetElementVisible(!1);tempRect.set(n,l,o,h);const r=a.GetLastWidth(),_=a.GetLastHeight(),c=s.GetHTMLIndex(),u=e.GetHTMLZIndex();if(!t&&tempRect.equals(this._lastRect)&&this._lastWindowWidth===r&&this._lastWindowHeight===_&&this._lastHTMLIndex===c&&this._lastHTMLZIndex===u)return void this.SetElementVisible(!0);this._lastRect.copy(tempRect),this._lastWindowWidth=r,this._lastWindowHeight=_,this._lastHTMLIndex=c,this._lastHTMLZIndex=u,this.SetElementVisible(!0);let M=null;this._autoFontSize&&(M=s.GetDisplayScale()+this._autoFontSizeOffset),this._PostToDOMElementMaybeSync("update-position",{"left":Math.round(this._lastRect.getLeft()),"top":Math.round(this._lastRect.getTop()),"width":Math.round(this._lastRect.width()),"height":Math.round(this._lastRect.height()),"htmlIndex":c,"htmlZIndex":u,"fontSize":M})}FocusElement(){this._PostToDOMElementMaybeSync("focus",{"focus":!0})}BlurElement(){this._PostToDOMElementMaybeSync("focus",{"focus":!1})}_OnElemFocused(){this._elemHasFocus=!0}_OnElemBlurred(){this._elemHasFocus=!1}IsElementFocused(){return this._elemHasFocus}SetElementCSSStyle(t,e){this.PostToDOMElement("set-css-style",{"prop":C3.CSSToCamelCase(t),"val":e})}SetElementAttribute(t,e){this.PostToDOMElement("set-attribute",{"name":t,"val":e})}RemoveElementAttribute(t){this.PostToDOMElement("remove-attribute",{"name":t})}UpdateElementState(){this._isPendingUpdateState||(this._isPendingUpdateState=!0,Promise.resolve().then((()=>{this._isPendingUpdateState=!1,this.PostToDOMElement("update-state",this.GetElementState())})))}GetElementState(){}GetElementId(){return this._elementId}};
}

// sdk/sdkBehaviorBase.js
{
const C3=self.C3,IBehavior=self.IBehavior;C3.SDKBehaviorBase=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e.runtime,this._id=e.id,this._name=e.name??"",this._myObjectClasses=C3.New(C3.ArraySet),this._myInstances=C3.New(C3.ArraySet),this._sdkVersion=e.sdkVersion,this._scriptInterfaceClass=e.scriptInterfaceClass,this._iBehavior=null}Release(){this._myInstances.Release(),this._myObjectClasses.Release(),this._runtime=null}GetRuntime(){return this._runtime}GetID(){return this._id}GetName(){return this._name}OnCreate(){}GetSdkVersion(){return this._sdkVersion}GetScriptInterfaceClass(e=!1){let s=this._scriptInterfaceClass;return e&&"function"!=typeof s&&this.GetSdkVersion()>=2&&(s=globalThis.ISDKBehaviorBase),s}_AddObjectClass(e){this._myObjectClasses.Add(e)}GetObjectClasses(){return this._myObjectClasses.GetArray()}_AddInstance(e){this._myInstances.Add(e)}_RemoveInstance(e){this._myInstances.Delete(e)}GetInstances(){return this._myInstances.GetArray()}_InitScriptInterface(){const e=this.GetSdkVersion();C3.AddonManager._PushInitObject(this,e);const s=this.GetScriptInterfaceClass(!0);if(s){if(this._iBehavior=new s,!(this._iBehavior instanceof IBehavior))throw new TypeError("behavior class must derive from IBehavior")}else this._iBehavior=new IBehavior;C3.AddonManager._PopInitObject(e)}GetIBehavior(){return this._iBehavior}};
}

// sdk/sdkBehaviorTypeBase.js
{
const C3=self.C3;C3.SDKBehaviorTypeBase=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e.GetRuntime(),this._behaviorType=e,this._objectClass=e.GetObjectClass(),this._behavior=e.GetBehavior(),this._behavior._AddObjectClass(this._objectClass)}Release(){this._runtime=null,this._behaviorType=null,this._objectClass=null,this._behavior=null}OnCreate(){}GetBehaviorType(){return this._behaviorType}GetObjectClass(){return this._objectClass}GetRuntime(){return this._runtime}GetBehavior(){return this._behavior}};
}

// sdk/sdkBehaviorInstanceBase.js
{
const C3=self.C3;C3.SDKBehaviorInstanceBase=class extends C3.DefendedBase{constructor(t,i){super(),this._behInst=t,this._domComponentId=i,this._inst=t.GetObjectInstance(),this._runtime=t.GetRuntime(),this._behaviorType=t.GetBehaviorType(),this._sdkType=this._behaviorType.GetSdkType(),this._isTicking=!1,this._isTicking2=!1,this._isPostTicking=!1,this._disposables=null}Release(){this._StopTicking(),this._StopTicking2(),this._StopPostTicking(),this._disposables&&(this._disposables.Release(),this._disposables=null),this._behInst=null,this._inst=null,this._runtime=null,this._behaviorType=null,this._sdkType=null}GetBehavior(){return this._behaviorType.GetBehavior()}GetBehaviorInstance(){return this._behInst}GetObjectInstance(){return this._inst}GetObjectClass(){return this._inst.GetObjectClass()}GetWorldInfo(){return this._inst.GetWorldInfo()}GetRuntime(){return this._runtime}GetBehaviorType(){return this._behaviorType}GetSdkType(){return this._sdkType}GetScriptInterface(){return this._behInst.GetScriptInterface()}Trigger(t){return this._runtime.Trigger(t,this._inst,this._behaviorType)}DebugTrigger(t){return this._runtime.DebugTrigger(t,this._inst,this._behaviorType)}TriggerAsync(t){return this._runtime.TriggerAsync(t,this._inst,this._behaviorType)}PostCreate(){}Tick(){}Tick2(){}PostTick(){}_StartTicking(){this._isTicking||(this._runtime._AddBehInstToTick(this),this._isTicking=!0)}_StopTicking(){this._isTicking&&(this._runtime._RemoveBehInstToTick(this),this._isTicking=!1)}IsTicking(){return this._isTicking}_StartTicking2(){this._isTicking2||(this._runtime._AddBehInstToTick2(this),this._isTicking2=!0)}_StopTicking2(){this._isTicking2&&(this._runtime._RemoveBehInstToTick2(this),this._isTicking2=!1)}IsTicking2(){return this._isTicking2}_StartPostTicking(){this._isPostTicking||(this._runtime._AddBehInstToPostTick(this),this._isPostTicking=!0)}_StopPostTicking(){this._isPostTicking&&(this._runtime._RemoveBehInstToPostTick(this),this._isPostTicking=!1)}IsPostTicking(){return this._isPostTicking}GetDebuggerProperties(){return[]}AddDOMMessageHandler(t,i){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,t,i)}OnSpriteFrameChanged(t,i){}SaveToJson(){return null}LoadFromJson(t){}GetPropertyValueByIndex(t){}SetPropertyValueByIndex(t,i){}OffsetPropertyValueByIndex(t,i){if(0===i)return;const e=this.GetPropertyValueByIndex(t);if("number"!=typeof e)throw new Error("expected number");this.SetPropertyValueByIndex(t,e+i)}SetPropertyColorOffsetValueByIndex(t,i,e,s){}CallAction(t,...i){t.call(this,...i)}CallExpression(t,...i){return t.call(this,...i)}GetScriptInterfaceClass(){return null}DispatchScriptEvent(t,i,e){if(!this._behInst.HasScriptInterface())return;const s=this.GetScriptInterface(),n=C3.New(C3.Event,t,i);n.behaviorInstance=s,n.instance=s.instance,e&&Object.assign(n,e),s.dispatchEvent(n)}};
}

// objects/addonManager.js
{
const C3=self.C3;C3.Plugins={},C3.Behaviors={};const internalApiToken=C3._GetInternalAPIToken();function ValidateInternalAPIToken(t){if(t!==internalApiToken)throw new Error("invalid internal API token")}let initObjectStack=[],initObjectStack2=[],initPropertiesStack=[],originalPushInitObject=null,originalPopInitObject=null,originalGetInitObject=null,originalGetInitObject2=null;const pluginsByCtor=new Map,behaviorsByCtor=new Map;C3.AddonManager=class extends C3.DefendedBase{constructor(t,e){super(),this._runtime=t,this._allPlugins=[],this._systemPlugin=null,this._allBehaviors=[],this._delayCreateBehaviors=new Map,this._solidBehavior=null,this._jumpthruBehavior=null,this._wrapperComponentIds=new Set(e)}CreatePlugin(t){const e=t[19],i=this._runtime.GetObjectReference(t[0]);if(!i)throw new Error("missing plugin");C3.AddCommonACEs(t,i,e);const n=e>=2?C3.SDKPluginBase:i,r=C3.New(n,{runtime:this._runtime,isSingleGlobal:t[1],isWorld:t[2],isRotatable:t[5],hasEffects:t[8],mustPredraw:t[9],supportsSceneGraph:t[13],supportsMesh:t[14],isHTMLElementType:t[17],is3d:t[18],sdkVersion:e,id:t[20],name:t[21],scriptInterfaceClass:e>=2?i:null});r.OnCreate(),this._allPlugins.push(r),pluginsByCtor.set(i,r)}CreateSystemPlugin(){this._systemPlugin=C3.New(C3.Plugins.System,{runtime:this._runtime,isSingleGlobal:!0}),this._systemPlugin.OnCreate()}CreateBehavior(t){const e=t[1],i=t[2],n=t[3],r=this._runtime.GetObjectReference(t[0]);if(!r)throw new Error("missing behavior");this._delayCreateBehaviors.set(r,(()=>{const t=e>=2?C3.SDKBehaviorBase:r,s=C3.New(t,{runtime:this._runtime,id:i,name:n,sdkVersion:e,scriptInterfaceClass:e>=2?r:null});s.OnCreate(),this._allBehaviors.push(s),behaviorsByCtor.set(r,s),!this._solidBehavior&&C3.Behaviors.solid&&s instanceof C3.Behaviors.solid?this._solidBehavior=s:!this._jumpthruBehavior&&C3.Behaviors.jumpthru&&s instanceof C3.Behaviors.jumpthru&&(this._jumpthruBehavior=s),s._InitScriptInterface()}))}_DelayCreateBehavior(t){const e=this._delayCreateBehaviors.get(t);e&&(e(),this._delayCreateBehaviors.delete(t))}static _PushInitObject(t,e=1){if(C3.AddonManager._PushInitObject!==originalPushInitObject)throw new Error("invalid method");1===e&&initObjectStack.push(t),initObjectStack2.push(t)}static _PopInitObject(t=1){if(C3.AddonManager._PopInitObject!==originalPopInitObject)throw new Error("invalid method");1===t&&initObjectStack.pop(),initObjectStack2.pop()}static _GetInitObject(){if(C3.AddonManager._GetInitObject!==originalGetInitObject)throw new Error("invalid method");if(0===initObjectStack.length)throw new Error("no init object set");return initObjectStack.at(-1)}static _GetInitObject2(t){if(C3.AddonManager._GetInitObject2!==originalGetInitObject2)throw new Error("invalid method");if(ValidateInternalAPIToken(t),0===initObjectStack2.length)throw new Error("no init object set");return initObjectStack2.at(-1)}static _PushInitProperties(t){initPropertiesStack.push(t)}static _PopInitProperties(){initPropertiesStack.pop()}static _GetInitProperties(){if(0===initPropertiesStack.length)throw new Error("no init properties set");return initPropertiesStack.at(-1)}_InitAddonScriptInterfaces(){for(const t of this._allPlugins)t._InitScriptInterface()}static GetPluginByConstructorFunction(t){return pluginsByCtor.get(t)||null}static GetBehaviorByConstructorFunction(t){return behaviorsByCtor.get(t)||null}GetSystemPlugin(){return this._systemPlugin}GetSolidBehavior(){return this._solidBehavior}GetJumpthruBehavior(){return this._jumpthruBehavior}HasWrapperComponentId(t){return this._wrapperComponentIds.has(t)}},originalPushInitObject=C3.AddonManager._PushInitObject,originalPopInitObject=C3.AddonManager._PopInitObject,originalGetInitObject=C3.AddonManager._GetInitObject,originalGetInitObject2=C3.AddonManager._GetInitObject2;
}

// objects/imageInfo.js
{
const C3=self.C3,allImageInfos=new Set;C3.ImageInfo=class extends C3.DefendedBase{constructor(){super(),this._generation=0,this._url="",this._size=0,this._offsetX=0,this._offsetY=0,this._width=0,this._height=0,this._isRotated=!1,this._hasMetaData=!1,this._imageAsset=null,this._textureState="",this._rcTex=C3.New(C3.Rect),this._quadTex=C3.New(C3.Quad),this._blobUrl="",this._iImageInfo=new self.IImageInfo(this),allImageInfos.add(this)}Release(){this.ReleaseTexture(),this._imageAsset&&0===this._imageAsset.GetRefCount()&&this._imageAsset.Release(),this._imageAsset=null,allImageInfos.delete(this),this.ReleaseBlobURL()}static OnRendererContextLost(){for(const t of allImageInfos)t._textureState="",t._rcTex.set(0,0,0,0),t._quadTex.setFromRect(t._rcTex)}LoadData(t){this._url=t[0],this._size=t[1],this._offsetX=t[2],this._offsetY=t[3],this._width=t[4],this._height=t[5],this._isRotated=t[6],this._hasMetaData=!0}LoadDynamicAsset(t,e,s){if(s=!!s,this._imageAsset)throw new Error("already loaded asset");this._url=e;const i={isTiled:s};return C3.IsAbsoluteURL(e)&&(i.loadPolicy="remote"),this.LoadAsset(t,i),this._imageAsset.Load()}LoadDynamicBlobAsset(t,e){if(this._imageAsset)throw new Error("already loaded asset");this._url="",this._size=e.size,this._imageAsset=C3.New(C3.ImageAsset,t.GetAssetManager(),{blob:e,size:this._size,loadPolicy:"local"})}ReplaceWith(t){if(t===this)throw new Error("cannot replace with self");this._generation++,this.ReleaseTexture(),this._url=t._url,this._size=t._size,this._offsetX=t._offsetX,this._offsetY=t._offsetY,this._width=t._width,this._height=t._height,this._isRotated=t._isRotated,this._hasMetaData=t._hasMetaData,this._imageAsset=t._imageAsset,this._textureState=t._textureState,this._rcTex=t._rcTex,this._quadTex=t._quadTex,this.ReleaseBlobURL()}GetURL(){return this._url}GetSize(){return this._size}GetOffsetX(){return this._offsetX}GetOffsetY(){return this._offsetY}IsRotated(){return this._isRotated}GetWidth(){return this._width}GetHeight(){return this._height}GetSheetWidth(){return this._imageAsset.GetWidth()}GetSheetHeight(){return this._imageAsset.GetHeight()}LoadAsset(t,e){if(this._imageAsset)throw new Error("already got asset");e=Object.assign({},e,{url:this.GetURL(),size:this.GetSize()}),this._imageAsset=t.LoadImage(e)}IsLoaded(){return this._imageAsset&&this._imageAsset.IsLoaded()}async LoadStaticTexture(t,e){if(!this._imageAsset)throw new Error("no asset");if(this._textureState)throw new Error("already loaded texture");const s=this._generation;this._textureState="loading";const i=await this._imageAsset.LoadStaticTexture(t,e);if(this._generation!==s)return null;if(!i)return this._textureState="",null;this._textureState="loaded",this._hasMetaData||(this._width=i.GetWidth(),this._height=i.GetHeight(),this._hasMetaData=!0);const h=this._isRotated?this._height:this._width,a=this._isRotated?this._width:this._height;return this._rcTex.set(this._offsetX,this._offsetY,this._offsetX+h,this._offsetY+a),this._rcTex.divide(i.GetWidth(),i.GetHeight()),this._quadTex.setFromRect(this._rcTex),this._isRotated&&this._quadTex.rotatePointsAnticlockwise(),i}ReleaseTexture(){this._textureState&&(this._imageAsset&&this._imageAsset.ReleaseTexture(),this._textureState="",this._rcTex.set(0,0,0,0),this._quadTex.setFromRect(this._rcTex))}GetTexture(){return this._imageAsset&&"loaded"===this._textureState?this._imageAsset.GetTexture():null}GetTexRect(){return this._rcTex}GetTexQuad(){return this._quadTex}GetIImageInfo(){return this._iImageInfo}GetImageAsset(){return this._imageAsset}async ExtractImageToCanvas(t){t||(t=await this._imageAsset.LoadToDrawable());const e=C3.CreateCanvas(this._width,this._height),s=e.getContext("2d");return this._isRotated?(s.rotate(Math.PI/-2),s.translate(-this._height,0),s.drawImage(t,this._offsetX,this._offsetY,this._height,this._width,0,0,this._height,this._width)):s.drawImage(t,this._offsetX,this._offsetY,this._width,this._height,0,0,this._width,this._height),e}async ExtractImageToBlobURL(t){if(this._blobUrl)return this._blobUrl;const e=await this.ExtractImageToCanvas(t),s=await C3.CanvasToBlob(e);return this._blobUrl=URL.createObjectURL(s),this._blobUrl}ReleaseBlobURL(){this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl="")}};
}

// objects/animationInfo.js
{
const C3=self.C3;C3.AnimationInfo=class extends C3.DefendedBase{constructor(e){super(),this._name=e[0],this._speed=e[1],this._isLooping=!!e[2],this._repeatCount=e[3],this._repeatTo=e[4],this._isPingPong=!!e[5],this._sid=e[6],this._frames=e[7].map((e=>C3.New(C3.AnimationFrameInfo,e))),this._iAnimation=new self.IAnimation(this)}static CreateDynamic(e,t){const r=C3.New(C3.AnimationInfo,[t,0,!1,0,0,!1,Math.floor(1e15*Math.random()),[]]);return r._frames.push(C3.AnimationFrameInfo.CreateDynamic(e)),r}Release(){for(const e of this._frames)e.Release();C3.clearArray(this._frames)}LoadAllAssets(e){for(const t of this._frames)t.GetImageInfo().LoadAsset(e)}LoadAllTextures(e,t){return Promise.all(this._frames.map((r=>r.GetImageInfo().LoadStaticTexture(e,t))))}ReleaseAllTextures(){for(const e of this._frames)e.GetImageInfo().ReleaseTexture()}GetName(){return this._name}GetSID(){return this._sid}GetFrameCount(){return this._frames.length}GetFrames(){return this._frames}GetFrameAt(e){if((e=Math.floor(e))<0||e>=this._frames.length)throw new RangeError("invalid frame");return this._frames[e]}InsertFrameAt(e,t){(t=Math.floor(t))<0?this._frames.unshift(e):t>=this._frames.length?this._frames.push(e):this._frames.splice(t,0,e)}RemoveFrameAt(e){if((e=Math.floor(e))<0||e>=this._frames.length)throw new RangeError("invalid frame");this._frames[e].Release(),this._frames.splice(e,1)}GetFrameIndexByTag(e){for(let t=0,r=this._frames.length;t<r;++t)if(C3.equalsNoCase(this._frames[t].GetTag(),e))return t;return-1}FrameTagOrIndexToIndex(e){if("string"==typeof e){const t=this.GetFrameIndexByTag(e);if(-1===t)throw new Error(`cannot find animation frame with tag ${e}`);return t}return e}GetSpeed(){return this._speed}IsLooping(){return this._isLooping}GetRepeatCount(){return this._repeatCount}GetRepeatTo(){return this._repeatTo}IsPingPong(){return this._isPingPong}GetIAnimation(){return this._iAnimation}};
}

// objects/animationFrameInfo.js
{
const C3=self.C3,EMPTY_IMAGE_BLOB=(()=>{const t=atob("iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAQMAAABKLAcXAAAAAXNSR0IArs4c6QAAAANQTFRFAAAAp3o92gAAAAF0Uk5TAEDm2GYAAAATSURBVBgZYxgFo2AUjIJRQFcAAAV4AAHcRQIbAAAAAElFTkSuQmCC"),i=new Uint8Array(t.length);for(let e=0,n=t.length;e<n;++e)i[e]=t.charCodeAt(e);return new Blob([i],{type:"image/png"})})();C3.AnimationFrameInfo=class extends C3.DefendedBase{constructor(t){super(),this._imageInfo=C3.New(C3.ImageInfo),this._imageInfo.LoadData(t),this._duration=t[7],this._origin=C3.New(C3.Vector2,t[8],t[9]),this._imagePoints=t[10].map((t=>C3.New(C3.ImagePoint,this,t))),this._imagePointsByName=new Map;for(const t of this._imagePoints)this._imagePointsByName.set(t.GetName().toLowerCase(),t);this._collisionPoly=null;const i=t[11];i.length>=6&&(this._collisionPoly=C3.New(C3.CollisionPoly,i)),this._tag=t[12]?t[12]:"",this._iAnimationFrame=new self.IAnimationFrame(this)}static CreateDynamic(t){const i=C3.New(C3.AnimationFrameInfo,["",0,0,0,100,100,!1,1,0,0,[],[],""]);return i._imageInfo.LoadDynamicBlobAsset(t,EMPTY_IMAGE_BLOB),i}Release(){this._collisionPoly&&(this._collisionPoly.Release(),this._collisionPoly=null),this._imageInfo.Release(),this._imageInfo=null}GetImageInfo(){return this._imageInfo}GetDuration(){return this._duration}GetOriginX(){return this._origin.getX()}GetOriginY(){return this._origin.getY()}GetCollisionPoly(){return this._collisionPoly}GetImagePointByName(t){return this._imagePointsByName.get(t.toLowerCase())||null}GetImagePointByIndex(t){return(t=Math.floor(t))<0||t>=this._imagePoints.length?null:this._imagePoints[t]}GetImagePointCount(){return this._imagePoints.length}GetTag(){return this._tag}GetIAnimationFrame(){return this._iAnimationFrame}};
}

// objects/imagePoint.js
{
const C3=self.C3;C3.ImagePoint=class extends C3.DefendedBase{constructor(e,t){super(),this._afi=e,this._name=t[0],this._pos=C3.New(C3.Vector2,t[1],t[2])}Release(){}GetName(){return this._name}GetX(){return this._pos.getX()}GetY(){return this._pos.getY()}GetVec2(){return this._pos}};
}

// objects/objectClass.js
{
const C3=globalThis.C3,C3Debugger=globalThis.C3Debugger,IObjectClass=globalThis.IObjectClass,IObjectType=globalThis.IObjectType,IFamily=globalThis.IFamily,assert=globalThis.assert;C3.ObjectClass=class extends C3.DefendedBase{constructor(t,e,s){super();const i=t.GetObjectReference(s[1]);this._runtime=t,this._plugin=C3.AddonManager.GetPluginByConstructorFunction(i),this._sdkType=null,this._instSdkCtor=i.Instance,this._index=e,this._sid=s[11],this._name=s[0],this._jsPropName=this._runtime.GetJsPropName(s[14]),this._isGlobal=!!s[9],this._isFamily=!!s[2],this._isOnLoaderLayout=!!s[10],this._instVars=s[3].map((e=>({sid:e[0],type:e[1],name:e[2],jsPropName:t.GetJsPropName(e[3])}))),this._behaviorsCount=s[4],this._effectsCount=s[5],this._isWorldType=this._plugin.IsWorldType(),this._dispatcher=C3.New(C3.Event.Dispatcher),this._effectList=null;const[n,a]=t.GetCollisionEngine().GetCollisionCellSize();if(this._collisionGrid=C3.New(C3.SparseGrid,n,a),this._anyCollisionCellChanged=!0,this._familyMembers=null,this._familyMembersSet=null,this._familyIndex=-1,this._families=null,this._familiesSet=null,this._familyInstVarMap=null,this._familyBehaviorMap=null,this._familyEffectMap=null,this._isInContainer=!1,this._container=null,this._behaviorTypes=s[8].map((t=>C3.BehaviorType.Create(this,t))),this._behaviorTypesIncludingInherited=[],this._behaviorsByName=new Map,this._behaviorNameToIndex=new Map,this._usedBehaviorCtors=new Set,this._customActionMap=new Map,this._solStack=C3.New(C3.SolStack,this),this._defaultInstanceData=null,this._defaultLayerIndex=0,this._isContained=!1,this._container=null,this._imageInfo=null,this._animations=null,this._animationsByName=null,this._animationsBySid=null,this._textureRefCount=0,this._savedData=new Map,this._unsavedData=new Map,this._instances=[],this._worldInfosByLayer=new Map,this._iidsStale=!0,this._plugin.HasEffects()&&(this._effectList=C3.New(C3.EffectList,this,s[12])),s[6]&&(this._imageInfo=C3.New(C3.ImageInfo),this._imageInfo.LoadData(s[6])),s[7]){this._animations=s[7].map((t=>C3.New(C3.AnimationInfo,t))),this._animationsByName=new Map,this._animationsBySid=new Map;for(const t of this._animations)this._animationsByName.set(t.GetName().toLowerCase(),t),this._animationsBySid.set(t.GetSID(),t)}this._isFamily?(this._familyMembers=[],this._familyMembersSet=new Set,this._familyIndex=this._runtime._GetNextFamilyIndex()):(this._families=[],this._familiesSet=new Set,this._familyInstVarMap=[],this._familyBehaviorMap=[],this._familyEffectMap=[]);const r=this._plugin.GetSdkVersion();if(r<2&&(this._sdkType=C3.New(i.Type,this,s[15]),!(this._sdkType instanceof C3.SDKTypeBase)))throw new Error("v1 sdk type must derive from SDKTypeBase");let o;if(this._iObjectClass=null,this._instanceUserScriptClass=null,this._userScriptDispatcher=C3.New(C3.Event.Dispatcher),C3.AddonManager._PushInitObject(this,r),r>=2?(o=i.Type,o||(o=globalThis.ISDKObjectTypeBase)):o=this._sdkType.GetScriptInterfaceClass(),o&&!this._isFamily){if(this._iObjectClass=new o(r<2?this:null),r<2&&!(this._iObjectClass instanceof IObjectType))throw new TypeError("script interface class must derive from IObjectType");if(r>=2&&!(this._iObjectClass instanceof globalThis.ISDKObjectTypeBase))throw new TypeError("script interface class must derive from ISDKObjectTypeBase")}else{const t=this._isFamily?IFamily:IObjectType;this._iObjectClass=new t}if(C3.AddonManager._PopInitObject(r),s[13]){const t=s[13];if(t){const e=t[0],s=t[1],i=t[2];this._sdkType.LoadTilemapData(e,s,i)}}this._runtime.UsesLoaderLayout()&&!this._isFamily&&!this._isOnLoaderLayout&&this._isWorldType||this.OnCreate(),this._plugin.IsSingleGlobal()&&(this._plugin._SetSingleGlobalObjectClass(this),this._CreateSingleGlobalInstance(s)),this._loadInstancesJson=null}static Create(t,e,s){return C3.New(C3.ObjectClass,t,e,s)}Release(){if(this._dispatcher.Release(),this._dispatcher=null,this._imageInfo&&(this._imageInfo.Release(),this._imageInfo=null),this._animations){for(const t of this._animations)t.Release();C3.clearArray(this._animations),this._animationsByName.clear(),this._animationsBySid.clear()}this._loadInstancesJson=null,this._solStack.Release(),this._solStack=null,this._savedData.clear(),this._unsavedData.clear(),this._container=null,this._runtime=null}_LoadFamily(t){for(let e=1,s=t.length;e<s;++e){const s=this._runtime.GetObjectClassByIndex(t[e]);this._familyMembers.push(s),this._familyMembersSet.add(s),s._families.push(this),s._familiesSet.add(this)}}_SetContainer(t){this._isInContainer=!0,this._container=t}IsInContainer(){return this._isInContainer}GetContainer(){return this._container}_OnAfterCreate(){let t=0;if(!this._isFamily)for(const e of this._families)for(const s of e.GetBehaviorTypes()){const e=s.GetName().toLowerCase();this._behaviorsByName.set(e,s),this._behaviorNameToIndex.set(e,t),this._behaviorTypesIncludingInherited.push(s),++t}for(const e of this.GetBehaviorTypes()){const s=e.GetName().toLowerCase();this._behaviorsByName.set(s,e),this._behaviorNameToIndex.set(s,t),this._behaviorTypesIncludingInherited.push(e),++t}for(const t of this._behaviorTypesIncludingInherited)this._usedBehaviorCtors.add(t.GetBehavior().constructor);if(!this._isFamily&&this._families.length){const t=this._runtime.GetFamilyCount();C3.extendArray(this._familyInstVarMap,t,0),C3.extendArray(this._familyBehaviorMap,t,0),C3.extendArray(this._familyEffectMap,t,0);const e=[];let s=0,i=0,n=0;for(const t of this._families){const a=t.GetFamilyIndex();this._familyInstVarMap[a]=s,s+=t.GetInstanceVariablesCount(),this._familyBehaviorMap[a]=i,i+=t.GetBehaviorTypesCount(),this._familyEffectMap[a]=n,n+=t.GetEffectTypesCount();const r=t.GetEffectList();if(r&&this._effectList)for(const t of r.GetAllEffectTypes())e.push(t.Clone(this._effectList))}this._effectList&&this._effectList.PrependEffectTypes(e)}}_CreateSingleGlobalInstance(t){const e=C3.IsFiniteNumber(t[17])?t[17]:this._runtime._GetNewUID(),s=C3.New(C3.Instance,{runtime:this._runtime,objectType:this,uid:e});s._CreateSdkInstance(t[16],[]),this._runtime._MapInstanceByUID(e,s),this._instances.push(s)}GetSdkType(){return this._sdkType}IsOnLoaderLayout(){return this._isOnLoaderLayout}Dispatcher(){return this._dispatcher}OnCreate(){this._isFamily||(this._sdkType?this._sdkType.OnCreate():this._iObjectClass._onCreate())}HasLoadedTextures(){return this._textureRefCount>0}async LoadTextures(t){this._isFamily||(this._textureRefCount++,1===this._textureRefCount&&(this._sdkType?await this._sdkType.LoadTextures(t):await this._iObjectClass._loadTextures(this._runtime.GetCanvasManager().GetIRenderer())))}ReleaseTextures(){if(!this._isFamily){if(this._textureRefCount--,this._textureRefCount<0)throw new Error("released textures too many times");0===this._textureRefCount&&(this._sdkType?this._sdkType.ReleaseTextures():this._iObjectClass._releaseTextures(this._runtime.GetCanvasManager().GetIRenderer()))}}OnDynamicTextureLoadComplete(){if(this._isFamily)throw new Error("not applicable to family");this._sdkType?this._sdkType.OnDynamicTextureLoadComplete():this._iObjectClass._onDynamicTextureLoadComplete()}async PreloadTexturesWithInstances(t){this._isFamily||(this._sdkType?await this._sdkType.PreloadTexturesWithInstances(t):await this._iObjectClass._preloadTexturesWithInstances(this._runtime.GetCanvasManager().GetIRenderer()))}GetRuntime(){return this._runtime}GetPlugin(){return this._plugin}GetInstanceSdkCtor(){return this._instSdkCtor}GetName(){return this._name}GetJsPropName(){return this._jsPropName}GetIndex(){return this._index}GetSID(){return this._sid}IsFamily(){return this._isFamily}IsGlobal(){return this._isGlobal}IsWorldType(){return this._isWorldType}GetFamilyIndex(){return this._familyIndex}GetBehaviorTypes(){return this._behaviorTypes}GetBehaviorTypesCount(){return this._behaviorsCount}UsesBehaviorByCtor(t){return t&&this._usedBehaviorCtors.has(t)}GetInstanceVariablesCount(){return this._instVars.length}GetInstanceVariableSIDs(){return this._instVars.map((t=>t.sid))}GetInstanceVariableIndexBySID(t){return this._instVars.findIndex((e=>e.sid===t))}GetInstanceVariableIndexByName(t){return this._instVars.findIndex((e=>e.name===t))}_GetAllInstanceVariableNames(){return this._instVars.map((t=>t.name))}_GetAllInstanceVariableJsPropNames(){return this._instVars.map((t=>t.jsPropName))}GetInstanceVariableType(t){if((t=Math.floor(t))<0||t>=this._instVars.length)throw new RangeError("invalid instance variable index");return this._instVars[t].type}GetInstanceVariableName(t){if((t=Math.floor(t))<0||t>=this._instVars.length)throw new RangeError("invalid instance variable index");return this._instVars[t].name}GetEffectTypesCount(){return this._effectsCount}GetBehaviorTypesIncludingInherited(){return this._behaviorTypesIncludingInherited}GetBehaviorTypeByName(t){return this._behaviorsByName.get(t.toLowerCase())||null}GetBehaviorIndexByName(t){const e=this._behaviorNameToIndex.get(t.toLowerCase());return void 0===e?-1:e}GetEffectList(){return this._effectList}HasEffects(){return this._plugin.HasEffects()}UsesEffects(){return this._effectList&&this._effectList.HasAnyEffectType()}GetSolStack(){return this._solStack}GetCurrentSol(){return this._solStack.GetCurrentSol()}GetImageInfo(){return this._imageInfo}SetDefaultInstanceData(t){this._defaultInstanceData=t}GetDefaultInstanceData(){return this._defaultInstanceData}_SetDefaultLayerIndex(t){this._defaultLayerIndex=t}GetDefaultLayerIndex(){return this._defaultLayerIndex}GetAnimations(){return this._animations}GetAnimationCount(){return this._animations.length}GetFamilies(){return this._families}BelongsToFamily(t){return this._familiesSet.has(t)}GetFamilyMembers(){return this._familyMembers}FamilyHasMember(t){return this._familyMembersSet.has(t)}GetFamilyBehaviorOffset(t){return this._familyBehaviorMap[t]}GetFamilyInstanceVariableOffset(t){return this._familyInstVarMap[t]}AddCustomAction(t){this._customActionMap.set(t.GetACEName().toLowerCase(),t)}HasOwnCustomActionByName(t){return!!this.GetOwnCustomActionByName(t)}GetOwnCustomActionByName(t){const e=this._customActionMap.get(t.toLowerCase());return e&&e.IsEnabled()?e:null}GetAllAnimations(){return this._animations}GetAnimationByName(t){if(!this._animations)throw new Error("no animations");return this._animationsByName.get(t.toLowerCase())||null}GetAnimationBySID(t){if(!this._animations)throw new Error("no animations");return this._animationsBySid.get(t)||null}AddAnimation(t){if(this.GetAnimationByName(t))throw new Error(`animation name '${t}' already exists`);const e=C3.AnimationInfo.CreateDynamic(this.GetRuntime(),t);return this._animations.push(e),this._animationsByName.set(e.GetName().toLowerCase(),e),this._animationsBySid.set(e.GetSID(),e),e}RemoveAnimation(t){const e=this.GetAnimationByName(t);if(!e)throw new Error(`animation name '${t}' does not exist`);if(1===this._animations.length)throw new Error("cannot remove last animation");const s=this._animations.indexOf(e);this._animations.splice(s,1),this._animationsByName.delete(e.GetName().toLowerCase()),this._animationsBySid.delete(e.GetSID()),e.Release()}GetFirstAnimation(){if(!this._animations)throw new Error("no animations");return this._animations[0]}GetFirstAnimationFrame(){return this.GetFirstAnimation().GetFrameAt(0)}GetDefaultInstanceSize(){if(this._animations){const t=this.GetFirstAnimationFrame().GetImageInfo();return[t.GetWidth(),t.GetHeight()]}return this._imageInfo?[this._imageInfo.GetWidth(),this._imageInfo.GetHeight()]:[100,100]}GetSingleGlobalInstance(){if(!this._plugin.IsSingleGlobal())throw new Error("not a single-global plugin");return this._instances[0]}GetInstances(){return this._instances}*instances(){yield*this._instances}*instancesIncludingPendingCreate(){yield*this._instances,yield*this._runtime.instancesPendingCreateForObjectClass(this)}GetInstanceCount(){return this._instances.length}_AddInstance(t){this._instances.push(t)}_SetIIDsStale(){this._iidsStale=!0}_UpdateIIDs(){if(!this._iidsStale||this._isFamily)return;const t=this._instances;let e=0;for(let s=t.length;e<s;++e)t[e]._SetIID(e);const s=this._runtime._GetInstancesPendingCreate();for(const t of s)t.GetObjectClass()===this&&t._SetIID(e++);this._iidsStale=!1}GetInstanceByIID(t){const e=this._instances;if(t<e.length)return e[t];t-=e.length;const s=this._runtime._GetInstancesPendingCreate();for(const e of s)if(e.GetObjectClass()===this){if(0===t)return e;--t}return null}GetFirstPicked(t){if(t&&t.IsInContainer()&&t.GetObjectClass()!==this)for(const e of t.siblings())if(e.GetObjectClass()===this)return e;const e=this.GetCurrentSol().GetInstances();return e.length?e[0]:null}GetPairedInstance(t){const e=this.GetCurrentSol().GetInstances();return e.length>0?e[t.GetIID()%e.length]:null}*allCorrespondingInstances(t,e){const s=this.GetCurrentSol().GetInstances(),i=s.length,n=e.GetCurrentSol(),a=e.GetCurrentSol().GetInstances(),r=a.length;let o=t.GetIID();!e.IsFamily()&&n.IsSelectAll()||(o=a.indexOf(t));const h=Math.ceil(i/r),l=i%r;let _=0,c=0;0===l||o<l?(_=o*h,c=h):(_=l*h+(o-l)*(h-1),c=h-1);for(let t=_,e=_+c;t<e;++t)yield s[t]}FinishCondition(t){this._sdkType?.FinishCondition(t)}ApplySolToContainer(){if(!this._isInContainer||this._isFamily)return;this._UpdateIIDs();const t=this.GetCurrentSol(),e=t._GetOwnInstances(),s=t.IsSelectAll(),i=this._runtime.GetCurrentEventStackFrame(),n=i&&i.GetCurrentEvent()&&i.GetCurrentEvent().IsOrBlock();for(const i of this._container.objectTypes()){if(i===this)continue;i._UpdateIIDs();const a=i.GetCurrentSol();if(a._SetSelectAll(s),!s){const s=a._GetOwnInstances();C3.clearArray(s);for(const t of e)s.push(i.GetInstanceByIID(t.GetIID()));if(n){const e=t._GetOwnElseInstances(),s=a._GetOwnElseInstances();C3.clearArray(s);for(const t of e)s.push(i.GetInstanceByIID(t.GetIID()))}}}}_TruncateContainerSols(t,e){for(const s of this.GetContainer().objectTypes()){const i=s.GetCurrentSol();t?C3.truncateArray(i._GetOwnElseInstances(),e):C3.truncateArray(i._GetOwnInstances(),e)}}_GetCollisionCellGrid(){return this._collisionGrid}_SetAnyCollisionCellChanged(t){this._anyCollisionCellChanged=!!t}_UpdateAllCollisionCells(){if(this._anyCollisionCellChanged&&this._isWorldType){for(const t of this._instances)t.GetWorldInfo()._UpdateCollisionCell();for(const t of this._runtime._GetInstancesPendingCreate())t.GetObjectClass()===this&&t.GetWorldInfo()._UpdateCollisionCell();this._anyCollisionCellChanged=!1}}_OnWorldInstanceLayerChanged(t,e,s){if(e){const s=this._worldInfosByLayer.get(e);s&&(s.delete(t),0===s.size&&this._worldInfosByLayer.delete(e))}if(s){let e=this._worldInfosByLayer.get(s);e||(e=new Set,this._worldInfosByLayer.set(s,e)),e.add(t)}}*layersHasInstancesOn(){if(this.IsFamily()){const t=new Set;for(const e of this._familyMembers)for(const s of e.layersHasInstancesOn())t.add(s);yield*t.values()}else for(const t of this._worldInfosByLayer.keys())t.WasReleased()||(yield t)}GetSavedDataMap(){return this._savedData||(this._savedData=new Map),this._savedData}GetUnsavedDataMap(){return this._unsavedData||(this._unsavedData=new Map),this._unsavedData}HasSolidBehavior(){return this.UsesBehaviorByCtor(C3.Behaviors.solid)}HasJumpthruBehavior(){return this.UsesBehaviorByCtor(C3.Behaviors.jumpthru)}HasNoSaveBehavior(){return this.UsesBehaviorByCtor(C3.Behaviors.NoSave)}HasPersistBehavior(){return this.UsesBehaviorByCtor(C3.Behaviors.Persist)}_SaveToJson(){const t={"instances":this._instances.map((t=>t.SaveToJson()))};return this._savedData&&this._savedData.size&&(t["ex"]=C3.ToSuperJSON(this._savedData)),t}_LoadFromJson(t,e){this._savedData&&(this._savedData.clear(),this._savedData=null);const s=t["ex"];s&&(this._savedData=C3.FromSuperJSON(s));const i=this._instances,n=t["instances"];for(let t=0,e=Math.min(i.length,n.length);t<e;++t)i[t].LoadFromJson(n[t]);for(let t=n.length,e=i.length;t<e;++t)this._runtime.DestroyInstance(i[t]);for(let t=i.length,s=n.length;t<s;++t){const s=n[t];let i=null;if(this.IsWorldType()&&(i=this._runtime.GetMainRunningLayout().GetLayerBySID(s["w"]["l"]),!i))continue;const a=this._runtime.CreateInstanceFromData(this._defaultInstanceData||this,i,!1,0,0,!0);a.LoadFromJson(s),e&&e.add(a)}this._loadInstancesJson=n,this._SetIIDsStale()}_GetLoadInstancesJson(){return this._loadInstancesJson}_ClearLoadInstancesJson(){this._loadInstancesJson=null}_SetupSceneGraphConnectionsOnChangeOfLayout(){for(let t=0,e=this._instances;t<e;++t)this._instances[t]._SetupSceneGraphConnectionsOnChangeOfLayout()}GetIObjectClass(){return this._iObjectClass}UserScriptDispatcher(){return this._userScriptDispatcher}_GetUserScriptInstanceClass(){return this._instanceUserScriptClass}_SetUserScriptInstanceClass(t){this._instanceUserScriptClass=t}DispatchUserScriptEvent(t){const e=this._runtime,s=e.IsDebug()&&!e.GetEventSheetManager().IsInEventEngine();s&&C3Debugger.StartMeasuringScriptTime(),this._userScriptDispatcher.dispatchEvent(t),s&&C3Debugger.AddScriptTime()}};
}

// objects/container.js
{
const C3=self.C3;C3.Container=class extends C3.DefendedBase{constructor(e,t){super(),this._runtime=e,this._objectTypes=t;for(const e of this._objectTypes)e._SetContainer(this)}Release(){this._runtime=null}GetRuntime(){return this._runtime}GetObjectTypes(){return this._objectTypes}objectTypes(){return this._objectTypes}HasAnyWorldType(){return this._objectTypes.some((e=>e.IsWorldType()))}};
}

// objects/instance.js
{
const C3=self.C3,C3Debugger=self.C3Debugger,IInstance=self.IInstance,originalAddonManager=C3.AddonManager,EMPTY_ARRAY=[];let nextPuid=0;const savedDataMaps=new WeakMap,unsavedDataMaps=new WeakMap,FLAG_DESTROYED=1,FLAG_TILEMAP=2,FLAG_MUST_PREDRAW=4,FLAG_SOLID_ENABLED=8,FLAG_JUMPTHRU_ENABLED=16,FLAG_MUST_MITIGATE_Z_FIGHTING=32,FLAG_IS_DRAWING_WITH_EFFECTS=64;C3.Instance=class extends C3.DefendedBase{constructor(t){if(C3.AddonManager!==originalAddonManager)throw new Error("invalid addon manager");super(),this._runtime=t.runtime,this._objectType=t.objectType,this._worldInfo=null,this._sdkInst=null,this._iScriptInterface=null,this._iid=0,this._uid=t.uid,this._puid=nextPuid++,this._flags=0,this._tagsSet=null;const e=C3.splitStringAndNormalize(t.tags);e.length>0&&(this._tagsSet=new Set(e)),this._instVarValues=EMPTY_ARRAY,this._behaviorInstances=EMPTY_ARRAY;const s=this._objectType.GetBehaviorTypesIncludingInherited();s.length>0&&(this._behaviorInstances=s.map(((t,e)=>C3.New(C3.BehaviorInstance,{runtime:this._runtime,behaviorType:t,instance:this,index:e})))),this._siblings=this._objectType.IsInContainer()?[]:null,this._timeScale=-1,this._dispatcher=null;const n=this.GetPlugin();if(n.MustPreDraw()&&(this._flags|=4),n.IsWorldType())if(this._worldInfo=C3.New(C3.WorldInfo,this,t.layer),t.worldData)this._worldInfo.Init(t.worldData);else{this._worldInfo.InitNoData();const[t,e]=this._objectType.GetDefaultInstanceSize();this._worldInfo.SetSize(t,e),this.GetObjectClass().UsesEffects()&&this._worldInfo.GetInstanceEffectList().LoadDefaultEffectParameters()}t.instVarData?this._LoadInstanceVariableData(t.instVarData):this._LoadDefaultInstanceVariables()}Release(){if(this._iScriptInterface&&(this._iScriptInterface._release(),this._iScriptInterface=null),this._behaviorInstances.length>0){for(const t of this._behaviorInstances)t.Release();C3.clearArray(this._behaviorInstances)}this._sdkInst&&(this._sdkInst.Release(),this._sdkInst=null);const t=savedDataMaps.get(this);t&&(t.clear(),savedDataMaps.delete(this));const e=unsavedDataMaps.get(this);e&&(e.clear(),unsavedDataMaps.delete(this)),this._siblings&&C3.clearArray(this._siblings),this._dispatcher&&(this._dispatcher.Release(),this._dispatcher=null),this._tagsSet&&this._tagsSet.clear(),this._tagsSet=null,this._runtime=null,this._objectType=null,this._instVarValues.length>0&&C3.clearArray(this._instVarValues),this._worldInfo&&(this._worldInfo.Release(),this._worldInfo=null)}_LoadInstanceVariableData(t){t.length>0&&(this._instVarValues=[],C3.shallowAssignArray(this._instVarValues,t))}_LoadDefaultInstanceVariables(){const t=this._objectType.GetInstanceVariablesCount();if(0===t)return;this._instVarValues=[];const e=[0,0,""];for(let s=0;s<t;++s)this._instVarValues.push(e[this._objectType.GetInstanceVariableType(s)])}_CreateSdkInstance(t,e){if(this._sdkInst)throw new Error("already got sdk instance");for(let t=0,s=this._behaviorInstances.length;t<s;++t){this._behaviorInstances[t]._CreateSdkInstance(e?e[t]:null)}if(this.GetPlugin().GetSdkVersion()<2){if(this._sdkInst=C3.New(this._objectType.GetInstanceSdkCtor(),this,t),!(this._sdkInst instanceof C3.SDKInstanceBase))throw new Error("sdk type must derive from SDKInstanceBase");!this.GetPlugin().IsWorldType()&&this._objectType._GetUserScriptInstanceClass()&&this.GetInterfaceClass()}else{const e=this.GetPlugin().GetScriptInterfaceClass();this._InitUserScriptInterface(e.Instance,t)}}GetSdkInstance(){return this._sdkInst??this._iScriptInterface}GetWorldInfo(){return this._worldInfo}GetRuntime(){return this._runtime}GetTimeScale(){return this._timeScale}GetActiveTimeScale(){const t=this._timeScale;return-1===t?this.GetRuntime().GetTimeScale():t}SetTimeScale(t){((t=+t)<0||!isFinite(t))&&(t=0),this._timeScale=t,this.GetObjectClass().UsesEffects()&&this._runtime._SetTrackingInstanceTime(this,!0)}RestoreTimeScale(){this._timeScale=-1,this.GetObjectClass().UsesEffects()&&this._runtime._SetTrackingInstanceTime(this,!1)}GetInstanceGameTime(){return this._runtime._GetInstanceGameTime(this)}Dispatcher(){return this._dispatcher||(this._dispatcher=C3.New(C3.Event.Dispatcher)),this._dispatcher}Draw(t){this._sdkInst?this._sdkInst.Draw(t):this._iScriptInterface._draw(this._runtime.GetCanvasManager().GetIRenderer())}OnCreate(t){this._sdkInst.OnCreate(t)}_SetHasTilemap(){this._flags|=2}HasTilemap(){return!!(2&this._flags)}_MarkDestroyed(){this._flags|=1}IsDestroyed(){return!!(1&this._flags)}MustPreDraw(){return!!(4&this._flags)||this._sdkInst.MustPreDraw()}SetMustMitigateZFighting(){this._flags|=32}MustMitigateZFighting(){return!!(32&this._flags)}_IsSolidEnabled(){return!!(8&this._flags)}_SetSolidEnabled(t){t?this._flags|=8:this._flags&=-9}_IsJumpthruEnabled(){return!!(16&this._flags)}_SetJumpthruEnabled(t){t?this._flags|=16:this._flags&=-17}_IsDrawingWithEffects(){return!!(64&this._flags)}_SetIsDrawingWithEffects(t){t?this._flags|=64:this._flags&=-65}SetFlag(t,e){t<<=16,e?this._flags|=t:this._flags&=~t}GetFlag(t){return!!(this._flags&t<<16)}GetCurrentImageInfo(){return this._sdkInst.GetCurrentImageInfo()}GetCurrentSurfaceSize(){return this._sdkInst.GetCurrentSurfaceSize()}GetCurrentTexRect(){return this._sdkInst.GetCurrentTexRect()}GetCurrentTexQuad(){return this._sdkInst.GetCurrentTexQuad()}IsCurrentTexRotated(){return this._sdkInst.IsCurrentTexRotated()}GetImagePoint(t){return this._sdkInst.GetImagePoint(t)}GetObjectClass(){return this._objectType}RendersToOwnZPlane(){return this._sdkInst.RendersToOwnZPlane()}BelongsToObjectClass(t){return t.IsFamily()?t.FamilyHasMember(this.GetObjectClass()):this.GetObjectClass()===t}CollectInstancesToPick(t,e,s){const n=(e,s)=>{const n=s||e.GetObjectClass(),i=t.get(n);i?i.add(e):t.set(n,new Set([e]))};if(n(this,e),this.IsInContainer())for(const t of this.siblings())n(t);if(s)for(const t of this.allChildren())n(t)}VerifySupportsSceneGraph(){if(!this.GetPlugin().SupportsSceneGraph())throw new Error("object does not support scene graph")}HasParent(){return null!==this.GetParent()}GetParent(){const t=this.GetWorldInfo();if(!t)return null;const e=t.GetParent();return e?e.GetInstance():null}GetTopParent(){const t=this.GetWorldInfo();if(!t)return null;const e=t.GetTopParent();return e?e.GetInstance():null}*parents(){const t=this.GetWorldInfo();if(t)for(const e of t.parents())yield e.GetInstance()}HasChild(t){if(!t)return!1;for(const e of this.children())if(e===t)return!0;return!1}HasChildren(){const t=this.GetWorldInfo();return!!t&&t.HasChildren()}GetChildrenOfObjectClass(t){const e=this.GetWorldInfo();if(!e)return[];const s=t.GetName();return e.GetChildren().map((t=>t.GetInstance())).filter((t=>t.GetObjectClass().GetName()===s))}GetChildren(){const t=this.GetWorldInfo();return t?t.GetChildren().map((t=>t.GetInstance())):[]}*children(){const t=this.GetWorldInfo();if(t)for(const e of t.children())yield e.GetInstance()}*allChildren(){const t=this.GetWorldInfo();if(t)for(const e of t.allChildren())yield e.GetInstance()}GetChildCount(){const t=this.GetWorldInfo();return t?t.GetChildCount():0}GetParentCount(){return[...this.parents()].length}GetAllChildCount(){const t=this.GetWorldInfo();return t?t.GetAllChildCount():0}GetChildAt(t){const e=this.GetWorldInfo();if(!e)return null;const s=e.GetChildAt(t);return s?s.GetInstance():null}GetIndexInParent(){const t=this.GetWorldInfo();if(!t)return NaN;const e=t.GetParent();return e?e.GetChildIndex(t):NaN}HasChildWithUID(t){for(const e of this.GetWorldInfo().GetChildren())if(e.GetInstance().GetUID()===t)return!0;return!1}AddChild(t,e){this.VerifySupportsSceneGraph(),t.VerifySupportsSceneGraph(),this.GetWorldInfo().AddChild(t.GetWorldInfo(),e||{})}RemoveChild(t){const e=this.GetWorldInfo();e&&e.RemoveChild(t.GetWorldInfo())}GetDestroyWithParent(){const t=this.GetWorldInfo();return!!t&&t.GetDestroyWithParent()}SetupInitialSceneGraphConnections(){const t=this.GetWorldInfo();if(!t)return;const e=t.GetSceneGraphChildrenExportData();if(e)for(const t of e){const e=this._runtime.GetInstanceByUID(t[2]);if(e){const s=t[3];this.AddChild(e,{transformX:!!(1&s),transformY:!!(s>>1&1),transformWidth:!!(s>>2&1),transformHeight:!!(s>>3&1),transformAngle:!!(s>>4&1),destroyWithParent:!!(s>>5&1),transformZElevation:!!(s>>6&1),transformOpacity:!!(s>>7&1),transformVisibility:!!(s>>8&1)})}}}SetupPersistedSceneGraphConnections(t,e){const s=t.get(this);if(s)for(const t of s["sceneGraphJson"]["children"]){const s=e.get(t["index"]);if(!s)continue;const n=t["flags"];this.AddChild(s,{transformX:!!(1&n),transformY:!!(n>>1&1),transformWidth:!!(n>>2&1),transformHeight:!!(n>>3&1),transformAngle:!!(n>>4&1),destroyWithParent:!!(n>>5&1),transformZElevation:!!(n>>6&1),transformOpacity:!!(n>>7&1),transformVisibility:!!(n>>8&1)})}}GetTemplateName(){const t=this._runtime.GetTemplateManager();return t?t.GetInstanceTemplateName(this):""}IsInContainer(){return null!==this._siblings}_ClearSiblings(){C3.clearArray(this._siblings)}_AddSibling(t){this._siblings.push(t)}GetSiblings(){return this._siblings}HasSibling(t){return!!this.GetSibling(t)}GetSibling(t){const e=this.siblings();if(null===e||0===e.length)return!1;for(const s of e)if(s.GetObjectClass()===t)return s;return null}siblings(){return this._siblings}SetSiblingsSinglePicked(){for(const t of this.siblings())t.GetObjectClass().GetCurrentSol().SetSinglePicked(t)}_PushSiblingsToSolInstances(){for(const t of this.siblings())t.GetObjectClass().GetCurrentSol()._PushInstance(t)}_SetSiblingsToSolInstancesIndex(t){for(const e of this.siblings())e.GetObjectClass().GetCurrentSol()._GetOwnInstances()[t]=e}_PushSiblingsToSolElseInstances(){for(const t of this.siblings())t.GetObjectClass().GetCurrentSol()._PushElseInstance(t)}_SetSiblingsToSolElseInstancesIndex(t){for(const e of this.siblings())e.GetObjectClass().GetCurrentSol()._GetOwnElseInstances()[t]=e}GetPlugin(){return this._objectType.GetPlugin()}_SetIID(t){this._iid=t}GetIID(){return this._objectType._UpdateIIDs(),this._iid}GetUID(){return this._uid}SetUID(t){this._uid=t}GetPUID(){return this._puid}_SetTagsSetFromJson(t){t?this.SetTagsSet(new Set(t)):this._tagsSet=null}SetTagsSet(t){if(0===t.size)this._tagsSet=null;else{this._tagsSet?this._tagsSet.clear():this._tagsSet=new Set;for(const e of t)this._tagsSet.add(e)}}GetTagsSet(){return this._tagsSet??new Set}GetTagsString(){return Array.from(this.GetTagsSet()).join(" ")}GetTagAt(t){t=Math.floor(t);for(const e of this.GetTagsSet()){if(0===t)return e;--t}return""}GetBehaviorInstances(){return this._behaviorInstances}GetBehaviorInstanceFromCtor(t){if(!t)return null;for(const e of this._behaviorInstances)if(e.GetBehavior()instanceof t)return e;return null}GetBehaviorSdkInstanceFromCtor(t){if(!t)return null;const e=this.GetBehaviorInstanceFromCtor(t);return e?e.GetSdkInstance():null}GetBehaviorIndexBySID(t){const e=this._behaviorInstances;for(let s=0,n=e.length;s<n;++s)if(e[s].GetBehaviorType().GetSID()===t)return s;return-1}GetAllInstanceVariableValues(){return this._instVarValues}_GetAllInstanceVariableNames(){return this._objectType._GetAllInstanceVariableNames()}GetInstanceVariableCount(){return this._instVarValues.length}GetInstanceVariableValue(t){t|=0;const e=this._instVarValues;if(t<0||t>=e.length)throw new RangeError("invalid instance variable");return e[t]}_GetInstanceVariableValueUnchecked(t){return this._instVarValues[t]}_GetInstanceVariableTypedValue(t){const e=this._instVarValues[t];return 0===this._objectType.GetInstanceVariableType(t)?!!e:e}SetInstanceVariableValue(t,e){t|=0;const s=this._instVarValues;if(t<0||t>=s.length)throw new RangeError("invalid instance variable");switch(this._objectType.GetInstanceVariableType(t)){case 0:s[t]=e?1:0;break;case 1:s[t]="number"==typeof e?e:parseFloat(e);break;case 2:s[t]="string"==typeof e?e:e.toString();break;default:throw new Error("unknown instance variable type")}}SetInstanceVariableOffset(t,e){if(0===e)return;t|=0;const s=this._instVarValues;if(t<0||t>=s.length)throw new RangeError("invalid instance variable");const n=s[t];if("number"!=typeof n)throw"boolean"==typeof n?new Error("can not set offset of boolean variable"):"string"==typeof n?new Error("can not set offset of string variable"):new Error("unknown instance variable type");s[t]+="number"==typeof e?e:parseFloat(e)}GetSavedDataMap(){let t=savedDataMaps.get(this);return t||(t=new Map,savedDataMaps.set(this,t),t)}GetUnsavedDataMap(){let t=unsavedDataMaps.get(this);return t||(t=new Map,unsavedDataMaps.set(this,t),t)}_HasAnyCreateDestroyHandler(t){const e=this.GetObjectClass();if(e.UserScriptDispatcher().HasAnyHandlerFor(t))return!0;for(const s of e.GetFamilies())if(s.UserScriptDispatcher().HasAnyHandlerFor(t))return!0;return!!this._runtime.UserScriptDispatcher().HasAnyHandlerFor(t)}_TriggerOnCreatedOnSelfAndRelated(t=void 0){const e=t??new Set;if(e.has(this))return;e.add(this);const s=this.GetWorldInfo();if(s&&s.HasChildren())for(const t of this.allChildren())if(e.add(t),t.IsInContainer())for(const s of t.siblings())e.add(s);if(this.IsInContainer())for(const t of this.siblings())t._TriggerOnCreatedOnSelfAndRelated(e);if(!t){for(const t of e.values())t._TriggerOnCreated();this._OnHierarchyReady()}}_OnCreatedCommon(){this._objectType._GetUserScriptInstanceClass()&&this.GetInterfaceClass();for(const t of this._behaviorInstances)t.PostCreate()}_OnCreatedForLoadingSavegame(){this._OnCreatedCommon()}_TriggerOnCreated(){if(this._OnCreatedCommon(),this._HasAnyCreateDestroyHandler("instancecreate")){const t=this.GetObjectClass(),e=new C3.Event("instancecreate");e.instance=this.GetInterfaceClass(),t.DispatchUserScriptEvent(e);for(const s of t.GetFamilies())s.DispatchUserScriptEvent(e);this._runtime.DispatchUserScriptEvent(e)}this._runtime.Trigger(this.GetPlugin().GetConstructor().Cnds.OnCreated,this,null)}_OnHierarchyReady(){if(this.GetPlugin().SupportsSceneGraph()){if(this.DispatchUserScriptEvent(new C3.Event("hierarchyready")),this._HasAnyCreateDestroyHandler("hierarchyready")){const t=this.GetObjectClass(),e=new C3.Event("hierarchyready");e.instance=this.GetInterfaceClass(),t.DispatchUserScriptEvent(e);for(const s of t.GetFamilies())s.DispatchUserScriptEvent(e);this._runtime.DispatchUserScriptEvent(e)}this._runtime.Trigger(this.GetPlugin().GetConstructor().Cnds.OnHierarchyReady,this,null)}}_TriggerOnDestroyed(){this._runtime.Trigger(this.GetPlugin().GetConstructor().Cnds.OnDestroyed,this,null)}_FireDestroyedScriptEvents(t){if(this._iScriptInterface){const e=new C3.Event("destroy");e.isEndingLayout=t,this.DispatchUserScriptEvent(e)}if(!this._HasAnyCreateDestroyHandler("instancedestroy"))return;const e=this.GetObjectClass(),s=new C3.Event("instancedestroy");s.instance=this.GetInterfaceClass(),s.isEndingLayout=t,e.DispatchUserScriptEvent(s);for(const t of e.GetFamilies())t.DispatchUserScriptEvent(s);this._runtime.DispatchUserScriptEvent(s)}_GetDebuggerProperties(){return this._sdkInst?this._sdkInst.GetDebuggerProperties():this._iScriptInterface._getDebuggerProperties()}SaveToJson(t="full",e=null){const s={};"full"===t?s["uid"]=this.GetUID():s["c3"]=!0;const n=this.GetTagsSet();if(n.size>0&&(s["tags"]=Array.from(n)),"visual-state"!==t){const e=savedDataMaps.get(this);if(e&&e.size&&(s["ex"]=C3.ToSuperJSON(e)),-1!==this.GetTimeScale()&&(s["mts"]=this.GetTimeScale()),this._objectType.GetInstanceVariablesCount()>0){const t={},e=this._objectType.GetInstanceVariableSIDs();for(let s=0,n=this._instVarValues.length;s<n;++s)t[e[s].toString()]=this._instVarValues[s];s["ivs"]=t}if(this._behaviorInstances.length){const e={};for(const s of this._behaviorInstances){const n=s.SaveToJson(t);n&&(e[s.GetBehaviorType().GetSID().toString()]=n)}s["behs"]=e}}this._worldInfo&&(s["w"]=this._worldInfo._SaveToJson(t,e));const i=this._sdkInst?this._sdkInst.SaveToJson():this._iScriptInterface._saveToJson();return i&&(s["data"]=i),s}_OnBeforeLoad(t="full",e=null){this._worldInfo&&this._worldInfo._OnBeforeLoad(t)}_OnAfterLoad(t,e="full",s=null){this._worldInfo&&this._worldInfo._OnAfterLoad(t,e,s)}_OnAfterLoad2(t,e="full",s=null){this._worldInfo&&this._worldInfo._OnAfterLoad2(t,e,s)}_SetupSceneGraphConnectionsOnChangeOfLayout(){this.GetPlugin().IsWorldType()&&this._worldInfo._SetupSceneGraphConnectionsOnChangeOfLayout()}LoadFromJson(t,e="full",s=null){if("full"===e)this._uid=t["uid"];else if(!t["c3"])return;if(this._SetTagsSetFromJson(t["tags"]),"visual-state"!==e){let e=savedDataMaps.get(this);e&&(e.clear(),savedDataMaps.delete(this));const s=t["ex"];s&&(e=C3.FromSuperJSON(s),savedDataMaps.set(this,e)),this._timeScale=t.hasOwnProperty("mts")?t["mts"]:-1;const n=t["ivs"];if(n)for(const[t,e]of Object.entries(n)){const s=parseInt(t,10),n=this._objectType.GetInstanceVariableIndexBySID(s);if(n<0||n>=this._instVarValues.length)continue;let i=e;null===i&&(i=NaN),this._instVarValues[n]=i}}if(this.GetPlugin().IsWorldType()){const n=t["w"];if(n){const t=n["l"];if(this._worldInfo.GetLayer().GetSID()!==t){const s=this._worldInfo.GetLayer(),n=s.GetLayout().GetLayerBySID(t);n?(this._worldInfo._SetLayer(n),s._RemoveInstance(this,!0),n._AddInstance(this,!0),n.SetZIndicesChanged(this),this._worldInfo.SetBboxChanged()):"full"===e&&this._runtime.DestroyInstance(this)}this._worldInfo._LoadFromJson(n,e,s)}}if("visual-state"!==e){const s=t["behs"];if(s)for(const[t,n]of Object.entries(s)){const s=parseInt(t,10),i=this.GetBehaviorIndexBySID(s);i<0||i>=this._behaviorInstances.length||this._behaviorInstances[i].LoadFromJson(n,e)}}const n=t["data"];n&&(this._sdkInst?this._sdkInst.LoadFromJson(n,e):this._iScriptInterface._loadFromJson(n))}MoveToLayerWithSID(t){if(this._worldInfo.GetLayer().GetSID()===t)return;const e=this._worldInfo.GetLayer(),s=e.GetLayout().GetLayerBySID(t);s&&(this._worldInfo._SetLayer(s),e._RemoveInstance(this,!0),s._AddInstance(this,!0),s.SetZIndicesChanged(this),this._worldInfo.SetBboxChanged())}GetInterfaceClass(){return this._iScriptInterface||this._InitUserScriptInterface()}HasScriptInterface(){return!!this._iScriptInterface}_InitUserScriptInterface(t,e){const s=this._worldInfo?t?self.ISDKWorldInstanceBase:self.IWorldInstance:t?self.ISDKInstanceBase:self.IInstance,n=t||this._sdkInst.GetScriptInterfaceClass(),i=this._objectType._GetUserScriptInstanceClass(),r=i||n||s,a=this.GetPlugin().GetSdkVersion();if(C3.AddonManager._PushInitObject(this,a),C3.AddonManager._PushInitProperties(e),this._iScriptInterface=new r,C3.AddonManager._PopInitProperties(),C3.AddonManager._PopInitObject(a),n&&!(this._iScriptInterface instanceof s))throw new TypeError(`script interface class '${n.name}' does not extend the right base class '${s.name}'`);if(i){const t=n||s;if(!(this._iScriptInterface instanceof t))throw new TypeError(`setInstanceClass(): class '${i.name}' does not extend the right base class - check it extends the right class, e.g. globalThis.InstanceType.MyObjectName`)}return this._iScriptInterface}_GetInstVarsScriptDescriptor(t){if(0===this._instVarValues.length)return;const e={},s=this._objectType._GetAllInstanceVariableJsPropNames();for(let t=0,n=s.length;t<n;++t)e[s[t]]={configurable:!1,enumerable:!0,get:C3.Instance.prototype._GetInstanceVariableTypedValue.bind(this,t),set:C3.Instance.prototype.SetInstanceVariableValue.bind(this,t)};const n=Object.create(Object.prototype,e);t.instVars={value:n,writable:!1}}_GetBehaviorsScriptDescriptor(t){const e=this._behaviorInstances;if(0===e.length)return;const s={};for(const t of e)s[t.GetBehaviorType().GetJsPropName()]={value:t.GetScriptInterface(),writable:!1};const n=Object.create(Object.prototype,s);t.behaviors={value:n,writable:!1}}DispatchUserScriptEvent(t){if(!this.HasScriptInterface())return;const e=this.GetInterfaceClass();t.instance=e;const s=this._runtime,n=s.IsDebug()&&!s.GetEventSheetManager().IsInEventEngine();n&&C3Debugger.StartMeasuringScriptTime(),e.dispatchEvent(t),n&&C3Debugger.AddScriptTime()}};
}

// objects/sceneGraphInfo.js
{
const C3=self.C3,updatedInstances=new Map;C3.SceneGraphInfo=class extends C3.DefendedBase{constructor(t){super(),this._owner=t,this._parent=null,this._children=[],this._startWidth=t.GetWidth(),this._startHeight=t.GetHeight(),this._startScaleX=1,this._startScaleY=1,this._parentStartAngle=0,this._ownOpacity=1,this._startOpacity=t.GetOpacity(),this._tmpSceneGraphChildren=null,this._tmpSceneGraphChildrenIndexes=null,this._indexInParent=NaN,this._originalSizeKnown=!1,this._originalWidth=NaN,this._originalHeight=NaN,this._on_instance_create=e=>{if(e.instance!==this._parent.GetInstance())return;t.GetRuntime().Dispatcher().removeEventListener("instancecreate",this._on_instance_create);const n=this._parent.GetInstance().GetSdkInstance();this._originalSizeKnown=!!n.IsOriginalSizeKnown(),this._originalWidth=this._originalSizeKnown?n.GetOriginalWidth():NaN,this._originalHeight=this._originalSizeKnown?n.GetOriginalHeight():NaN}}Release(){this._parent=null,this._tmpSceneGraphChildren=null,this._tmpSceneGraphChildrenIndexes=null,this._indexInParent=NaN,this._originalSizeKnown=!1,this._originalWidth=NaN,this._originalHeight=NaN,C3.clearArray(this._children)}SetParent(t){if(this._ownOpacity=this._owner.GetOpacity(),this._startOpacity=this._ownOpacity,this._parent=t,this._parentStartAngle=t?t.GetAngle():0,this._parent){const t=this._owner.GetRuntime();if(this._parent.GetInstance().GetPlugin().GetSdkVersion()<2){const e=this._parent.GetInstance().GetSdkInstance();e?(this._originalSizeKnown=!!e.IsOriginalSizeKnown(),this._originalWidth=this._originalSizeKnown?e.GetOriginalWidth():NaN,this._originalHeight=this._originalSizeKnown?e.GetOriginalHeight():NaN):this._parent.GetInstance().IsDestroyed()||t.Dispatcher().addEventListener("instancecreate",this._on_instance_create)}else this._originalSizeKnown=!1,this._originalWidth=NaN,this._originalHeight=NaN}else this._originalSizeKnown=!1,this._originalWidth=NaN,this._originalHeight=NaN}GetParent(){return this._parent}HasChildren(){return this._children.length>0}GetChildren(){return this._children}_MaybeSortChildren(){this.HasChildren()&&1!==this._children.length&&(this._tmpSceneGraphChildrenIndexes?this._children.sort(((t,e)=>{const n=this._tmpSceneGraphChildrenIndexes.get(t.GetInstance()),s=this._tmpSceneGraphChildrenIndexes.get(e.GetInstance());return C3.IsFiniteNumber(n)&&C3.IsFiniteNumber(s)?n-s:0})):this._children.sort(((t,e)=>{const n=t._GetSceneGraphInfo()._GetIndexInParent(),s=e._GetSceneGraphInfo()._GetIndexInParent();return C3.IsFiniteNumber(n)&&C3.IsFiniteNumber(s)?n-s:0})))}_GetIndexInParent(){return this._indexInParent}GetStartScaleX(){return this._startScaleX}SetStartScaleX(t){this._startScaleX=t}GetStartScaleY(){return this._startScaleY}SetStartScaleY(t){this._startScaleY=t}GetStartOpacity(){return this._startOpacity}GetOwnOpacity(){return this._ownOpacity}SetOwnOpacity(t){this._ownOpacity=t}_GetStartWidth(){return 0===this._startWidth?Number.EPSILON:this._startWidth}_GetStartHeight(){return 0===this._startHeight?Number.EPSILON:this._startHeight}GetParentScaleX(){if(this._owner.GetTransformWithParentWidth()){const t=this._parent;let e=t.GetWidth(),n=t._GetSceneGraphInfo()._GetStartWidth();return 0===e&&(e=Number.EPSILON),n===Number.EPSILON&&e===Number.EPSILON?1:n===Number.EPSILON&&e!==Number.EPSILON&&this._originalSizeKnown?1+e/this._originalWidth:e/n}return 1}GetParentScaleY(){if(this._owner.GetTransformWithParentHeight()){const t=this._parent;let e=t.GetHeight(),n=t._GetSceneGraphInfo()._GetStartHeight();return 0===e&&(e=Number.EPSILON),n===Number.EPSILON&&e===Number.EPSILON?1:n===Number.EPSILON&&e!==Number.EPSILON&&this._originalSizeKnown?1+e/this._originalHeight:e/n}return 1}GetParentStartAngle(){return 0}_SaveToJsonProperties(){return{"sw":this._startWidth,"sh":this._startHeight,"sx":this._startScaleX,"sy":this._startScaleY,"psa":this._parentStartAngle,"oo":this._ownOpacity,"so":this._startOpacity,"pi":this._owner.GetInstance().GetIndexInParent()}}_SaveToJson(t,e=null){const n=this._SaveToJsonProperties();return e&&e["selfOnly"]?Object.assign(n,{"p":null,"c":[]}):Object.assign(n,{"p":this._GetParentJson(t),"c":this._GetChildrenJson(t)})}_GetFlagsString(t){let e="";return t.GetTransformWithParentX()&&(e+="x"),t.GetTransformWithParentY()&&(e+="y"),t.GetTransformWithParentWidth()&&(e+="w"),t.GetTransformWithParentHeight()&&(e+="h"),t.GetTransformWithParentAngle()&&(e+="a"),t.GetTransformWithParentZElevation()&&(e+="z"),t.GetDestroyWithParent()&&(e+="d"),t.GetTransformWithParentOpacity()&&(e+="o"),t.GetTransformWithParentVisibility()&&(e+="v"),e}_GetParentJson(t){return this._parent?!this._parent.GetInstance()||this._parent.GetInstance().IsDestroyed()?null:this._GetInstanceJson(this._parent,this._owner,t):null}_GetChildrenJson(t){return this._children.map((e=>this._GetInstanceJson(e,e,t))).filter((t=>t))}_GetInstanceJson(t,e,n){const s=t.GetInstance();if(s&&s.IsDestroyed())return null;const i={};return i["uid"]=s.GetUID(),i["f"]=this._GetFlagsString(e),i["offsets"]=e._SaveSceneGraphPropertiesToJson(),i["data"]=C3.SceneGraphInfo.GetSceneGraphInstanceDataFromInstance(s),i["oci"]=s.GetObjectClass().GetIndex(),"state"===n?(i["inst"]=s.SaveToJson("full",{"selfOnly":!0}),i["instIndex"]=NaN):(i["instIndex"]=s.GetObjectClass().GetInstances().indexOf(s),i["inst"]=null),i}_LoadFromJson(t){this._startWidth=t["sw"],this._startHeight=t["sh"],this._startScaleX=t["sx"],this._startScaleY=t["sy"],this._parentStartAngle=t["psa"],this._ownOpacity=t["oo"],this._startOpacity=t["so"],this._indexInParent=C3.IsFiniteNumber(t["pi"])?t["pi"]:NaN}_SetTmpSceneGraphChildren(t,e,n,s){if(!t&&!e)if(s?.setFromJson){if(this._tmpSceneGraphChildren)for(const t of this._tmpSceneGraphChildren)t.IsDestroyed()||t.HasParent()||t.GetRuntime().DestroyInstance(t)}else if(this._tmpSceneGraphChildren)for(const t of this._tmpSceneGraphChildren)if(n["c"]&&n["c"].length){if(!n["c"].some((e=>e["uid"]===t.GetUID())))continue;t.IsDestroyed()||t.HasParent()||t.GetRuntime().DestroyInstance(t)}this._tmpSceneGraphChildren=t,this._tmpSceneGraphChildrenIndexes=e}_GetInstanceByUID(t){const e=this._owner.GetRuntime();return updatedInstances.has(t)?updatedInstances.get(t):e.GetInstanceByUID(t)}_OnAfterLoad(t,e){const n=this._owner,s=n.GetRuntime(),i=e?.processedWorldInfo??new Set;if(t["p"]&&!this._parent){const a=t["p"]["uid"],r=this._GetInstanceByUID(a);if(r){const a=r.GetWorldInfo();if(r.HasChild(n.GetInstance()))this._parent=a;else{r.HasChildWithUID(n.GetInstance().GetUID())?(s.DestroyInstance(n.GetInstance()),s._RemoveInstanceFromUIDMap(n.GetInstance().GetUID()),updatedInstances.delete(n.GetInstance().GetUID())):r.AddChild(n.GetInstance(),this._GetFlagsObj(t["p"]["f"])),i.has(n)||(n._LoadSceneGraphPropertiesFromJson(t["p"]["offsets"]),this._LoadInstancePropertiesFromJson(r,t["p"],e),this._UpdateUIDInstanceMap(r,r.GetUID(),n.GetRuntime(),e)),i.add(n);r.GetWorldInfo()._GetSceneGraphInfo()._MaybeSortChildren()}}else if(C3.IsFiniteNumber(t["p"]["oci"])){const i=s.CreateInstance(s.GetObjectClassByIndex(t["p"]["oci"]),n.GetLayer(),0,0,!0);if(i){const a=this._GetInstanceData(t["p"],s);a&&i.LoadFromJson(a);const r=i.GetWorldInfo(),h=!!e?.setFromJson;r.GetLayer().SortAndAddInstancesByZIndex(i,!1,h),i.AddChild(n.GetInstance(),this._GetFlagsObj(t["p"]["f"])),updatedInstances.set(i.GetUID(),i),this._UpdateUIDInstanceMap(i,i.GetUID(),s,e);i.GetWorldInfo()._GetSceneGraphInfo()._MaybeSortChildren()}}}const a=[];for(const e of t["c"]){const t=e["uid"],n=this._GetInstanceByUID(t);n&&a.push(n)}let r=0;for(const h of t["c"]){const c=h["uid"],o=this._GetInstanceByUID(c);if(o){if(this._tmpSceneGraphChildren){if(this._tmpSceneGraphChildren.includes(o)){const s=o;if(s.GetObjectClass()!==o.GetObjectClass()){r++;continue}if(s.IsDestroyed()){r++;continue}const h=t["c"][r];if(!e?.setFromJson&&this._HasAllChildrenOfType(s,a,n)){if(n.GetInstance().GetChildAt(r)){const a=s.GetObjectClass().GetIndex(),c=h["oci"],o=n.GetInstance().GetChildAt(r).GetObjectClass().GetIndex();if(a!==c||c!==o){this._RefreshAllChildren(t["c"],n,i,e);break}this._UpdateInstance(r,h,n,i,e)}else this._UpdateInstance(r,h,n,i,e);r++;continue}if(s.HasParent()&&s.GetParent()!==n.GetInstance()){const t=this._CreateNewChildInstance(h,e);this._AddAndSetChildInstance(t,h,i,e),r++;continue}this._AddAndSetChildInstance(s.GetWorldInfo(),h,i,e,!0),r++;continue}if(this._tmpSceneGraphChildren[r]){const s=this._tmpSceneGraphChildren[r];if(s.GetObjectClass()!==o.GetObjectClass()){r++;continue}if(s.IsDestroyed()){r++;continue}const h=t["c"][r];if(!e?.setFromJson&&this._HasAllChildrenOfType(s,a,n)){if(n.GetInstance().GetChildAt(r)){const a=s.GetObjectClass().GetIndex(),c=h["oci"],o=n.GetInstance().GetChildAt(r).GetObjectClass().GetIndex();if(a!==c||c!==o){this._RefreshAllChildren(t["c"],n,i,e);break}this._UpdateInstance(r,h,n,i,e)}else this._UpdateInstance(r,h,n,i,e);r++;continue}if(s.HasParent()&&s.GetParent()!==n.GetInstance()){const t=this._CreateNewChildInstance(h,e);this._AddAndSetChildInstance(t,h,i,e),r++;continue}this._AddAndSetChildInstance(s.GetWorldInfo(),h,i,e,!0),r++;continue}}const s=o.GetObjectClass();if(this._GetInstancesOfObjectClassCount(a,s)===n.GetInstance().GetChildrenOfObjectClass(s).length){for(const t of n.GetInstance().GetChildren()){if(t.GetObjectClass()!==s)continue;const n=t.GetWorldInfo();if(n&&!i.has(n)){i.add(n),n._LoadSceneGraphPropertiesFromJson(h["offsets"]),this._LoadInstancePropertiesFromJson(t,h,e);break}}r++;continue}if(o.HasParent()&&o.GetParent()!==n.GetInstance()){const t=this._CreateNewChildInstance(h,e);this._AddAndSetChildInstance(t,h,i,e),r++;continue}this._AddAndSetChildInstance(o.GetWorldInfo(),h,i,e)}else if(this._tmpSceneGraphChildren&&this._tmpSceneGraphChildren[r]){const c=this._tmpSceneGraphChildren[r],o=s.GetObjectClassByIndex(this._GetObjectClassIndex(h));if(c.GetObjectClass()!==o){r++;continue}if(c.IsDestroyed()){r++;continue}const d=t["c"][r];if(!e?.setFromJson&&this._HasAllChildrenOfType(c,a,n)){if(n.GetInstance().GetChildAt(r)){const s=c.GetObjectClass().GetIndex(),a=d["oci"],h=n.GetInstance().GetChildAt(r).GetObjectClass().GetIndex();if(s!==a||a!==h){this._RefreshAllChildren(t["c"],n,i,e);break}this._UpdateInstance(r,d,n,i,e)}else this._UpdateInstance(r,d,n,i,e);r++;continue}if(c.HasParent()&&c.GetParent()!==n.GetInstance()){const t=this._CreateNewChildInstance(d,e);this._AddAndSetChildInstance(t,d,i,e),r++;continue}this._AddAndSetChildInstance(c.GetWorldInfo(),d,i,e)}else{const t=this._CreateNewChildInstance(h,e);this._AddAndSetChildInstance(t,h,i,e)}r++}}_RefreshAllChildren(t,e,n,s){const i=e.GetRuntime();for(const t of e.GetInstance().children())t&&!t.IsDestroyed()&&(i.DestroyInstance(t),i._RemoveInstanceFromUIDMap(t.GetUID()),updatedInstances.delete(t.GetUID()));this._tmpSceneGraphChildren&&(this._tmpSceneGraphChildren=[]),this._tmpSceneGraphChildrenIndexes&&(this._tmpSceneGraphChildrenIndexes=new WeakMap);Object.assign({},s,{"assignZIndex":!1});for(const e of t){const t=this._CreateNewChildInstance(e,s);this._AddAndSetChildInstance(t,e,n,s),this._tmpSceneGraphChildren.push(t.GetInstance()),this._tmpSceneGraphChildrenIndexes.set(t.GetInstance(),this._tmpSceneGraphChildren.length-1)}e._GetSceneGraphInfo()._MaybeSortChildren()}_HasAllChildrenOfType(t,e,n){const s=t.GetObjectClass();return this._GetInstancesOfObjectClassCount(e,s)===n.GetInstance().GetChildrenOfObjectClass(s).length}_UpdateInstance(t,e,n,s,i){const a=n.GetInstance().GetChildAt(t);if(!a)return;const r=a.GetWorldInfo();r&&(s.has(r)||(r._LoadSceneGraphPropertiesFromJson(e["offsets"]),this._LoadInstancePropertiesFromJson(a,e,i)),s.add(r))}_GetFlagsObj(t){const e={};return e.transformX=t.includes("x"),e.transformY=t.includes("y"),e.transformWidth=t.includes("w"),e.transformHeight=t.includes("h"),e.transformAngle=t.includes("a"),e.transformZElevation=t.includes("z"),e.destroyWithParent=t.includes("d"),e.transformOpacity=t.includes("o"),e.transformVisibility=t.includes("v"),e}_GetObjectClassIndex(t){return C3.IsFiniteNumber(t["oci"])?t["oci"]:t[1]}_CreateNewChildInstance(t,e){if(!C3.IsFiniteNumber(t["oci"]))return;const n=this._owner,s=n.GetRuntime();let i;const a=!e.hasOwnProperty("createHierarchy")||e["createHierarchy"];if(i=t["data"]?s.CreateInstanceFromData(t["data"],n.GetLayer(),!1,0,0,!1,a):s.CreateInstance(s.GetObjectClassByIndex(t["oci"]),n.GetLayer(),0,0,a),!i)return;const r=this._GetInstanceData(t,s);r&&i.LoadFromJson(r);const h=i.GetWorldInfo(),c=!!e?.setFromJson;return h.GetLayer().SortAndAddInstancesByZIndex(i,!0,c),h}_UpdateUIDInstanceMap(t,e,n,s){if(this._GetInstanceByUID(e)&&!s?.setFromJson){const s=this._GetInstanceByUID(e);s!==t&&n.DestroyInstance(s)}n._RemoveInstanceFromUIDMap(e),n._MapInstanceByUID(e,t)}_AddAndSetChildInstance(t,e,n,s,i=!0){const a=this._owner,r=a.AddChild(t,this._GetFlagsObj(e["f"]));r&&i?(n.has(t)||(t._LoadSceneGraphPropertiesFromJson(e["offsets"]),this._LoadInstancePropertiesFromJson(t.GetInstance(),e,s)),n.add(t)):r&&(updatedInstances.set(t.GetInstance().GetUID(),t.GetInstance()),this._UpdateUIDInstanceMap(t.GetInstance(),e["uid"],a.GetRuntime(),s)),this._MaybeSortChildren()}_LoadInstancePropertiesFromJson(t,e,n){let s=this._GetInstanceData(e,this._owner.GetRuntime());if(!s)return;const i=!n.hasOwnProperty("clearChildren")||n["clearChildren"],a=!n.hasOwnProperty("assignZIndex")||n["assignZIndex"],r=t.GetRuntime();if(updatedInstances.set(t.GetUID(),t),s=JSON.parse(JSON.stringify(s)),i&&t.GetUID()!==s["uid"]){for(const e of t.children())e&&!e.IsDestroyed()&&(r.DestroyInstance(e),r._RemoveInstanceFromUIDMap(e.GetUID()),updatedInstances.delete(e.GetUID()));if(s["w"]?.["sgi"]&&s["w"]["sgi"]["c"]?.length)for(const e of s["w"]["sgi"]["c"]){const s=Object.assign({},n,{"clearChildren":!1,"createHierarchy":!1}),i=this._CreateNewChildInstance(e,s);updatedInstances.set(i.GetInstance().GetUID(),i.GetInstance()),t.AddChild(i.GetInstance(),this._GetFlagsObj(e["f"])),i._LoadSceneGraphPropertiesFromJson(e["offsets"]),this._LoadInstancePropertiesFromJson(i.GetInstance(),e,s)}}const h=s["w"]?.["zi"],c=s["w"]?.["l"];s["w"]=null,t.LoadFromJson(s),n?.setFromJson||(C3.IsFiniteNumber(h)&&a&&t.GetWorldInfo()._SetZIndex(h),C3.IsFiniteNumber(c)&&t.MoveToLayerWithSID(c)),this._UpdateUIDInstanceMap(t,s["uid"],r,n)}_GetInstancesOfObjectClassCount(t,e){return t.filter((t=>t.GetObjectClass().GetName()===e.GetName())).length}_GetInstanceData(t,e){if(C3.IsFiniteNumber(t["instIndex"])){const n=e.GetObjectClassByIndex(t["oci"])._GetLoadInstancesJson();return n?n[t["instIndex"]]:null}return C3.IsString(t["inst"])?JSON.parse(t["inst"]):t["inst"]?t["inst"]:void 0}static GetSceneGraphInstanceDataFromInstance(t){let e=t.GetWorldInfo().GetLayer().GetInitialInstanceData(t.GetUID());if(!e)return null;e=JSON.parse(JSON.stringify(e));const n=[];for(const e of[...t.GetChildren()]){const t=e.GetWorldInfo();n.push([t.GetLayout().GetSID(),t.GetLayer().GetIndex(),e.GetUID(),C3.SceneGraphInfo._GetFlagsNumber(t),e.GetObjectClass().IsInContainer()?1:0,t.GetZIndex(),C3.SceneGraphInfo.GetSceneGraphInstanceDataFromInstance(e)])}return C3.IsArray(e[0][14])?e[0][14][1]=n:(e[0][14]=[],e[0][14][0]=C3.SceneGraphInfo._GetDefaultFlagsNumber(),e[0][14][1]=n,e[0][14][2]=t.GetWorldInfo().GetZIndex()),e}static _GetFlagsNumber(t){let e=0;return e|=Number(t.GetTransformWithParentVisibility())<<8,e|=Number(t.GetTransformWithParentOpacity())<<7,e|=Number(t.GetTransformWithParentZElevation())<<6,e|=Number(t.GetDestroyWithParent())<<5,e|=Number(t.GetTransformWithParentAngle())<<4,e|=Number(t.GetTransformWithParentHeight())<<3,e|=Number(t.GetTransformWithParentWidth())<<2,e|=Number(t.GetTransformWithParentY())<<1,e|=Number(t.GetTransformWithParentX())|0,e}static _GetDefaultFlagsNumber(t){let e=0;return e|=256,e|=128,e|=64,e|=32,e|=16,e|=8,e|=4,e|=2,e|=1,511}static ClearUpdatedInstances(){updatedInstances.clear()}};
}

// objects/worldInfo.js
{
const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,tempRect=C3.New(C3.Rect),tempQuad=C3.New(C3.Quad),bboxChangeEvent=C3.New(C3.Event,"bboxchange",!1),tempColor=C3.New(C3.Color,0,0,0,0),tempCollisionPoly=C3.New(C3.CollisionPoly),DEFAULT_COLOR=C3.New(C3.Color,1,1,1,1),DEFAULT_RENDER_CELLS=C3.New(C3.Rect,0,0,-1,-1),DEFAULT_COLLISION_CELLS=C3.New(C3.Rect,0,0,-1,-1),VALID_SET_MESH_POINT_MODES=new Set(["absolute","relative"]),EMPTY_ARRAY=[];let enableUpdateRendererStateGroup=!0;const FLAG_IS_VISIBLE=1,FLAG_BBOX_CHANGED=2,FLAG_ENABLE_BBOX_CHANGED_EVENT=4,FLAG_COLLISION_ENABLED=8,FLAG_COLLISION_CELL_CHANGED=16,FLAG_SOLID_FILTER_INCLUSIVE=32,FLAG_HAS_ANY_ACTIVE_EFFECT=64,FLAG_IS_ROTATABLE=128,FLAG_DESTROYED=256,FLAG_DESTROY_WITH_PARENT=512,FLAG_TRANSFORM_WITH_PARENT_X=1024,FLAG_TRANSFORM_WITH_PARENT_Y=2048,FLAG_TRANSFORM_WITH_PARENT_W=4096,FLAG_TRANSFORM_WITH_PARENT_H=8192,FLAG_TRANSFORM_WITH_PARENT_A=16384,FLAG_TRANSFORM_WITH_PARENT_Z_ELEVATION=32768,FLAG_TRANSFORM_WITH_PARENT_OPACITY=1<<22,FLAG_TRANSFORM_WITH_PARENT_VISIBILITY=1<<23,MASK_ALL_SCENE_GRAPH_FLAGS=12647936,FLAG_MESH_CHANGED=65536,FLAG_PHYSICS_BODY_CHANGED=1<<17,FLAG_SIN_COS_ANGLE_CHANGED=1<<18,FLAG_USE_POINTS_SHADER_PROGRAM=1<<19,FLAG_DRAW_BACK_FACE_ONLY=1<<20,FLAG_DRAW_NON_BACK_FACES_ONLY=1<<21,FLAG_BLEND_MODE_BIT_OFFSET=26,FLAG_BLEND_MODE_MASK=31<<26,sceneGraphExportDataMap=new WeakMap,sceneGraphZIndexMap=new WeakMap;C3.WorldInfo=class extends C3.DefendedBase{constructor(t,e){super(),this._inst=t,this._objectClass=t.GetObjectClass(),this._runtime=t.GetRuntime(),this._layer=e,this._objectClass._OnWorldInstanceLayerChanged(this,null,e),this._zIndex=-1,this._htmlZIndex=-1,this._flags=196635,this._objectClass.GetPlugin().IsRotatable()&&(this._flags|=128),this._x=NaN,this._y=NaN,this._zElevation=NaN,this._w=NaN,this._h=NaN,this._depth=NaN,this._a=NaN,this._sinA=NaN,this._cosA=NaN,this._ox=NaN,this._oy=NaN,this._boundingBox=C3.New(C3.Rect),this._boundingQuad=C3.New(C3.Quad),this._collisionCells=DEFAULT_COLLISION_CELLS,this._renderCells=DEFAULT_RENDER_CELLS,this._sourceCollisionPoly=null,this._transformedPolyInfo=null,this._solidFilterTags=null,this._color=DEFAULT_COLOR,this._colorPremultiplied=DEFAULT_COLOR,this._stateGroup=null,this._instanceEffectList=null,this._inst.GetObjectClass().UsesEffects()&&(this._instanceEffectList=C3.New(C3.InstanceEffectList,this._inst,this)),this._sceneGraphInfo=null,this._tmpSceneGraphChildren=null,this._tmpSceneGraphChildrenIndexes=null,this._tmpHierarchyPosition=-1,this._meshInfo=null}_MarkDestroyed(){this._flags|=256}Release(){if(this._objectClass._OnWorldInstanceLayerChanged(this,this._layer,null),this._stateGroup&&(this._runtime.GetRenderer().ReleaseStateGroup(this._stateGroup),this._stateGroup=null),this._sourceCollisionPoly=null,this._transformedPolyInfo&&(this._transformedPolyInfo.poly.Release(),this._transformedPolyInfo=null),this._solidFilterTags&&(this._solidFilterTags.clear(),this._solidFilterTags=null),this.ReleaseMesh(),this._instanceEffectList&&this._instanceEffectList.Release(),this.HasParent()&&this.GetParent().RemoveChild(this),this.HasChildren()){const t=[...this.GetChildren()];for(const e of t)this.RemoveChild(e)}this._ReleaseSceneGraphInfo(),this._ReleaseTmpSceneGraphInfo(),sceneGraphExportDataMap.delete(this),sceneGraphZIndexMap.delete(this),this._inst=null,this._objectClass=null,this._runtime=null,this._layer=null}Init(t){if(enableUpdateRendererStateGroup=!1,this.SetXY(t[0],t[1]),this.SetZElevation(t[2]),this.SetSize(t[3],t[4]),this._depth=0,this.IsRotatable()?this.SetAngle(t[6]):this._a=0,tempColor.setFromJSON(t[7]),this._SetColor(tempColor),this.SetOriginX(t[8]),this.SetOriginY(t[9]),this.SetBlendMode(t[10]),this._instanceEffectList&&this._instanceEffectList._LoadEffectParameters(t[12]),t[14]&&sceneGraphExportDataMap.set(this,{childrenData:t[14][1],zIndexData:t[14][2]}),t[15]){const e=t[15];this.CreateMesh(e[0],e[1]);const s=this.GetSourceMesh(),i=e[2];for(let t=0,e=i.length;t<e;++t){const e=i[t];for(let i=0,n=e.length;i<n;++i){const n=e[i],r=s.GetMeshPointAt(i,t);r.SetX(n[0]),r.SetY(n[1]),r.SetZElevation(n[2]),r.SetU(n[3]),r.SetV(n[4])}}}if(t[16]){const e=t[16][0],s=t[16][1],i=!!s,n=!i,r=this._runtime.GetTemplateManager();i&&r&&r.MapInstanceToTemplateName(this.GetInstance(),s),n&&r&&r.MapInstanceToTemplateName(this.GetInstance(),e)}enableUpdateRendererStateGroup=!0,this._UpdateRendererStateGroup()}InitNoData(){this._x=0,this._y=0,this._zElevation=0,this._w=0,this._h=0,this._depth=0,this._a=0,this._sinA=0,this._cosA=1,this._ox=0,this._oy=0,this._UpdateRendererStateGroup()}GetRuntime(){return this._runtime}GetObjectClass(){return this._objectClass}GetInstance(){return this._inst}_GetParentOffsetAngle(){return this.GetTransformWithParentAngle()?this._MaybeReflectAngleForMirrorFlip(this.GetParent()._GetAngleNoReflect()-this._sceneGraphInfo.GetParentStartAngle()):0}SetX(t){if(t=+t,this.GetTransformWithParentX()){const e=this._sceneGraphInfo,s=t-this.GetX(),i=-this._GetParentOffsetAngle();0===i?this._x+=s/e.GetParentScaleX():(this._x+=Math.cos(i)*s/e.GetParentScaleX(),this.GetTransformWithParentY()&&(this._y+=Math.sin(i)*s/e.GetParentScaleY()))}else this._x=t}OffsetX(t,e=!1){t=+t,e?this._x+=t:this.GetTransformWithParentX()?this.SetX(this.GetX()+t):this._x+=t}GetX(){if(this.GetTransformWithParentX()){let t=this._x;const e=this._sceneGraphInfo,s=this.GetParent(),i=this._GetParentOffsetAngle();return 0===i?t*=e.GetParentScaleX():(t=t*e.GetParentScaleX()*Math.cos(i),this.GetTransformWithParentY()&&(t-=this._y*e.GetParentScaleY()*Math.sin(i))),s.GetX()+t}return this._x}SetY(t){if(t=+t,this.GetTransformWithParentY()){const e=this._sceneGraphInfo,s=t-this.GetY(),i=-this._GetParentOffsetAngle();0===i?this._y+=s/e.GetParentScaleY():(this.GetTransformWithParentX()&&(this._x-=Math.sin(i)*s/e.GetParentScaleX()),this._y+=Math.cos(i)*s/e.GetParentScaleY())}else this._y=t}OffsetY(t,e=!1){t=+t,e?this._y+=t:this.GetTransformWithParentY()?this.SetY(this.GetY()+t):this._y+=t}GetY(){if(this.GetTransformWithParentY()){let t=this._y;const e=this._sceneGraphInfo,s=this.GetParent(),i=this._GetParentOffsetAngle();return 0===i?t*=e.GetParentScaleY():(t=t*e.GetParentScaleY()*Math.cos(i),this.GetTransformWithParentX()&&(t+=this._x*e.GetParentScaleX()*Math.sin(i))),s.GetY()+t}return this._y}SetXY(t,e){if(t=+t,e=+e,this.GetTransformWithParentXOrY()){const s=this.GetTransformWithParentX(),i=this.GetTransformWithParentY(),n=this._sceneGraphInfo,r=t-this.GetX(),h=e-this.GetY(),a=-this._GetParentOffsetAngle();if(0===a)s?this._x+=r/n.GetParentScaleX():this._x=t,i?this._y+=h/n.GetParentScaleY():this._y=e;else{const o=Math.sin(a),l=Math.cos(a);s?this._x+=i?(l*r-o*h)/n.GetParentScaleX():l*r/n.GetParentScaleX():this._x=t,i?this._y+=s?(o*r+l*h)/n.GetParentScaleY():l*h/n.GetParentScaleY():this._y=e}}else this._x=t,this._y=e}GetXY(){return[this.GetX(),this.GetY()]}OffsetXY(t,e){t=+t,e=+e,this.GetTransformWithParentXOrY()?this.SetXY(this.GetX()+t,this.GetY()+e):(this._x+=t,this._y+=e)}EqualsXY(t,e){return this.GetX()===t&&this.GetY()===e}SetZElevation(t){if(t=+t,this.GetTransformWithParentZElevation()&&(t-=this.GetParent().GetZElevation()),this._zElevation===t)return;this._zElevation=t,this._UpdateZElevation();const e=this.GetLayer();0!==this._zElevation&&e._SetAnyInstanceZElevated(),e.SetZIndicesChanged(this)}_UpdateZElevation(){if(this._UpdateRendererStateGroup(),this.HasChildren()){const t=this.GetChildren();for(let e=0,s=t.length;e<s;e++){const s=t[e];s.GetTransformWithParentZElevation()&&s._UpdateZElevation()}}}OffsetZElevation(t){this.SetZElevation(this.GetZElevation()+t)}GetZElevation(){return this.GetTransformWithParentZElevation()?this.GetParent().GetZElevation()+this._zElevation:this._zElevation}GetTotalZElevation(){return this.GetLayer().GetZElevation()+this.GetZElevation()}IsOriginalSizeKnown(){return this.GetInstance().GetPlugin().GetSdkVersion()<2&&this.GetInstance().GetSdkInstance().IsOriginalSizeKnown()}SetWidth(t){if(t=+t,this.GetTransformWithParentWidth()){const e=this.GetWidth();0===e?this._w=Number.EPSILON:this._w*=t/e}else this._w=t;this._MarkSinCosAngleChanged()}OffsetWidth(t,e){t=+t,e?this._w+=t:this.GetTransformWithParentWidth()?this.SetWidth(this.GetWidth()+t):this._w+=t,this._MarkSinCosAngleChanged()}GetWidth(){if(this.GetTransformWithParentWidth()){const t=this.GetParent(),e=t.GetWidth();return t._GetSceneGraphInfo()._GetStartWidth()===Number.EPSILON?(this._GetSceneGraphInfo()._GetStartWidth()+e)*this._w:e*this._w}return this._w}SetHeight(t){if(t=+t,this.GetTransformWithParentHeight()){const e=this.GetHeight();0===e?this._h=Number.EPSILON:this._h*=t/e}else this._h=t;this._MarkSinCosAngleChanged()}OffsetHeight(t,e){t=+t,e?this._h+=t:this.GetTransformWithParentHeight()?this.SetHeight(this.GetHeight()+t):this._h+=t,this._MarkSinCosAngleChanged()}GetHeight(){if(this.GetTransformWithParentHeight()){const t=this.GetParent(),e=t.GetHeight();return t._GetSceneGraphInfo()._GetStartHeight()===Number.EPSILON?(this._GetSceneGraphInfo()._GetStartHeight()+e)*this._h:e*this._h}return this._h}SetSize(t,e){if(t=+t,e=+e,this.GetTransformWithParentWidth()){const e=this.GetWidth();0===e?this._w=Number.EPSILON:this._w*=t/e}else this._w=t;if(this.GetTransformWithParentHeight()){const t=this.GetHeight();0===t?this._h=Number.EPSILON:this._h*=e/t}else this._h=e;this._MarkSinCosAngleChanged()}GetSize(){return[this.GetWidth(),this.GetHeight()]}GetDepth(){return this._depth}SetDepth(t){if(t<0)throw new RangeError("invalid depth");this._depth=t}GetSceneGraphScale(){if(this.HasParent()){const t=this._sceneGraphInfo;return Math.min(t.GetParentScaleX(),t.GetParentScaleY())}return 1}IsRotatable(){return!!(128&this._flags)}SetAngle(t){t=+t,this.IsRotatable()&&(this.GetTransformWithParentAngle()&&(t-=this.GetParent().GetAngle()),t=C3.clampAngle(t),this._a!==t&&(this._a=t,this._MarkSinCosAngleChanged()))}OffsetAngle(t){0!==(t=+t)&&this.IsRotatable()&&(this._a=C3.clampAngle(this._a+t),this._MarkSinCosAngleChanged())}_MarkSinCosAngleChanged(){if(this._flags|=262144,this.HasChildren()){const t=this.GetChildren();for(let e=0,s=t.length;e<s;e++)t[e]._MarkSinCosAngleChanged()}}GetAngle(){return this.GetTransformWithParentAngle()&&this.IsRotatable()?this._MaybeReflectAngleForMirrorFlip(C3.clampAngle(this.GetParent()._GetAngleNoReflect()+this._a)):this._a}_GetAngleNoReflect(){return this.GetTransformWithParentAngle()&&this.IsRotatable()?C3.clampAngle(this.GetParent()._GetAngleNoReflect()+this._a):this._a}_MaybeReflectAngleForMirrorFlip(t){return this.GetTransformWithParentWidth()&&this.GetTopParent().GetWidth()<0&&(t=C3.clampAngle(C3.angleReflect(t,this.GetTopParent().GetAngle()+Math.PI))),this.GetTransformWithParentHeight()&&this.GetTopParent().GetHeight()<0&&(t=C3.angleReflect(t,this.GetTopParent().GetAngle())),t}_NeedsReflectAngleForMirrorOrFlip(){const t=this.GetParent();return!!(this.GetTransformWithParentWidth()&&t.GetWidth()<0)||!!(this.GetTransformWithParentHeight()&&t.GetHeight()<0)}_NeedsReflectAngleForMirrorAndFlip(){const t=this.GetParent();return!!(this.GetTransformWithParentWidth()&&t.GetWidth()<0&&this.GetTransformWithParentHeight()&&t.GetHeight()<0)}_MaybeUpdateSinCosAngle(){const t=this._flags;if(!(262144&t))return;const e=this.GetAngle();this._sinA=Math.sin(e),this._cosA=Math.cos(e),this._flags=-262145&t}GetSinAngle(){return this._MaybeUpdateSinCosAngle(),this._sinA}GetCosAngle(){return this._MaybeUpdateSinCosAngle(),this._cosA}SetOriginX(t){this._ox=+t}OffsetOriginX(t){this._ox+=+t}GetOriginX(){return this._ox}SetOriginY(t){this._oy=+t}OffsetOriginY(t){this._oy+=+t}GetOriginY(){return this._oy}_SetColor(t){this._color.equals(t)||(this._color===DEFAULT_COLOR?(this._color=C3.New(C3.Color,t),this._colorPremultiplied=C3.New(C3.Color,t),this._colorPremultiplied.premultiply()):t.equalsRgba(1,1,1,1)?(this._color=DEFAULT_COLOR,this._colorPremultiplied=DEFAULT_COLOR):(this._color.set(t),this._colorPremultiplied.set(t),this._colorPremultiplied.premultiply()),this._UpdateRendererStateGroup())}SetOpacity(t){if(t=C3.clamp(+t,0,1),this.GetTransformWithParentOpacity()){if(this._GetSceneGraphInfo().GetOwnOpacity()===t)return;this._GetSceneGraphInfo().SetOwnOpacity(t),t=this.GetOpacity()}else if(this._color.a===t)return;this._SetColorWithOpacity(t)}_SetOpacityOfChildren(){if(!this.HasChildren())return;const t=this.GetChildren();for(let e=0,s=t.length;e<s;e++){const s=t[e];s._SetColorWithOpacity(s.GetOpacity())}}_SetColorWithOpacity(t){tempColor.copyRgb(this._color),tempColor.a=t,this._SetColor(tempColor),this._SetOpacityOfChildren()}OffsetOpacity(t){this.GetTransformWithParentOpacity()?this.SetOpacity(this._GetSceneGraphInfo().GetOwnOpacity()+t):this.SetOpacity(this.GetOpacity()+t)}GetOpacity(){return this.GetTransformWithParentOpacity()?this.GetParent().GetOpacity()*this._GetSceneGraphInfo().GetOwnOpacity():this._color.a}SetUnpremultipliedColor(t){this._color.equalsIgnoringAlpha(t)||(tempColor.copyRgb(t),tempColor.a=this.GetOpacity(),this._SetColor(tempColor))}SetUnpremultipliedColorRGB(t,e,s){tempColor.setRgb(t,e,s),this.SetUnpremultipliedColor(tempColor)}OffsetUnpremultipliedColorRGB(t,e,s){0===t&&0===e&&0===s||(tempColor.copyRgb(this._color),tempColor.r+=t,tempColor.g+=e,tempColor.b+=s,this.SetUnpremultipliedColor(tempColor))}GetUnpremultipliedColor(){return this._color}GetPremultipliedColor(){return this._colorPremultiplied}GetDestroyWithParent(){return!!(512&this._flags)}SetDestroyWithParent(t){this._SetFlag(512,t)}GetTransformWithParentX(){return!!(1024&this._flags)}SetTransformWithParentX(t){this._SetFlag(1024,t)}GetTransformWithParentY(){return!!(2048&this._flags)}GetTransformWithParentXOrY(){return!!(3072&this._flags)}SetTransformWithParentY(t){this._SetFlag(2048,t)}GetTransformWithParentWidth(){return!!(4096&this._flags)}SetTransformWithParentWidth(t){this._SetFlag(4096,t)}GetTransformWithParentHeight(){return!!(8192&this._flags)}SetTransformWithParentHeight(t){this._SetFlag(8192,t)}GetTransformWithParentAngle(){return!!(16384&this._flags)}SetTransformWithParentAngle(t){this._SetFlag(16384,t)}GetTransformWithParentZElevation(){return!!(32768&this._flags)}SetTransformWithParentZElevation(t){this._SetFlag(32768,t)}GetTransformWithParentOpacity(){return!!(4194304&this._flags)}SetTransformWithParentOpacity(t){this._SetFlag(4194304,t)}GetTransformWithParentVisibility(){return!!(8388608&this._flags)}SetTransformWithParentVisibility(t){this._SetFlag(8388608,t)}_ClearAllSceneGraphFlags(){this._flags&=-12647937}AddChild(t,e){if(t===this)return!1;if(t.HasParent())return!1;if(this._HasChildRecursive(t))return!1;if(this._HasAnyParent(t))return!1;const s=t.GetX(),i=t.GetY(),n=t.GetWidth(),r=t.GetHeight(),h=t.GetAngle(),a=t.GetZElevation(),o=t.GetOpacity();t._SetParent(this),t.SetTransformWithParentX(e.transformX),t.SetTransformWithParentY(e.transformY),t.SetTransformWithParentWidth(e.transformWidth),t.SetTransformWithParentHeight(e.transformHeight),t.SetTransformWithParentAngle(e.transformAngle),t.SetTransformWithParentZElevation(e.transformZElevation),t.SetTransformWithParentOpacity(e.transformOpacity),t.SetTransformWithParentVisibility(e.transformVisibility),t.SetDestroyWithParent(e.destroyWithParent);const l=s-this.GetX(),_=i-this.GetY(),G=-this.GetAngle(),c=Math.cos(G),d=Math.sin(G);if(e.transformX&&(e.transformAngle?t._x=l*c-_*d:t._x=l,e.transformWidth)){const e=this.GetWidth()/this._sceneGraphInfo._GetStartWidth();0!==e&&(t._x/=e)}if(e.transformY&&(e.transformAngle?t._y=l*d+_*c:t._y=_,e.transformHeight)){const e=this.GetHeight()/this._sceneGraphInfo._GetStartHeight();0!==e&&(t._y/=e)}if(e.transformWidth){const e=this.GetWidth();0===e||e===Number.EPSILON?(t._w=1,t._sceneGraphInfo.SetStartScaleX(1)):(t._w=n/this.GetWidth(),t._sceneGraphInfo.SetStartScaleX(t._w))}if(e.transformHeight){const e=this.GetHeight();0===e||e===Number.EPSILON?(t._h=1,t._sceneGraphInfo.SetStartScaleY(1)):(t._h=r/this.GetHeight(),t._sceneGraphInfo.SetStartScaleY(t._h))}return e.transformAngle&&(t._a=h-this.GetAngle()),e.transformZElevation&&(t._zElevation=a-this.GetZElevation()),e.transformOpacity&&t._sceneGraphInfo.SetOwnOpacity(o),e.transformVisibility&&t.SetVisible(this.IsVisible()),this._AddChildToSceneGraphInfo(t),this.SetBboxChanged(),this._SetOpacityOfChildren(),!0}RemoveChild(t){if(t.GetParent()!==this)return;const e=t.GetX(),s=t.GetY(),i=t.GetWidth(),n=t.GetHeight(),r=t.GetAngle(),h=t.GetZElevation(),a=t.GetOpacity();t._SetParent(null),t._ClearAllSceneGraphFlags(),t.SetXY(e,s),t.SetSize(i,n),t.SetAngle(r),t.SetZElevation(h),t.SetOpacity(a),this._RemoveChildFromSceneGraphInfo(t),this.SetBboxChanged()}GetTmpHierarchyPosition(){return this._tmpHierarchyPosition}_ResetAllSceneGraphState(){this._BuildTmpSceneGraphData();const t=[...this.children()];for(const e of t)this.RemoveChild(e);const e=this.GetParent();e&&e.RemoveChild(this),this._ClearAllSceneGraphFlags()}_BuildTmpSceneGraphData(){if(this._SetTmpHierarchyPosition(),!this._tmpSceneGraphChildren){const t=[...this.children()];t.length&&(this._tmpSceneGraphChildren=[],this._tmpSceneGraphChildrenIndexes=new WeakMap);let e=0;for(const s of t){const t=s.GetInstance();this._tmpSceneGraphChildren.push(t),this._tmpSceneGraphChildrenIndexes.set(t,e),e++}}const t=this.GetParent();t&&t._BuildTmpSceneGraphData()}_SetTmpHierarchyPosition(){if(-1!==this._tmpHierarchyPosition)return;const t=[...this.parents()];this._tmpHierarchyPosition=t.length;for(const e of t)e._SetTmpHierarchyPosition();const e=[...this.children()];for(const t of e)t._SetTmpHierarchyPosition()}_ReleaseTmpSceneGraphInfo(){this._tmpSceneGraphChildren&&(this._tmpSceneGraphChildren.length=0),this._tmpSceneGraphChildren=null,this._tmpSceneGraphChildrenIndexes=null;const t=this.GetParent();t&&t._ReleaseTmpSceneGraphInfo(),this._tmpHierarchyPosition=-1}HasParent(){return null!==this.GetParent()}GetParent(){const t=this._sceneGraphInfo;return null!==t?t.GetParent():null}GetTopParent(){let t=this;for(;t.HasParent();)t=t.GetParent();return t}*parents(){let t=this.GetParent();for(;t;)yield t,t=t.GetParent()}HasChild(t){return this.GetChildren().includes(t)}HasChildren(){const t=this._sceneGraphInfo;return null!==t&&t.HasChildren()}GetChildren(){const t=this._sceneGraphInfo;return null!==t?t.GetChildren():EMPTY_ARRAY}children(){return this.GetChildren()}*allChildren(){for(const t of this.children())yield t,yield*t.allChildren()}GetChildCount(){return this.GetChildren().length}GetAllChildCount(){return[...this.allChildren()].length}GetChildAt(t){const e=this.GetChildren();return(t=Math.floor(+t))<0||t>=e.length?null:e[t]}GetChildIndex(t){if(!t)return NaN;const e=this.GetChildren();if(!e)return NaN;for(let s=0;s<e.length;s++)if(t===e[s])return s;return NaN}_CreateSceneGraphInfo(t){this._sceneGraphInfo||(this._sceneGraphInfo=C3.New(C3.SceneGraphInfo,this)),t&&this._sceneGraphInfo.SetParent(t)}_GetSceneGraphInfo(){return this._sceneGraphInfo}_ReleaseSceneGraphInfo(){this._sceneGraphInfo&&(this._sceneGraphInfo.Release(),this._sceneGraphInfo=null)}_SetParent(t){t?(t._CreateSceneGraphInfo(null),this._CreateSceneGraphInfo(t)):(this._sceneGraphInfo&&this._sceneGraphInfo.SetParent(null),this.HasChildren()||this._ReleaseSceneGraphInfo())}_HasAnyParent(t){if(!this.HasParent())return!1;const e=this.GetParent();return e===t||e._HasAnyParent(t)}_HasChildRecursive(t){if(this.HasChild(t))return!0;for(const e of this.GetChildren())if(e._HasChildRecursive(t))return!0;return!1}_AddChildToSceneGraphInfo(t){this._sceneGraphInfo.GetChildren().push(t)}_RemoveChildFromSceneGraphInfo(t){const e=this._sceneGraphInfo.GetChildren(),s=e.indexOf(t);-1!==s&&e.splice(s,1),0!==e.length||this.HasParent()||this._ReleaseSceneGraphInfo(),t.HasChildren()||t._ReleaseSceneGraphInfo()}GetSceneGraphChildrenExportData(){const t=sceneGraphExportDataMap.get(this);return t?t.childrenData:null}GetSceneGraphZIndexExportData(){const t=sceneGraphExportDataMap.get(this);return t?t.zIndexData:NaN}GetSceneGraphZIndex(){const t=sceneGraphZIndexMap.get(this);return C3.IsFiniteNumber(t)?t:NaN}SetSceneGraphZIndex(t){sceneGraphZIndexMap.set(this,t)}SetUsePointsShaderProgram(){this._SetFlag(524288,!0),this._UpdateRendererStateGroup()}_UpdateRendererStateGroup(){if(!enableUpdateRendererStateGroup)return;const t=this._runtime.GetRenderer();let e;this._stateGroup&&t.ReleaseStateGroup(this._stateGroup),e=524288&this._flags?t.GetPointsRenderingProgram()||"<point>":t.GetTextureFillShaderProgram()||"<default>",this._stateGroup=t.AcquireStateGroup(e,this.GetBlendMode(),this._colorPremultiplied,this.GetZElevation())}GetRendererStateGroup(){return this._stateGroup}HasDefaultColor(){return this._color===DEFAULT_COLOR}SetBlendMode(t){if((t|=0)<0||t>31)throw new RangeError("invalid blend mode");this.GetBlendMode()!==t&&(this._flags=-2080374785&this._flags|t<<26,this._UpdateRendererStateGroup())}GetBlendMode(){return(2080374784&this._flags)>>26}_SetLayer(t,e){const s=e&&this._layer!==t;s&&this._RemoveFromRenderCells(),this._objectClass._OnWorldInstanceLayerChanged(this,this._layer,t),this._layer=t,s&&this._UpdateRenderCell(),0!==this.GetZElevation()&&this._layer._SetAnyInstanceZElevated()}GetLayer(){return this._layer}GetLayout(){return this.GetLayer().GetLayout()}_SetZIndex(t){this._zIndex=0|t}GetZIndex(){return this._layer._UpdateZIndices(),this._zIndex}_SetHTMLZIndex(t){this._htmlZIndex=0|t}GetHTMLZIndex(){return this._layer._UpdateHTMLZIndices(),this._htmlZIndex}_GetLastCachedZIndex(){return this._zIndex}_SetFlag(t,e){e?this._flags|=t:this._flags&=~t}IsVisible(){return!!(1&this._flags)}SetVisible(t){if(this._SetFlag(1,t),this.HasChildren())for(const e of this.GetChildren())e.GetTransformWithParentVisibility()&&e.SetVisible(t)}IsCollisionEnabled(){return!!(8&this._flags)}SetCollisionEnabled(t){t=!!t,this.IsCollisionEnabled()!==t&&(this._SetFlag(8,t),t?this.SetBboxChanged():this._RemoveFromCollisionCells())}SetSolidCollisionFilter(t,e){if(this._SetFlag(32,t),this._solidFilterTags&&this._solidFilterTags.clear(),e.trim()){this._solidFilterTags||(this._solidFilterTags=new Set);for(const t of e.split(" "))t&&this._solidFilterTags.add(t.toLowerCase())}else this._solidFilterTags=null}IsSolidCollisionAllowed(t){const e=!!(32&this._flags),s=this._solidFilterTags;if(!t||!s)return!e;for(const i of s)if(t.has(i))return e;return!e}SetBboxChanged(){if(this._flags|=65554,this._objectClass._SetAnyCollisionCellChanged(!0),this._runtime.UpdateRender(),this._layer.UsesRenderCells()&&(this.CalculateBbox(this._boundingBox,this._boundingQuad,!0),this._flags&=-3,this._UpdateRenderCell()),4&this._flags&&this._inst.Dispatcher().dispatchEvent(bboxChangeEvent),null!==this._sceneGraphInfo){const t=this._sceneGraphInfo.GetChildren();for(let e=0,s=t.length;e<s;++e)t[e].SetBboxChanged()}}CalculateBbox(t,e,s){const i=this.GetX(),n=this.GetY(),r=this.GetWidth(),h=this.GetHeight(),a=this.GetAngle();t.setWH(i-this._ox*r,n-this._oy*h,r,h),s&&this.HasMesh()&&this._ExpandBboxForMesh(t),0===a?e.setFromRect(t):(t.offset(-i,-n),e.setFromRotatedRectPrecalc(t,this.GetSinAngle(),this.GetCosAngle()),e.offset(i,n),e.getBoundingBox(t)),t.normalize()}_UpdateBbox(){const t=this._flags;2&t&&(this.CalculateBbox(this._boundingBox,this._boundingQuad,!0),this._flags=-3&t)}GetBoundingBox(){return this._UpdateBbox(),this._boundingBox}GetBoundingQuad(){return this._UpdateBbox(),this._boundingQuad}PixelRoundQuad(t){const e=this.GetX(),s=this.GetY(),i=Math.round(e)-e,n=Math.round(s)-s;return 0===i&&0===n?t:(tempQuad.copy(t),tempQuad.offset(i,n),tempQuad)}OverwriteBoundingBox(t){this._boundingBox.copy(t),this._boundingQuad.setFromRect(this._boundingBox),this._flags&=-3,this._UpdateCollisionCell(),this._UpdateRenderCell()}SetBboxChangeEventEnabled(t){this._SetFlag(4,t)}IsBboxChangeEventEnabled(){return!!(4&this._flags)}IsInViewport(t,e,s){return e&&0!==this.GetDepth()?this.IsInViewport3D(this.GetLayer()._GetViewFrustum()):0===this.GetZElevation()||s?t.intersectsRect(this.GetBoundingBox()):this._IsInViewport_ZElevated()}_IsInViewport_ZElevated(){const t=this.GetLayer(),e=this.GetTotalZElevation();return!(e>=t.Get2DCameraZ())&&(t.GetViewportForZ(e,tempRect),tempRect.intersectsRect(this.GetBoundingBox()))}IsInViewport3D(t){const e=this.GetBoundingBox(),s=e.getLeft(),i=e.getRight(),n=e.getTop(),r=e.getBottom(),h=this.GetTotalZElevation(),a=h+this.GetDepth();return t.ContainsAABB(s,n,h,i,r,a)}IsInViewport2(){const t=this.GetLayer();if(t.Has3DCamera())return this.IsInViewport3D(t._GetViewFrustum());{const e=t.GetLayout();return this.IsInViewport(t.GetViewport(),e.HasVanishingPointOutsideViewport(),e.IsOrthographicProjection())}}_SetDrawBackFaceOnly(t){this._SetFlag(1048576,t)}_SetDrawNonBackFacesOnly(t){this._SetFlag(2097152,t)}IsDrawBackFaceOnly(){return!!(1048576&this._flags)}IsDrawNonBackFacesOnly(){return!!(2097152&this._flags)}SetSourceCollisionPoly(t){this._sourceCollisionPoly=t,this._DiscardTransformedCollisionPoly(),this.HasMesh()&&(this._meshInfo.meshPoly=null)}GetSourceCollisionPoly(){return this._sourceCollisionPoly}HasOwnCollisionPoly(){return null!==this._sourceCollisionPoly||this.HasMesh()}GetTransformedCollisionPoly(){return this._GetCustomTransformedCollisionPolyPrecalc(this.GetWidth(),this.GetHeight(),this.GetAngle(),this.GetSinAngle(),this.GetCosAngle())}GetCustomTransformedCollisionPoly(t,e,s){let i=0,n=1;return 0!==s&&(i=Math.sin(s),n=Math.cos(s)),this._GetCustomTransformedCollisionPolyPrecalc(t,e,s,i,n)}_GetCustomTransformedCollisionPolyPrecalc(t,e,s,i,n){let r=this._transformedPolyInfo;null===r&&(r={poly:C3.New(C3.CollisionPoly),width:NaN,height:NaN,angle:NaN},this._transformedPolyInfo=r);const h=r.poly;if(r.width===t&&r.height===e&&r.angle===s)return h;const a=this._sourceCollisionPoly;if(this.HasMesh()){const s=this.GetOriginX(),r=this.GetOriginY(),o=this.GetSourceMesh();let l=this._meshInfo.meshPoly;l||(a?(tempCollisionPoly.copy(a),tempCollisionPoly.offset(s,r)):tempCollisionPoly.setDefaultPoints(),l=o.InsertPolyMeshVertices(tempCollisionPoly),this._meshInfo.meshPoly=l),o.TransformCollisionPoly(l,h),h.offset(-s,-r),h.transformPrecalc(t,e,i,n)}else a?(h.copy(a),h.transformPrecalc(t,e,i,n)):h.setFromQuad(this.GetBoundingQuad(),-this.GetX(),-this.GetY());return r.width=t,r.height=e,r.angle=s,h}_DiscardTransformedCollisionPoly(){this.SetPhysicsBodyChanged(!0);const t=this._transformedPolyInfo;null!==t&&(t.width=NaN)}CreateMesh(t,e){if(t=Math.floor(t),e=Math.floor(e),!this.GetInstance().GetPlugin().SupportsMesh())throw new Error("object does not support mesh");this.ReleaseMesh(),this._meshInfo={sourceMesh:C3.New(C3.Gfx.Mesh,t,e),transformedMesh:C3.New(C3.Gfx.Mesh,t,e),meshPoly:null}}HasMesh(){return null!==this._meshInfo}GetSourceMesh(){if(!this.HasMesh())throw new Error("no mesh");return this._meshInfo.sourceMesh}GetTransformedMesh(){if(!this.HasMesh())throw new Error("no mesh");return this._meshInfo.transformedMesh}SetMeshChanged(t){this._SetFlag(65536,t)}IsMeshChanged(){return!!(65536&this._flags)}SetPhysicsBodyChanged(t){this._SetFlag(131072,t)}IsPhysicsBodyChanged(){return!!(131072&this._flags)}_ExpandBboxForMesh(t){const e=this._meshInfo.sourceMesh,s=Math.min(e.GetMinX(),0),i=Math.min(e.GetMinY(),0),n=Math.max(e.GetMaxX(),1),r=Math.max(e.GetMaxY(),1),h=t.width(),a=t.height();t.offsetLeft(s*h),t.offsetTop(i*a),t.offsetRight((n-1)*h),t.offsetBottom((r-1)*a),this._depth=e.GetMaxZ()}ReleaseMesh(){this._meshInfo&&(this._meshInfo.sourceMesh.Release(),this._meshInfo.transformedMesh.Release(),this._meshInfo=null,this._DiscardTransformedCollisionPoly())}SetMeshPoint(t,e,s){t=Math.floor(t),e=Math.floor(e);const i=s.mode||"absolute";if(!VALID_SET_MESH_POINT_MODES.has(i))throw new Error("invalid mode");const n="relative"===i;let r=s.x,h=s.y;const a=s.zElevation;let o="number"==typeof s.u?s.u:n?0:-1,l="number"==typeof s.v?s.v:n?0:-1;if(!this.HasMesh())return!1;const _=this.GetSourceMesh(),G=_.GetMeshPointAt(t,e);if(null===G)return!1;let c=!1;return"number"==typeof a&&G.GetZElevation()!==a&&(G.SetZElevation(a),c=!0),n&&(r+=t/(_.GetHSize()-1),h+=e/(_.GetVSize()-1)),-1!==o||n?(n&&(o+=t/(_.GetHSize()-1)),o=C3.clamp(o,0,1)):o=G.GetU(),-1!==l||n?(n&&(l+=e/(_.GetVSize()-1)),l=C3.clamp(l,0,1)):l=G.GetV(),G.GetX()===r&&G.GetY()===h&&G.GetU()===o&&G.GetV()===l?c:(G.SetX(r),G.SetY(h),G.SetU(o),G.SetV(l),this._DiscardTransformedCollisionPoly(),!0)}HasTilemap(){return this._inst.HasTilemap()}ContainsPoint(t,e){return!!this.GetBoundingBox().containsPoint(t,e)&&(!!this.GetBoundingQuad().containsPoint(t,e)&&(this.HasTilemap()?this._inst.GetSdkInstance().TestPointOverlapTile(t,e):!this.HasOwnCollisionPoly()||this.GetTransformedCollisionPoly().containsPoint(t-this.GetX(),e-this.GetY())))}_IsCollisionCellChanged(){return!!(16&this._flags)}_UpdateCollisionCell(){if(!this._IsCollisionCellChanged()||!this.IsCollisionEnabled()||256&this._flags)return;const t=this.GetBoundingBox(),e=this._objectClass._GetCollisionCellGrid(),s=this._collisionCells;if(tempRect.set(e.XToCell(t.getLeft()),e.YToCell(t.getTop()),e.XToCell(t.getRight()),e.YToCell(t.getBottom())),s.equals(tempRect))return;const i=this._inst;s===DEFAULT_COLLISION_CELLS?(e.Update(i,null,tempRect),this._collisionCells=C3.New(C3.Rect,tempRect)):(e.Update(i,s,tempRect),s.copy(tempRect)),this._flags&=-17}_SetCollisionCellChanged(){this._flags|=16}_RemoveFromCollisionCells(){const t=this._collisionCells;t!==DEFAULT_COLLISION_CELLS&&(this._objectClass._GetCollisionCellGrid().Update(this._inst,t,null),this._collisionCells=DEFAULT_COLLISION_CELLS)}_UpdateRenderCell(){const t=this.GetLayer();if(!t.UsesRenderCells()||256&this._flags)return;const e=t.GetRenderGrid(),s=this.GetBoundingBox(),i=this._renderCells;if(tempRect.set(e.XToCell(s.getLeft()),e.YToCell(s.getTop()),e.XToCell(s.getRight()),e.YToCell(s.getBottom())),i.equals(tempRect))return;const n=this._inst;i===DEFAULT_RENDER_CELLS?(e.Update(n,null,tempRect),this._renderCells=C3.New(C3.Rect,tempRect)):(e.Update(n,i,tempRect),i.copy(tempRect)),t.SetRenderListStale()}_RemoveFromRenderCells(){const t=this._renderCells;t!==DEFAULT_RENDER_CELLS&&(this.GetLayer().GetRenderGrid().Update(this._inst,t,null),this._renderCells=DEFAULT_RENDER_CELLS)}GetRenderCellRange(){return this._renderCells}ZOrderMoveToTop(){const t=this._inst,e=this._layer,s=e._GetInstances();s.length&&s.at(-1)===t||(e._RemoveInstance(t,!1),e._AddInstance(t,!1),this._runtime.UpdateRender())}ZOrderMoveToBottom(){const t=this._inst,e=this._layer,s=e._GetInstances();s.length&&s[0]===t||(e._RemoveInstance(t,!1),e._PrependInstance(t,!1),this._runtime.UpdateRender())}ZOrderMoveToLayer(t){const e=this._inst,s=this._layer;if(s.GetLayout()!==t.GetLayout())throw new Error("layer from different layout");t!==s&&(s._RemoveInstance(e,!0),this._SetLayer(t),t._AddInstance(e,!0),this._runtime.UpdateRender())}ZOrderMoveAdjacentToInstance(t,e){const s=this._inst;let i=!1;const n=this._layer;if(t.GetUID()===s.GetUID())return;const r=t.GetWorldInfo();if(!r)throw new Error("expected world instance");const h=r.GetLayer();n.GetIndex()!==h.GetIndex()&&(n._RemoveInstance(s,!0),this._SetLayer(h),h._AddInstance(s,!0),i=!0);const a=h.MoveInstanceAdjacent(s,t,!!e);(i||a)&&this._runtime.UpdateRender()}GetInstanceEffectList(){return this._instanceEffectList}_SetHasAnyActiveEffect(t){this._SetFlag(64,t)}HasAnyActiveEffect(){return!!(64&this._flags)}_SaveToJson(t,e=null){const s={"x":this.GetX(),"y":this.GetY(),"w":this.GetWidth(),"h":this.GetHeight(),"l":this.GetLayer().GetSID(),"zi":this.GetZIndex()};0!==this.GetZElevation()&&(s["ze"]=this.GetZElevation()),0!==this.GetAngle()&&(s["a"]=this._GetAngleNoReflect()),this.HasDefaultColor()||(s["c"]=this._color.toJSON()),.5!==this.GetOriginX()&&(s["oX"]=this.GetOriginX()),.5!==this.GetOriginY()&&(s["oY"]=this.GetOriginY()),0!==this.GetBlendMode()&&(s["bm"]=this.GetBlendMode()),this.IsVisible()||(s["v"]=this.IsVisible()),this.IsCollisionEnabled()||(s["ce"]=this.IsCollisionEnabled()),this.IsBboxChangeEventEnabled()&&(s["be"]=this.IsBboxChangeEventEnabled()),this._instanceEffectList&&(s["fx"]=this._instanceEffectList._SaveToJson());const i=!!(32&this._flags);return i&&(s["sfi"]=i),this._solidFilterTags&&(s["sft"]=[...this._solidFilterTags].join(" ")),this._sceneGraphInfo&&"visual-state"!==t&&(s["sgi"]=this._sceneGraphInfo._SaveToJson(t,e),sceneGraphExportDataMap.has(this)&&(s["sgcd"]=sceneGraphExportDataMap.get(this).childrenData,s["sgzid"]=sceneGraphExportDataMap.get(this).zIndexData)),this.HasMesh()&&(s["mesh"]=this.GetSourceMesh().SaveToJson()),s}_SaveSceneGraphPropertiesToJson(){return{"x":this._x,"y":this._y,"z":this._zElevation,"w":this._w,"h":this._h,"a":this._a,"sgi":this._GetSceneGraphInfo()?this._GetSceneGraphInfo()._SaveToJsonProperties():null}}_LoadSceneGraphPropertiesFromJson(t){t&&(this._x=t["x"],this._y=t["y"],this._zElevation=t["z"],this._w=t["w"],this._h=t["h"],this._a=t["a"],t["sgi"]&&this._GetSceneGraphInfo()&&this._GetSceneGraphInfo()._LoadFromJson(t["sgi"]),this._MarkSinCosAngleChanged(),this.SetBboxChanged())}_SetupSceneGraphConnectionsOnChangeOfLayout(){this._ReleaseTmpSceneGraphInfo(),this._ResetAllSceneGraphState(),this._CreateSceneGraphInfo(null),this._sceneGraphInfo&&this._sceneGraphInfo._SetTmpSceneGraphChildren(this._tmpSceneGraphChildren,this._tmpSceneGraphChildrenIndexes)}_OnBeforeLoad(t){"visual-state"!==t&&this._ResetAllSceneGraphState()}_OnAfterLoad(t,e="full",s=null){if(t.hasOwnProperty("sgi")&&"visual-state"!==e){if(256&this._flags)return;this._sceneGraphInfo._OnAfterLoad(t["sgi"],s)}}_OnAfterLoad2(t,e="full",s=null){if("visual-state"!==e)if(256&this._flags)this._ReleaseTmpSceneGraphInfo();else{if(t.hasOwnProperty("sgi"))this._sceneGraphInfo._SetTmpSceneGraphChildren(null,null,t["sgi"],s);else if(s?.setFromJson&&this._tmpSceneGraphChildren)for(const t of this._tmpSceneGraphChildren)t.IsDestroyed()||this._runtime.DestroyInstance(t);this._ReleaseTmpSceneGraphInfo(),this.SetBboxChanged()}}_LoadFromJson(t,e,s=null){if(enableUpdateRendererStateGroup=!1,this.SetX(t["x"]),this.SetY(t["y"]),this.SetWidth(t["w"]),this.SetHeight(t["h"]),this._SetZIndex(t["zi"]),this.SetZElevation(t.hasOwnProperty("ze")?t["ze"]:0),this.SetAngle(t.hasOwnProperty("a")?t["a"]:0),t.hasOwnProperty("c")?tempColor.setFromJSON(t["c"]):t.hasOwnProperty("o")?(tempColor.copyRgb(this._color),tempColor.a=t["o"]):tempColor.setRgba(1,1,1,1),this._SetColor(tempColor),this.SetOriginX(t.hasOwnProperty("oX")?t["oX"]:.5),this.SetOriginY(t.hasOwnProperty("oY")?t["oY"]:.5),this.SetBlendMode(t.hasOwnProperty("bm")?t["bm"]:0),this.SetVisible(!t.hasOwnProperty("v")||t["v"]),this.SetCollisionEnabled(!t.hasOwnProperty("ce")||t["ce"]),this.SetBboxChangeEventEnabled(!!t.hasOwnProperty("be")&&t["be"]),this.SetSolidCollisionFilter(!!t.hasOwnProperty("sfi")&&t["sfi"],t.hasOwnProperty("sft")?t["sft"]:""),this._instanceEffectList&&t.hasOwnProperty("fx")&&this._instanceEffectList._LoadFromJson(t["fx"]),t.hasOwnProperty("sgi")&&"visual-state"!==e){this._CreateSceneGraphInfo(null);const e=this._sceneGraphInfo,s=t["sgi"];e._LoadFromJson(s),e._SetTmpSceneGraphChildren(this._tmpSceneGraphChildren,this._tmpSceneGraphChildrenIndexes),this._SetSceneGraphExportData(t["sgcd"],t["sgzid"])}if(t.hasOwnProperty("mesh")){const e=t["mesh"];this.CreateMesh(e["cols"],e["rows"]),this.GetSourceMesh().LoadFromJson(e)}else this.ReleaseMesh();this.SetBboxChanged(),enableUpdateRendererStateGroup=!0,this._UpdateRendererStateGroup(),"visual-state"!==e&&this._runtime.AddInstanceNeedingAfterLoad(this.GetInstance(),t)}_SetSceneGraphExportData(t,e){t&&C3.IsFiniteNumber(e)&&sceneGraphExportDataMap.set(this,{childrenData:t,zIndexData:e})}};
}

// objects/behaviorType.js
{
const C3=self.C3;C3.BehaviorType=class extends C3.DefendedBase{constructor(e,t){super();const s=e.GetRuntime(),i=s.GetObjectReference(t[1]);s.GetAddonManager()._DelayCreateBehavior(i),this._runtime=s,this._objectClass=e,this._behavior=C3.AddonManager.GetBehaviorByConstructorFunction(i),this._sdkType=null,this._iBehaviorType=null,this._instSdkCtor=i.Instance,this._sid=t[2],this._name=t[0],this._jsPropName=this._runtime.GetJsPropName(t[3]);const r=this._behavior.GetSdkVersion();if(r<2&&(this._sdkType=C3.New(i.Type,this),!(this._sdkType instanceof C3.SDKBehaviorTypeBase)))throw new Error("v1 sdk type must derive from SDKBehaviorBase");if(C3.AddonManager._PushInitObject(this,r),r>=2){const e=i.Type??globalThis.ISDKBehaviorTypeBase;if(this._iBehaviorType=new e,!(this._iBehaviorType instanceof globalThis.ISDKBehaviorTypeBase))throw new Error("script interface class must derive from ISDKBehaviorTypeBase")}else this._iBehaviorType=new globalThis.IBehaviorType;C3.AddonManager._PopInitObject(r),this.OnCreate()}static Create(e,t){return C3.New(C3.BehaviorType,e,t)}Release(){this._runtime=null,this._behavior=null,this._sdkType&&(this._sdkType.Release(),this._sdkType=null),this._instSdkCtor=null}GetSdkType(){return this._sdkType}OnCreate(){this._sdkType?this._sdkType.OnCreate():this._iBehaviorType&&this._iBehaviorType._onCreate()}GetRuntime(){return this._runtime}GetObjectClass(){return this._objectClass}GetBehavior(){return this._behavior}GetInstanceSdkCtor(){return this._instSdkCtor}GetName(){return this._name}GetSID(){return this._sid}GetIBehaviorType(){return this._iBehaviorType}GetJsPropName(){return this._jsPropName}};
}

// objects/behaviorInstance.js
{
const C3=self.C3,IBehaviorInstance=self.IBehaviorInstance;C3.BehaviorInstance=class extends C3.DefendedBase{constructor(t){super(),this._runtime=t.runtime,this._behaviorType=t.behaviorType,this._behavior=this._behaviorType.GetBehavior(),this._inst=t.instance,this._index=t.index,this._sdkInst=null,this._iScriptInterface=null,this._behavior._AddInstance(this._inst)}Release(){this._iScriptInterface&&(this._iScriptInterface._release(),this._iScriptInterface=null),this._behavior._RemoveInstance(this._inst),this._sdkInst&&(this._sdkInst.Release(),this._sdkInst=null),this._runtime=null,this._behaviorType=null,this._behavior=null,this._inst=null}_CreateSdkInstance(t){if(this._sdkInst)throw new Error("already got sdk instance");if(this.GetBehavior().GetSdkVersion()<2){if(this._sdkInst=C3.New(this._behaviorType.GetInstanceSdkCtor(),this,t),!(this._sdkInst instanceof C3.SDKBehaviorInstanceBase))throw new Error("v1 sdk type must derive from SDKBehaviorInstanceBase")}else{const e=this.GetBehavior().GetScriptInterfaceClass();this._InitScriptInterface(e.Instance,t)}}GetSdkInstance(){return this._sdkInst??this._iScriptInterface}GetObjectInstance(){return this._inst}GetRuntime(){return this._runtime}GetBehaviorType(){return this._behaviorType}GetBehavior(){return this._behavior}_GetIndex(){return this._index}PostCreate(){this._sdkInst?this._sdkInst.PostCreate():this._iScriptInterface._postCreate()}OnSpriteFrameChanged(t,e){this._sdkInst&&this._sdkInst.OnSpriteFrameChanged(t,e)}_GetDebuggerProperties(){return this._sdkInst?this._sdkInst.GetDebuggerProperties():this._iScriptInterface._getDebuggerProperties()}SaveToJson(t="full"){return this._sdkInst?this._sdkInst.SaveToJson(t):this._iScriptInterface._saveToJson(t)}LoadFromJson(t,e="full"){if(this._sdkInst)return this._sdkInst.LoadFromJson(t,e);this._iScriptInterface._loadFromJson(t,e)}static SortByTickSequence(t,e,s){const n=globalThis.ISDKBehaviorInstanceBase;let i,r;i=e instanceof n?t._UnwrapScriptInterface(e):e.GetBehaviorInstance(),r=s instanceof n?t._UnwrapScriptInterface(s):s.GetBehaviorInstance();const a=i.GetObjectInstance(),h=r.GetObjectInstance(),c=a.GetObjectClass().GetIndex(),o=h.GetObjectClass().GetIndex();if(c!==o)return c-o;const I=a.GetPUID(),_=h.GetPUID();return I!==_?I-_:i._GetIndex()-r._GetIndex()}_InitScriptInterface(t,e){const s=IBehaviorInstance,n=t??this._sdkInst.GetScriptInterfaceClass(),i=n||s,r=this.GetBehavior().GetSdkVersion();if(C3.AddonManager._PushInitObject(this,r),C3.AddonManager._PushInitProperties(e),this._iScriptInterface=new i,C3.AddonManager._PopInitProperties(),C3.AddonManager._PopInitObject(r),n&&!(this._iScriptInterface instanceof s))throw new TypeError(`script interface class '${n.name}' does not extend the right base class '${s.name}'`);return this._iScriptInterface}GetScriptInterface(){return this._iScriptInterface||this._InitScriptInterface()}HasScriptInterface(){return!!this._iScriptInterface}};
}

// objects/effectList.js
{
const C3=self.C3;C3.EffectList=class extends C3.DefendedBase{constructor(e,t){super(),this._owner=e,this._allEffectTypes=[],this._activeEffectTypes=[],this._effectTypesByName=new Map,this._effectParams=[],this._effectParamBuffers=[],this._allInstanceEffectLists=new Set,this._preservesOpaqueness=!0;for(const e of t){const t=C3.New(C3.EffectType,this,e,this._allEffectTypes.length);this._allEffectTypes.push(t),this._effectTypesByName.set(t.GetName().toLowerCase(),t),e.length>=3&&this._effectParams.push(this._LoadSingleEffectParameters(t,e[2]))}this.GetRuntime()._AddEffectList(this)}Release(){this.GetRuntime()._RemoveEffectList(this);for(const e of this._effectParamBuffers)e.Release();C3.clearArray(this._effectParamBuffers),C3.clearArray(this._allEffectTypes),C3.clearArray(this._activeEffectTypes),this._effectTypesByName.clear(),C3.clearArray(this._effectParams),this._owner=null}_AddInstanceEffectList(e){this._allInstanceEffectLists.add(e)}_RemoveInstanceEffectList(e){this._allInstanceEffectLists.delete(e)}_InitRenderer(e){e.IsWebGPU()&&(this._effectParamBuffers=this._allEffectTypes.map((e=>{const t=e.GetShaderProgram();return t.GetCustomParametersByteSize()>0?C3.New(C3.Gfx.WebGPUEffectCustomParamsBuffer,t):null})),this._UpdateAllEffectParamBuffers());for(const t of this._allInstanceEffectLists)t._InitRenderer(e)}PrependEffectTypes(e){if(e.length){this._allEffectTypes=e.concat(this._allEffectTypes);for(const t of e)this._effectTypesByName.set(t.GetName().toLowerCase(),t);for(let e=0,t=this._allEffectTypes.length;e<t;++e)this._allEffectTypes[e]._SetIndex(e)}}_LoadSingleEffectParameters(e,t){e.SetActive(t[0]);const s=t.slice(1);for(let e=0,t=s.length;e<t;++e){const t=s[e];if(Array.isArray(t)){const f=C3.New(C3.Color);f.setFromJSON(t),s[e]=f}}return s}GetOwner(){return this._owner}GetRuntime(){return this._owner.GetRuntime()}UpdateActiveEffects(){C3.clearArray(this._activeEffectTypes);let e=!0;for(const t of this._allEffectTypes)t.IsActive()&&(this._activeEffectTypes.push(t),t.GetShaderProgram().PreservesOpaqueness()||(e=!1));this._preservesOpaqueness=e}GetAllEffectTypes(){return this._allEffectTypes}HasAnyEffectType(){return this._allEffectTypes.length>0}GetEffectTypeByName(e){return this._effectTypesByName.get(e.toLowerCase())||null}GetEffectTypeByIndex(e){if((e=Math.floor(+e))<0||e>=this._allEffectTypes.length)throw new RangeError("invalid effect type index");return this._allEffectTypes[e]}IsEffectIndexActive(e){return this.GetEffectTypeByIndex(e).IsActive()}SetEffectIndexActive(e,t){this.GetEffectTypeByIndex(e).SetActive(t)}GetActiveEffectTypes(){return this._activeEffectTypes}HasAnyActiveEffect(){return this._activeEffectTypes.length>0}PreservesOpaqueness(){return this._preservesOpaqueness}GetEffectParametersForIndex(e){return this._effectParams[e]}_GetEffectChainShaderParametersForIndex(e){return e<this._effectParamBuffers.length?this._effectParamBuffers[e]:this._effectParams[e]}GetEffectParameter(e,t){if(e<0||e>=this._effectParams.length)return null;const s=this._effectParams[e];return t<0||t>=s.length?null:s[t]}SetEffectParameter(e,t,s){if(e<0||e>=this._effectParams.length)return!1;const f=this._effectParams[e];if(t<0||t>=f.length)return!1;const r=f[t];if(r instanceof C3.Color){if(r.equalsIgnoringAlpha(s))return!1;r.copyRgb(s)}else{if(r===s)return!1;f[t]=s}return e<this._effectParamBuffers.length&&this._effectParamBuffers[e].SetParameterValue(t,s),!0}_UpdateAllEffectParamBuffers(){const e=this._effectParams,t=this._effectParamBuffers;for(let s=0,f=Math.min(e.length,t.length);s<f;++s){const f=t[s],r=e[s];for(let e=0,t=r.length;e<t;++e)f.SetParameterValue(e,r[e])}}static SaveFxParamToJson(e){return e&&e instanceof C3.Color?{"t":"color","v":e.toJSON()}:e}static LoadFxParamFromJson(e){if(null===e)return NaN;if("object"==typeof e){if("color"===e["t"]){const t=C3.New(C3.Color);return t.setFromJSON(e["v"]),t}throw new Error("invalid effect parameter type")}return e}static SaveFxParamsToJson(e){return e.map(C3.EffectList.SaveFxParamToJson)}static LoadFxParamsFromJson(e){return e.map(C3.EffectList.LoadFxParamFromJson)}SaveToJson(){return this._allEffectTypes.map((e=>({"name":e.GetName(),"active":e.IsActive(),"params":C3.EffectList.SaveFxParamsToJson(this._effectParams[e.GetIndex()])})))}LoadFromJson(e){for(const t of e){const e=this.GetEffectTypeByName(t["name"]);e&&(e.SetActive(t["active"]),this._effectParams[e.GetIndex()]=C3.EffectList.LoadFxParamsFromJson(t["params"]))}this.UpdateActiveEffects(),this._UpdateAllEffectParamBuffers()}};
}

// objects/effectType.js
{
const C3=self.C3;C3.EffectType=class extends C3.DefendedBase{constructor(e,t,r){super(),this._effectList=e,this._id=t[0],this._name=t[1],this._index=r,this._shaderProgram=null,this._isActive=!0}Release(){this._effectList=null,this._shaderProgram=null}Clone(e){const t=C3.New(C3.EffectType,e,[this._id,this._name],-1);return t._shaderProgram=this._shaderProgram,t._isActive=this._isActive,t}_InitRenderer(e){const t=e.GetShaderProgramByName(this._id);if(!t)throw new Error("failed to find shader program '"+this._id+"'");this._shaderProgram=t}GetEffectList(){return this._effectList}GetName(){return this._name}_SetIndex(e){this._index=e}GetIndex(){return this._index}GetOwner(){return this._effectList.GetOwner()}GetRuntime(){return this._effectList.GetRuntime()}SetActive(e){this._isActive=!!e}IsActive(){return this._isActive}GetShaderProgram(){return this._shaderProgram}GetDefaultParameterValues(){const e=[];for(let t=0,r=this._shaderProgram.GetParameterCount();t<r;++t){const r=this._shaderProgram.GetParameterType(t);if("float"===r||"percent"===r)e.push(0);else{if("color"!==r)throw new TypeError("unknown effect parameter type");e.push(C3.New(C3.Color,1,1,1,1))}}return e}};
}

// objects/instanceEffectList.js
{
const C3=self.C3;C3.InstanceEffectList=class extends C3.DefendedBase{constructor(e,t){super(),this._inst=e,this._wi=t,this._effectList=e.GetObjectClass().GetEffectList(),this._needsRebuildSteps=!0,this._wasDefaultColor=!0,this._was3D=!1,this._wasRotatedOrNegativeSize=!1,this._wasTexRotated=!1,this._wasMustPreDraw=!1,this._effectChain=C3.New(C3.Gfx.EffectChain,e.GetRuntime().GetCanvasManager().GetEffectChainManager(),{drawContent:(e,t)=>{const s=t.GetContentObject(),f=s.GetWorldInfo();e.SetColor(f.GetPremultipliedColor()),e.SetCurrentZ(f.GetTotalZElevation()),s.Draw(e),e.SetCurrentZ(0)},getSourceTextureInfo:e=>{const t=e.GetCurrentTexRect(),[s,f]=e.GetCurrentSurfaceSize();return{srcTexRect:t,srcWidth:s,srcHeight:f}},getShaderParameters:e=>this._GetEffectChainShaderParametersForIndex(e)}),this._activeEffectFlags=[],this._activeEffectTypes=[],this._preservesOpaqueness=!0,this._effectParams=[],this._effectParamBuffers=[],this._InitRenderer(e.GetRuntime().GetRenderer());for(let e=0,t=this._effectList.GetAllEffectTypes().length;e<t;++e)this._activeEffectFlags.push(!0);this.UpdateActiveEffects(),this._effectList._AddInstanceEffectList(this)}Release(){this._effectList._RemoveInstanceEffectList(this);for(const e of this._effectParamBuffers)e&&e.Release();C3.clearArray(this._effectParamBuffers),this._effectChain.Release(),this._effectChain=null,C3.clearArray(this._activeEffectFlags),C3.clearArray(this._activeEffectTypes),C3.clearArray(this._effectParams),this._inst=null,this._effectList=null}_InitRenderer(e){e.IsWebGPU()&&(this._effectParamBuffers=this._effectList.GetAllEffectTypes().map((e=>{const t=e.GetShaderProgram();return t.GetCustomParametersByteSize()>0?C3.New(C3.Gfx.WebGPUEffectCustomParamsBuffer,t):null})))}_LoadEffectParameters(e){let t=0;for(const s of e)this._effectParams.push(this._LoadSingleEffectParameters(t,s)),++t;this._UpdateAllEffectParamBuffers(),this.UpdateActiveEffects()}_LoadSingleEffectParameters(e,t){this._activeEffectFlags[e]=t[0];const s=t.slice(1);for(let e=0,t=s.length;e<t;++e){const t=s[e];if(Array.isArray(t)){const f=C3.New(C3.Color);f.setFromJSON(t),s[e]=f}}return s}LoadDefaultEffectParameters(){for(const e of this._effectList.GetAllEffectTypes())this._effectParams.push(e.GetDefaultParameterValues());this._UpdateAllEffectParamBuffers()}GetOwner(){return this._owner}GetEffectList(){return this._effectList}GetEffectChain(){return this._MaybeRebuildEffectChainSteps(),this._effectChain}GetRuntime(){return this._inst.GetRuntime()}UpdateActiveEffects(){C3.clearArray(this._activeEffectTypes);const e=this._wi,t=this._effectList.GetAllEffectTypes(),s=this._activeEffectTypes,f=this._activeEffectFlags;let a=!0;for(let e=0,r=t.length;e<r;++e)if(f[e]){const f=t[e];s.push(f),f.GetShaderProgram().PreservesOpaqueness()||(a=!1)}this._preservesOpaqueness=a,e._SetHasAnyActiveEffect(!!s.length),this._needsRebuildSteps=!0}_MaybeRebuildEffectChainSteps(){const e=this._inst,t=this._wi,s=t.HasDefaultColor(),f=e.GetPlugin().Is3D(),a=0!==t.GetAngle()||0!==t.GetLayer().GetAngle()||t.GetWidth()<0||t.GetHeight()<0,r=e.IsCurrentTexRotated(),i=e.MustPreDraw();(this._needsRebuildSteps||s!==this._wasDefaultColor||f!==this._was3D||a!==this._wasRotatedOrNegativeSize||r!==this._wasTexRotated||i!==this._wasMustPreDraw||this._effectChain.NeedsRebuild())&&(this._effectChain.BuildSteps(this._activeEffectTypes.map((e=>e.GetShaderProgram())),{indexMap:this._activeEffectTypes.map((e=>e.GetIndex())),forcePreDraw:!s||i,is3D:f,isSourceTextureRotated:r,isRotatedOrNegativeSizeInstance:a}),this._needsRebuildSteps=!1,this._wasDefaultColor=s,this._was3D=f,this._wasRotatedOrNegativeSize=a,this._wasTexRotated=r,this._wasMustPreDraw=i)}GetActiveEffectTypes(){return this._activeEffectTypes}GetEffectParametersForIndex(e){return this._effectParams[e]}_GetEffectChainShaderParametersForIndex(e){return e<this._effectParamBuffers.length?this._effectParamBuffers[e]:this._effectParams[e]}GetEffectParameter(e,t){if(e<0||e>=this._effectParams.length)return null;const s=this._effectParams[e];return t<0||t>=s.length?null:s[t]}SetEffectParameter(e,t,s){if(e<0||e>=this._effectParams.length)return!1;const f=this._effectParams[e];if(t<0||t>=f.length)return!1;const a=f[t];if(a instanceof C3.Color){if(a.equalsIgnoringAlpha(s))return!1;a.copyRgb(s)}else{if(a===s)return!1;f[t]=s}return e<this._effectParamBuffers.length&&this._effectParamBuffers[e].SetParameterValue(t,s),!0}_UpdateAllEffectParamBuffers(){const e=this._effectParams,t=this._effectParamBuffers;for(let s=0,f=t.length;s<f;++s){const f=t[s],a=e[s];for(let e=0,t=a.length;e<t;++e)f.SetParameterValue(e,a[e])}}PreservesOpaqueness(){return this._preservesOpaqueness}HasAnyActiveBackgroundBlendingEffect(){return this._activeEffectTypes.some((e=>e.GetShaderProgram().BlendsBackground()))}IsEffectIndexActive(e){return this._activeEffectFlags[e]}SetEffectIndexActive(e,t){this._activeEffectFlags[e]=!!t}GetAllEffectTypes(){return this._effectList.GetAllEffectTypes()}_SaveToJson(){return this._effectList.GetAllEffectTypes().map((e=>({"name":e.GetName(),"active":this._activeEffectFlags[e.GetIndex()],"params":C3.EffectList.SaveFxParamsToJson(this._effectParams[e.GetIndex()])})))}_LoadFromJson(e){for(const t of e){const e=this._effectList.GetEffectTypeByName(t["name"]);e&&(this._activeEffectFlags[e.GetIndex()]=t["active"],this._effectParams[e.GetIndex()]=C3.EffectList.LoadFxParamsFromJson(t["params"]))}this.UpdateActiveEffects(),this._UpdateAllEffectParamBuffers()}};
}

// collisions/collisionEngine.js
{
const C3=self.C3,tempCandidates=[],tileCollRectCandidates=[],tempJumpthruRet=[],tempPolyA=C3.New(C3.CollisionPoly),tempPolyB=C3.New(C3.CollisionPoly),tempQuad=C3.New(C3.Quad),tempRect=C3.New(C3.Rect),tempRect2=C3.New(C3.Rect);let tempPolyC=null,tempRect3=null,tempQuadB=null;C3.CollisionEngine=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e,this._collisionCellWidth=0,this._collisionCellHeight=0,this._registeredCollisions=[],this._collisionCheckCount=0,this._collisionCheckSec=0,this._polyCheckCount=0,this._polyCheckSec=0,this._iCollisionEngine=new self.ICollisionEngine(this)}Release(){this._runtime=null}GetRuntime(){return this._runtime}GetICollisionEngine(){return this._iCollisionEngine}_Update1sStats(){this._collisionCheckSec=this._collisionCheckCount,this._collisionCheckCount=0,this._polyCheckSec=this._polyCheckCount,this._polyCheckCount=0}Get1secCollisionChecks(){return this._collisionCheckSec}Get1secPolyChecks(){return this._polyCheckSec}RegisterCollision(e,t){const s=e.GetWorldInfo(),n=t.GetWorldInfo();s&&n&&s.IsCollisionEnabled()&&n.IsCollisionEnabled()&&this._registeredCollisions.push([e,t])}AddRegisteredCollisionCandidates(e,t,s){for(const[n,l]of this._registeredCollisions){let o=null;if(e===n)o=l;else{if(e!==l)continue;o=n}o.BelongsToObjectClass(t)&&(s.includes(o)||s.push(o))}}CheckRegisteredCollision(e,t){if(!this._registeredCollisions.length)return!1;for(const[s,n]of this._registeredCollisions)if(e===s&&t===n||e===n&&t===s)return!0;return!1}ClearRegisteredCollisions(){C3.clearArray(this._registeredCollisions)}TestOverlap(e,t){if(!e||!t||e===t)return!1;const s=e.GetWorldInfo(),n=t.GetWorldInfo();if(!s.IsCollisionEnabled()||!n.IsCollisionEnabled())return!1;this._collisionCheckCount++;const l=s.GetLayer(),o=n.GetLayer();return l.IsTransformCompatibleWith(o)?this._TestOverlap_SameLayers(s,n):this._TestOverlap_DifferentLayers(s,n)}_TestOverlap_SameLayers(e,t){if(!e.GetBoundingBox().intersectsRect(t.GetBoundingBox()))return!1;if(this._polyCheckCount++,!e.GetBoundingQuad().intersectsQuad(t.GetBoundingQuad()))return!1;if(e.HasTilemap()&&t.HasTilemap())return!1;if(e.HasTilemap())return this.TestTilemapOverlap(e,t);if(t.HasTilemap())return this.TestTilemapOverlap(t,e);if(!e.HasOwnCollisionPoly()&&!t.HasOwnCollisionPoly())return!0;const s=e.GetTransformedCollisionPoly(),n=t.GetTransformedCollisionPoly();return s.intersectsPoly(n,t.GetX()-e.GetX(),t.GetY()-e.GetY())}_TestOverlap_DifferentLayers(e,t){const s=e.HasTilemap(),n=t.HasTilemap();if(s&&!n)return this.TestTilemapOverlapDifferentLayers(e,t);if(n&&!s)return this.TestTilemapOverlapDifferentLayers(t,e);if(n||s)return!1;{const s=e.GetLayer(),n=t.GetLayer();tempPolyA.copy(e.GetTransformedCollisionPoly()),tempPolyB.copy(t.GetTransformedCollisionPoly());const l=tempPolyA.pointsArr();for(let t=0,n=l.length;t<n;t+=2){const n=t+1,o=l[t],i=l[n],[r,a]=s.LayerToCanvasCss(o+e.GetX(),i+e.GetY());l[t]=r,l[n]=a}const o=tempPolyB.pointsArr();for(let e=0,s=o.length;e<s;e+=2){const s=e+1,l=o[e],i=o[s],[r,a]=n.LayerToCanvasCss(l+t.GetX(),i+t.GetY());o[e]=r,o[s]=a}return tempPolyA.setBboxChanged(),tempPolyB.setBboxChanged(),this._polyCheckCount++,tempPolyA.intersectsPoly(tempPolyB,0,0)}}TestTilemapOverlapDifferentLayers(e,t){const s=e.GetLayer(),n=t.GetLayer();tempPolyC||(tempPolyC=C3.New(C3.CollisionPoly)),tempRect3||(tempRect3=C3.New(C3.Rect)),tempQuadB||(tempQuadB=C3.New(C3.Quad));const l=t.GetX(),o=t.GetY(),[i,r]=n.LayerToCanvasCss(l,o),[a,c]=s.CanvasCssToLayer(i,r),C=a-l,d=c-o;if(tempRect3.copy(t.GetBoundingBox()),tempRect3.offset(C,d),!e.GetBoundingBox().intersectsRect(tempRect3))return!1;if(tempQuadB.copy(t.GetBoundingQuad()),tempQuadB.offset(C,d),this._polyCheckCount++,!e.GetBoundingQuad().intersectsQuad(tempQuadB))return!1;tempPolyC.copy(t.GetTransformedCollisionPoly());const u=tempPolyC.pointsArr();for(let e=0,t=u.length;e<t;e+=2){const t=e+1;u[e]+=C,u[t]+=d}return tempPolyC.setBboxChanged(),this.TestTilemapOverlap(e,t,a,c,tempPolyC,tempRect3,tempQuadB)}TestTilemapOverlap(e,t,s,n,l,o,i){const r=void 0!==o?o:t.GetBoundingBox(),a=e.GetX(),c=e.GetY(),C=e.GetInstance().GetSdkInstance(),d=void 0!==s?s:t.GetX(),u=void 0!==n?n:t.GetY(),h=t.HasOwnCollisionPoly(),p=void 0!==i?i:t.GetBoundingQuad(),f=tileCollRectCandidates;C.GetCollisionRectCandidates(r,f);for(let e=0,s=f.length;e<s;++e){const s=f[e],n=s.GetRect();if(this._collisionCheckCount++,r.intersectsRectOffset(n,a,c)&&(tempQuad.setFromRect(n),tempQuad.offset(a,c),tempQuad.intersectsQuad(p)))if(h){const e=void 0!==l?l:t.GetTransformedCollisionPoly();let o=d,i=u;void 0!==l&&(o=t.GetX(),i=t.GetY());const r=s.GetPoly();if(r){if(this._polyCheckCount++,r.intersectsPoly(e,o-(a+n.getLeft()),i-(c+n.getTop())))return C3.clearArray(f),!0}else if(tempPolyA.setFromQuad(tempQuad,0,0),tempPolyA.intersectsPoly(e,o,i))return C3.clearArray(f),!0}else{const e=s.GetPoly();if(!e)return C3.clearArray(f),!0;if(tempPolyA.setFromQuad(p,0,0),e.intersectsPoly(tempPolyA,-(a+n.getLeft()),-(c+n.getTop())))return C3.clearArray(f),!0}}return C3.clearArray(f),!1}TestAndSelectCanvasPointOverlap(e,t,s){const n=e.GetCurrentSol(),l=this._runtime.GetCurrentEvent();if(!l)throw new Error("cannot call outside event");const o=l.IsOrBlock(),i=new C3.LayerStateCache;if(n.IsSelectAll()){s||(n._SetSelectAll(!1),C3.clearArray(n._GetOwnInstances())),o&&C3.clearArray(n._GetOwnElseInstances());for(const l of e.GetInstances()){const e=l.GetWorldInfo(),r=e.GetLayer();let a=!1;if(i.IsInteractive(r)&&e.IsInViewport2()&&(a=t.some((([t,s])=>{const[n,l]=i.CanvasCssToLayer(r,t,s,e.GetTotalZElevation());return e.ContainsPoint(n,l)}))),a){if(s)return!1;n._PushInstance(l)}else o&&n._PushElseInstance(l)}}else{let e,r=!1;o&&!l.IsFirstConditionOfType(this._runtime.GetCurrentCondition())?this._runtime.IsCurrentConditionFirst()&&!n._GetOwnElseInstances().length&&n._GetOwnInstances().length?e=n._GetOwnInstances():(e=n._GetOwnElseInstances(),r=!0):e=n._GetOwnInstances();let a=0;for(let l=0,c=e.length;l<c;++l){const c=e[l],C=c.GetWorldInfo(),d=C.GetLayer();let u=!1;if(i.IsInteractive(d)&&C.IsInViewport2()&&(u=t.some((([e,t])=>{const[s,n]=i.CanvasCssToLayer(d,e,t,C.GetTotalZElevation());return C.ContainsPoint(s,n)}))),u){if(s)return!1;r?n._PushInstance(c):e[a++]=c}else r?e[a++]=c:o&&n._PushElseInstance(c)}s||(e.length=a)}return e.ApplySolToContainer(),i.Release(),!!s||n.HasAnyInstances()}_ObjectClassCanUseCollisionCells(e,t){if(!e)return!0;for(const s of t.layersHasInstancesOn())if(!e.IsTransformCompatibleWith(s))return!1;return!0}GetCollisionCandidates(e,t,s,n){if(t.IsFamily())for(const l of t.GetFamilyMembers())this._ObjectClassCanUseCollisionCells(e,l)?(l._UpdateAllCollisionCells(),l._GetCollisionCellGrid().QueryRange(s,n)):C3.appendArray(n,l.GetInstances());else this._ObjectClassCanUseCollisionCells(e,t)?(t._UpdateAllCollisionCells(),t._GetCollisionCellGrid().QueryRange(s,n)):C3.appendArray(n,t.GetInstances())}GetObjectClassesCollisionCandidates(e,t,s,n){for(const l of t)this.GetCollisionCandidates(e,l,s,n)}GetSolidCollisionCandidates(e,t,s){const n=this._runtime.GetSolidBehavior();n&&this.GetObjectClassesCollisionCandidates(e,n.GetObjectClasses(),t,s)}GetJumpthruCollisionCandidates(e,t,s){const n=this._runtime.GetJumpthruBehavior();n&&this.GetObjectClassesCollisionCandidates(e,n.GetObjectClasses(),t,s)}IsSolidCollisionAllowed(e,t){return e._IsSolidEnabled()&&(!t||t.GetWorldInfo().IsSolidCollisionAllowed(e.GetSavedDataMap().get("solidTags")))}TestOverlapSolid(e){const t=e.GetWorldInfo();this.GetSolidCollisionCandidates(t.GetLayer(),t.GetBoundingBox(),tempCandidates);for(const t of tempCandidates)if(this.IsSolidCollisionAllowed(t,e)&&this.TestOverlap(e,t))return C3.clearArray(tempCandidates),t;return C3.clearArray(tempCandidates),null}TestRectOverlapSolid(e,t){this.GetSolidCollisionCandidates(null,e,tempCandidates);for(const s of tempCandidates)if(this.IsSolidCollisionAllowed(s,t)&&this.TestRectOverlap(e,s))return C3.clearArray(tempCandidates),s;return C3.clearArray(tempCandidates),null}TestOverlapJumpthru(e,t){let s=null;t&&(s=tempJumpthruRet,C3.clearArray(s));const n=e.GetWorldInfo();this.GetJumpthruCollisionCandidates(n.GetLayer(),n.GetBoundingBox(),tempCandidates);for(const n of tempCandidates)if(n._IsJumpthruEnabled()&&this.TestOverlap(e,n)){if(!t)return C3.clearArray(tempCandidates),n;s.push(n)}return C3.clearArray(tempCandidates),s}PushOut(e,t,s,n,l){n=n||50;const o=e.GetWorldInfo(),i=o.GetX(),r=o.GetY();for(let a=0;a<n;++a)if(o.SetXY(i+t*a,r+s*a),o.SetBboxChanged(),!this.TestOverlap(e,l))return!0;return o.SetXY(i,r),o.SetBboxChanged(),!1}PushOutSolid(e,t,s,n,l,o){n=n||50;const i=e.GetWorldInfo(),r=i.GetX(),a=i.GetY();let c=null,C=null;for(let d=0;d<n;++d)if(i.SetXY(r+t*d,a+s*d),i.SetBboxChanged(),!this.TestOverlap(e,c))if(c=this.TestOverlapSolid(e),c)C=c;else if(l&&(c=o?this.TestOverlap(e,o)?o:null:this.TestOverlapJumpthru(e),c&&(C=c)),!c)return C&&this.PushInFractional(e,t,s,C,16,!0),!0;return i.SetXY(r,a),i.SetBboxChanged(),!1}PushOutSolidAxis(e,t,s,n){n=n||50;const l=e.GetWorldInfo(),o=l.GetX(),i=l.GetY();let r=null,a=null;for(let c=0;c<n;++c)for(let n=0;n<2;++n){const C=2*n-1;if(l.SetXY(o+t*c*C,i+s*c*C),l.SetBboxChanged(),!this.TestOverlap(e,r)){if(r=this.TestOverlapSolid(e),!r)return a&&this.PushInFractional(e,t*C,s*C,a,16,!0),!0;a=r}}return l.SetXY(o,i),l.SetBboxChanged(),!1}PushInFractional(e,t,s,n,l,o){let i=2,r=!1,a=!1;const c=e.GetWorldInfo();let C=c.GetX(),d=c.GetY();for(;i<=l;){const l=1/i;i*=2,c.OffsetXY(t*l*(r?1:-1),s*l*(r?1:-1)),c.SetBboxChanged(),this.TestOverlap(e,n)||o&&this.TestOverlapSolid(e)?(r=!0,a=!0):(r=!1,a=!1,C=c.GetX(),d=c.GetY())}a&&(c.SetXY(C,d),c.SetBboxChanged())}PushOutSolidNearest(e,t=100){let s=0;const n=e.GetWorldInfo(),l=n.GetX(),o=n.GetY();let i=0,r=this.TestOverlapSolid(e);if(!r)return!0;for(;s<=t;){let t=0,a=0;switch(i){case 0:t=0,a=-1,s++;break;case 1:t=1,a=-1;break;case 2:t=1,a=0;break;case 3:t=1,a=1;break;case 4:t=0,a=1;break;case 5:t=-1,a=1;break;case 6:t=-1,a=0;break;case 7:t=-1,a=-1}if(i=(i+1)%8,n.SetXY(Math.floor(l+t*s),Math.floor(o+a*s)),n.SetBboxChanged(),!this.TestOverlap(e,r)&&(r=this.TestOverlapSolid(e),!r))return!0}return n.SetXY(l,o),n.SetBboxChanged(),!1}CalculateBounceAngle(e,t,s,n){const l=e.GetWorldInfo(),o=l.GetX(),i=l.GetY(),r=Math.max(10,C3.distanceTo(t,s,o,i)),a=C3.angleTo(t,s,o,i),c=n||this.TestOverlapSolid(e);if(!c)return C3.clampAngle(a+Math.PI);let C=c,d=0,u=0;const h=C3.toRadians(5);let p;for(p=1;p<36;++p){const o=a-p*h;if(l.SetXY(t+Math.cos(o)*r,s+Math.sin(o)*r),l.SetBboxChanged(),!this.TestOverlap(e,C)&&(C=n?null:this.TestOverlapSolid(e),!C)){d=o;break}}for(36===p&&(d=C3.clampAngle(a+Math.PI)),C=c,p=1;p<36;++p){const o=a+p*h;if(l.SetXY(t+Math.cos(o)*r,s+Math.sin(o)*r),l.SetBboxChanged(),!this.TestOverlap(e,C)&&(C=n?null:this.TestOverlapSolid(e),!C)){u=o;break}}if(36===p&&(u=C3.clampAngle(a+Math.PI)),l.SetXY(o,i),l.SetBboxChanged(),u===d)return u;const f=C3.angleDiff(u,d)/2;let G;G=C3.angleClockwise(u,d)?C3.clampAngle(d+f+Math.PI):C3.clampAngle(u+f);const m=Math.cos(a),y=Math.sin(a),g=Math.cos(G),T=Math.sin(G),_=m*g+y*T,I=m-2*_*g,S=y-2*_*T;return C3.angleTo(0,0,I,S)}TestSegmentOverlap(e,t,s,n,l){if(!l)return!1;const o=l.GetWorldInfo();if(!o.IsCollisionEnabled())return!1;if(this._collisionCheckCount++,tempRect.set(Math.min(e,s),Math.min(t,n),Math.max(e,s),Math.max(t,n)),!o.GetBoundingBox().intersectsRect(tempRect))return!1;if(l.HasTilemap())return this._TestSegmentOverlapTilemap(e,t,s,n,l,o);if(this._polyCheckCount++,!o.GetBoundingQuad().intersectsSegment(e,t,s,n))return!1;if(!o.HasOwnCollisionPoly())return!0;return o.GetTransformedCollisionPoly().intersectsSegment(o.GetX(),o.GetY(),e,t,s,n)}_TestSegmentOverlapTilemap(e,t,s,n,l,o){const i=o.GetX(),r=o.GetY(),a=l.GetSdkInstance(),c=tileCollRectCandidates;tempRect2.set(e,t,s,n),tempRect2.normalize(),a.GetCollisionRectCandidates(tempRect2,c);for(let l=0,o=c.length;l<o;++l){const o=c[l],a=o.GetRect();if(this._collisionCheckCount++,tempRect.intersectsRectOffset(a,i,r)&&(tempQuad.setFromRect(a),tempQuad.offset(i,r),tempQuad.intersectsSegment(e,t,s,n))){const l=o.GetPoly();if(!l)return C3.clearArray(c),!0;if(this._polyCheckCount++,l.intersectsSegment(i+a.getLeft(),r+a.getTop(),e,t,s,n))return C3.clearArray(c),!0}}return C3.clearArray(c),!1}TestRectOverlap(e,t){if(!t)return!1;const s=t.GetWorldInfo();if(!s.IsCollisionEnabled())return!1;if(this._collisionCheckCount++,!s.GetBoundingBox().intersectsRect(e))return!1;if(t.HasTilemap())return this._TestRectOverlapTilemap(e,t,s);if(this._polyCheckCount++,tempQuad.setFromRect(e),!s.GetBoundingQuad().intersectsQuad(tempQuad))return!1;if(!s.HasOwnCollisionPoly())return!0;const n=tempPolyA;n.setFromRect(e,s.GetX(),s.GetY());const l=s.GetTransformedCollisionPoly();return n.intersectsPoly(l,0,0)}_TestRectOverlapTilemap(e,t,s){const n=s.GetX(),l=s.GetY(),o=t.GetSdkInstance(),i=tileCollRectCandidates;o.GetCollisionRectCandidates(e,i);for(let t=0,s=i.length;t<s;++t){const s=i[t],o=s.GetRect();if(this._collisionCheckCount++,e.intersectsRectOffset(o,n,l)){const t=s.GetPoly();if(!t)return C3.clearArray(i),!0;if(this._polyCheckCount++,tempPolyA.setFromRect(e,0,0),t.intersectsPoly(tempPolyA,-(n+o.getLeft()),-(l+o.getTop())))return C3.clearArray(i),!0}}return C3.clearArray(i),!1}TestRayIntersectsInstance(e,t){if(!e)return;const s=e.GetWorldInfo();s.IsCollisionEnabled()&&(this._collisionCheckCount++,s.GetBoundingBox().intersectsRect(t.rect)&&(e.HasTilemap()?this._TestRayIntersectsTilemap(e,s,t):(this._polyCheckCount++,s.HasOwnCollisionPoly()?t.TestInstancePoly(e,s.GetX(),s.GetY(),s.GetTransformedCollisionPoly()):t.TestInstanceQuad(e,s.GetBoundingQuad()))))}_TestRayIntersectsTilemap(e,t,s){const n=t.GetX(),l=t.GetY(),o=tileCollRectCandidates;e.GetSdkInstance().GetCollisionRectCandidates(s.rect,o);for(let i=0,r=o.length;i<r;i++){const r=o[i],a=r.GetRect();if(this._collisionCheckCount++,s.rect.intersectsRectOffset(a,n,l)){const o=r.GetPoly();this._polyCheckCount++,o?s.TestInstancePoly(e,n+a.getLeft(),l+a.getTop(),o):s.TestInstanceRect(e,t.GetX(),t.GetY(),a)}}C3.clearArray(o)}SetCollisionCellSize(e,t){if(e===this._collisionCellWidth&&t===this._collisionCellHeight)return;this._collisionCellWidth=e,this._collisionCellHeight=t;const s=this._runtime.GetAllObjectClasses();for(const n of s)if(n.IsWorldType()){for(const e of n.instancesIncludingPendingCreate())e.GetWorldInfo()._RemoveFromCollisionCells();n._GetCollisionCellGrid().SetCellSize(e,t),n._SetAnyCollisionCellChanged();for(const e of n.instancesIncludingPendingCreate()){const t=e.GetWorldInfo();t._SetCollisionCellChanged(),t._UpdateCollisionCell()}}}GetCollisionCellSize(){return[this._collisionCellWidth,this._collisionCellHeight]}_InitCollisionCellSize(e,t){this._collisionCellWidth=e,this._collisionCellHeight=t}};
}

// collisions/sparseGrid.js
{
const C3=self.C3;C3.SparseGrid=class extends C3.DefendedBase{constructor(t,e){super(),this._cellWidth=t,this._cellHeight=e,this._cells=C3.New(C3.PairMap)}Release(){this._cells.Release(),this._cells=null}SetCellSize(t,e){if(!this._cells.IsEmpty())throw new Error("grid not empty");this._cellWidth=t,this._cellHeight=e}GetCell(t,e,l){let i=this._cells.Get(t,e);return i||(l?(i=C3.New(C3.GridCell,this,t,e),this._cells.Set(t,e,i),i):null)}XToCell(t){const e=Math.floor(t/this._cellWidth);return isFinite(e)?e:0}YToCell(t){const e=Math.floor(t/this._cellHeight);return isFinite(e)?e:0}Update(t,e,l){if(e)for(let i=e.getLeft(),s=e.getRight();i<=s;++i)for(let s=e.getTop(),o=e.getBottom();s<=o;++s){if(l&&l.containsPoint(i,s))continue;const e=this.GetCell(i,s,!1);e&&(e.Remove(t),e.IsEmpty()&&this._cells.Delete(i,s))}if(l)for(let i=l.getLeft(),s=l.getRight();i<=s;++i)for(let s=l.getTop(),o=l.getBottom();s<=o;++s)e&&e.containsPoint(i,s)||this.GetCell(i,s,!0).Insert(t)}QueryRange(t,e){let l=this.XToCell(t.getLeft());const i=this.YToCell(t.getTop()),s=this.XToCell(t.getRight()),o=this.YToCell(t.getBottom());if(isFinite(s)&&isFinite(o))for(;l<=s;++l)for(let t=i;t<=o;++t){const i=this.GetCell(l,t,!1);i&&i.Dump(e)}}};
}

// collisions/gridCell.js
{
const C3=self.C3;C3.GridCell=class extends C3.DefendedBase{constructor(s,e,t){super(),this._grid=s,this._x=e,this._y=t,this._instances=C3.New(C3.ArraySet)}Release(){this._instances.Release(),this._instances=null,this._grid=null}IsEmpty(){return this._instances.IsEmpty()}Insert(s){this._instances.Add(s)}Remove(s){this._instances.Delete(s)}Dump(s){C3.appendArray(s,this._instances.GetArray())}};
}

// collisions/ray.js
{
const C3=self.C3,PADDING=1e-6,NO_HIT=2;C3.Ray=class{constructor(){this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.dx=0,this.dy=0,this.rect=new C3.Rect,this.hitFraction=2,this.hitUid=null,this.hitNormal=0,this.hitNormalDx=0,this.hitNormalDy=0,this.hitX=0,this.hitY=0,this.distance=0,this.normalX=1,this.normalY=0,this.reflectionX=1,this.reflectionY=0}DidCollide(){return this.hitFraction<1.000001}Reset(){this.hitFraction=2}Set(t,i,s,h){return this.x1=t,this.y1=i,this.x2=s,this.y2=h,this.dx=s-t,this.dy=h-i,this.rect.set(t,i,s,h),this.rect.normalize(),this.hitFraction=2,this.hitUid=null,this.hitNormal=0,this.hitNormalDx=0,this.hitNormalDy=0,this.hitX=0,this.hitY=0,this.distance=0,this.normalX=1,this.normalY=0,this.reflectionX=1,this.reflectionY=0,this}Complete(){if(!1===this.DidCollide())return;const t=this.dx*this.hitFraction,i=this.dy*this.hitFraction,s=C3.hypot2DFast(t,i),h=t/s,e=i/s;this.distance=s-PADDING,this.hitX=this.x1+h*this.distance,this.hitY=this.y1+e*this.distance,this.hitNormal=Math.atan2(this.hitNormalDy,this.hitNormalDx)+Math.PI/2,this.normalX=Math.cos(this.hitNormal),this.normalY=Math.sin(this.hitNormal);const n=h*this.normalX+e*this.normalY;if(this.reflectionX=h-2*this.normalX*n,this.reflectionY=e-2*this.normalY*n,n>0){const t=Math.PI;this.hitNormal=C3.clampAngle(this.hitNormal+t),this.normalX=-this.normalX,this.normalY=-this.normalY}}TestInstanceSegment(t,i,s,h,e){const n=C3.rayIntersect(this.x1,this.y1,this.x2,this.y2,i,s,h,e);n>=0&&n<this.hitFraction&&(this.hitFraction=n,this.hitUid=t.GetUID(),this.hitNormalDx=i-h,this.hitNormalDy=s-e)}TestInstanceRect(t,i,s,h){const e=i+h.getLeft(),n=i+h.getRight(),a=s+h.getTop(),o=s+h.getBottom();this.TestInstanceSegment(t,e,a,n,a),this.TestInstanceSegment(t,n,a,n,o),this.TestInstanceSegment(t,n,o,e,o),this.TestInstanceSegment(t,e,o,e,a)}TestInstanceQuad(t,i){const s=i.getTlx(),h=i.getTly(),e=i.getTrx(),n=i.getTry(),a=i.getBrx(),o=i.getBry(),r=i.getBlx(),l=i.getBly();this.TestInstanceSegment(t,s,h,e,n),this.TestInstanceSegment(t,e,n,a,o),this.TestInstanceSegment(t,a,o,r,l),this.TestInstanceSegment(t,r,l,s,h)}TestInstancePoly(t,i,s,h){const e=h.pointsArr();for(let h=0,n=e.length;h<n;h+=2){const a=(h+2)%n,o=e[h]+i,r=e[h+1]+s,l=e[a]+i,c=e[a+1]+s;this.TestInstanceSegment(t,o,r,l,c)}}};
}

// collisions/layerStateCache.js
{
const C3=self.C3;C3.LayerStateCache=class{constructor(){this._layerCache=new Map}Release(){for(const e of this._layerCache.values())e.layerPts.Clear();this._layerCache.clear()}_GetLayerCache(e){let a=this._layerCache.get(e);return void 0===a&&(a={isInteractive:null,layerPts:new C3.PairMap},this._layerCache.set(e,a)),a}IsInteractive(e){const a=this._GetLayerCache(e);return null===a.isInteractive&&(a.isInteractive=e.IsSelfAndParentsInteractive()),a.isInteractive}CanvasCssToLayer(e,a,t,s){if(0!==s)return e.CanvasCssToLayer(a,t,s);const r=this._GetLayerCache(e);let n=r.layerPts.Get(a,t);return void 0===n&&(n=e.CanvasCssToLayer(a,t,s),r.layerPts.Set(a,t,n)),n}};
}

// canvasManager.js
{
const C3=self.C3,VALID_FULLSCREEN_MODES=new Set(["off","crop","scale-inner","scale-outer","letterbox-scale","letterbox-integer-scale"]),VALID_FULLSCREEN_SCALING_QUALITIES=new Set(["high","low"]),glMatrix=self.glMatrix,mat4=glMatrix.mat4,vec3=glMatrix.vec3,tempProjection=mat4.create(),PERCENTTEXT_WIDTH=300,PERCENTTEXT_HEIGHT=200,PROGRESSBAR_WIDTH=120,PROGRESSBAR_HEIGHT=8,tempQuad=C3.New(C3.Quad),tempRect=C3.New(C3.Rect),SPLASH_MIN_DISPLAY_TIME=3e3,SPLASH_AFTER_FADEOUT_WAIT_TIME=200,SPLASH_FADE_DURATION=300;C3.CanvasManager=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e,this._canvasLayers=[],this._isWebGPUEnabled=!1,this._webglRenderer=null,this._webgpuRenderer=null,this._iRenderer=null,this._gpuPreference="high-performance",this._isLimitedToWebGL1=!1,this._multitexturingMode="auto",this._windowInnerWidth=0,this._windowInnerHeight=0,this._cssDisplayMode="",this._canvasCssWidth=0,this._canvasCssHeight=0,this._canvasDeviceWidth=0,this._canvasDeviceHeight=0,this._canvasCssOffsetX=0,this._canvasCssOffsetY=0,this._zAxisScale="normalized",this._initFieldOfView=0,this._zNear=1,this._zFar=1e4,this._enableMipmaps=!0,this._textureAnisotropy=0,this._drawWidth=0,this._drawHeight=0,this._fullscreenMode="letterbox-scale",this._documentFullscreenMode="letterbox-scale",this._deviceTransformOffX=0,this._deviceTransformOffY=0,this._defaultProjectionMatrix=mat4.create(),this._wantFullscreenScalingQuality="high",this._fullscreenScalingQuality=this._wantFullscreenScalingQuality,this._isDocumentFullscreen=!1,this._availableAdditionalRenderTargets=[],this._usedAdditionalRenderTargets=new Set,this._shaderData=self["C3_Shaders"],this._effectChainManager=C3.New(C3.Gfx.EffectChainManager,{getDrawSize:()=>[this.GetDrawWidth(),this.GetDrawHeight()],getRenderTarget:()=>this.GetEffectCompositorRenderTarget(),releaseRenderTarget:e=>this.ReleaseEffectCompositorRenderTarget(e),getTime:()=>this.GetRuntime().GetGameTime(),redraw:()=>this.GetRuntime().UpdateRender()}),this._gpuTimeStartFrame=0,this._gpuTimeEndFrame=0,this._gpuLastUtilisation=NaN,this._gpuFrameTimingsBuffer=null,this._layersGpuProfile=new Map,this._gpuCurUtilisation=NaN,this._webgpuFrameTimings=new Map,this._snapshotFormat="",this._snapshotQuality=1,this._snapshotArea=C3.New(C3.Rect),this._snapshotUrl="",this._snapshotPromise=null,this._snapshotResolve=null,this._isPastingToDrawingCanvas=0,this._loaderStartTime=0,this._rafId=-1,this._loadingProgress=0,this._loadingprogress_handler=e=>this._loadingProgress=e.progress,this._percentText=null,this._splashTextures={logo:null,powered:null,website:null},this._splashFrameNumber=0,this._splashFadeInFinishTime=0,this._splashFadeOutStartTime=0,this._splashState="fade-in",this._splashDoneResolve=null,this._splashDonePromise=new Promise((e=>this._splashDoneResolve=e))}_SetGPUPowerPreference(e){this._gpuPreference=e}_SetWebGPUEnabled(e){this._isWebGPUEnabled=!!e}_SetZAxisScale(e){this._zAxisScale=e}GetZAxisScale(){return this._zAxisScale}_SetInitFieldOfView(e){this._initFieldOfView=e}_SetZDistances(e,t){this._zNear=e,this._zFar=t}_SetLimitedToWebGL1(e){this._isLimitedToWebGL1=!!e}_SetMultitexturingMode(e){this._multitexturingMode=e}async CreateCanvas(e){let t=e["canvas"];this._canvasLayers.push({canvas:t,ctx:null}),this._runtime.AddDOMComponentMessageHandler("runtime","window-resize",(e=>this._OnWindowResize(e))),this._runtime.AddDOMComponentMessageHandler("runtime","fullscreenchange",(e=>this._OnFullscreenChange(e))),this._runtime.AddDOMComponentMessageHandler("runtime","fullscreenerror",(e=>this._OnFullscreenError(e))),t.addEventListener("webglcontextlost",(e=>this._OnWebGLContextLost(e))),t.addEventListener("webglcontextrestored",(e=>this._OnWebGLContextRestored(e))),this._isDocumentFullscreen=!!e["isFullscreen"],this._cssDisplayMode=e["cssDisplayMode"];const s=navigator["gpu"]&&this._isWebGPUEnabled;let i=!1;if(s)try{await this._InitWebGPUContext(!0)}catch(e){this._MaybeLogRendererError("WebGPU",e),this._webgpuRenderer=null}if(!this.GetRenderer())try{await this._InitWebGLContext(!0)}catch(e){this._MaybeLogRendererError("WebGL",e),this._webglRenderer=null}if(this.GetRenderer()||(i=!0),!this.GetRenderer()&&s)try{await this._InitWebGPUContext(!1)}catch(e){this._MaybeLogRendererError("WebGPU",e),this._webgpuRenderer=null}if(!this.GetRenderer())try{await this._InitWebGLContext(!1)}catch(e){this._MaybeLogRendererError("WebGL",e),this._webglRenderer=null}const r=this.GetRenderer();if(!r)throw new Error("failed to acquire a renderer - check WebGL or WebGPU is supported");r.SetHasMajorPerformanceCaveat(i),this._webgpuRenderer&&(this._webgpuRenderer.ondevicelost=()=>this._OnWebGPUDeviceLost(),this._webgpuRenderer.ondevicerestored=()=>this._OnWebGPUDeviceRestored()),"normalized"===this._zAxisScale?r.SetZAxisScaleNormalized():(r.SetZAxisScaleRegular(),r.SetFovY(this._initFieldOfView)),this.SetSize(e["windowInnerWidth"],e["windowInnerHeight"],!0),await this._InitRenderer()}_MaybeLogRendererError(e,t){t&&"string"==typeof t.message&&t.message.startsWith("renderer-unavailable")||console.error(`Error creating ${e} renderer: `,t)}async _InitWebGPUContext(e){const t={nearZ:this._zNear,farZ:this._zFar};let s=!0;"no"===this._multitexturingMode?s=!1:"auto"===this._multitexturingMode&&(s=C3.Platform.IsDesktop);const i={powerPreference:this._gpuPreference,depth:this._runtime.Uses3DFeatures(),failIfMajorPerformanceCaveat:e,usesBackgroundBlending:this._runtime.UsesAnyBackgroundBlending(),canSampleBackbuffer:this._runtime.UsesAnyCrossSampling(),canSampleDepth:this._runtime.UsesAnyDepthSampling(),isMultiTexturingAllowed:s};this._webgpuRenderer=C3.New(C3.Gfx.WebGPURenderer,t),await this._webgpuRenderer.Create(this._canvasLayers[0].canvas,i)}async _InitWebGLContext(e){const t={alpha:!0,powerPreference:this._gpuPreference,enableGpuProfiling:"xbox-uwp-webview2"!==this._runtime.GetExportType(),depth:this._runtime.Uses3DFeatures(),canSampleDepth:this._runtime.UsesAnyDepthSampling(),failIfMajorPerformanceCaveat:e,nearZ:this._zNear,farZ:this._zFar};this._isLimitedToWebGL1&&(t.maxWebGLVersion=1),this._webglRenderer=C3.New(C3.Gfx.WebGLRenderer,this._canvasLayers[0].canvas,t),await this._webglRenderer.InitState()}async _InitWebGPU(){if(this._shaderData){const e=[];for(const[t,s]of Object.entries(this._shaderData)){s.src=s.wgsl;const i=C3.Gfx.WebGPUShaderProgram.GetDefaultVertexShaderSource(this._webgpuRenderer.IsColorDataF16());e.push(this._webgpuRenderer.CreateShaderProgram(Object.assign({vertexSrc:i,name:t},s)))}await Promise.all(e)}}async _InitWebGL(){if(this._shaderData){const e=[];for(const[t,s]of Object.entries(this._shaderData)){let i;if(s.glslWebGL2&&this._webglRenderer.GetWebGLVersionNumber()>=2)s.src=s.glslWebGL2,i=C3.Gfx.WebGLShaderProgram.GetDefaultVertexShaderSource_WebGL2();else{if(!s.glsl)throw new Error(`shader '${t}' does not support WebGL 1`);s.src=s.glsl,i=C3.Gfx.WebGLShaderProgram.GetDefaultVertexShaderSource()}e.push(this._webglRenderer.CreateShaderProgram(Object.assign({vertexSrc:i,name:t},s)))}await Promise.all(e),this._webglRenderer.ResetLastProgram(),this._webglRenderer.SetTextureFillMode()}this._webglRenderer.SupportsGPUProfiling()&&(this._gpuFrameTimingsBuffer=C3.New(C3.Gfx.WebGLQueryResultBuffer,this._webglRenderer))}async _InitRenderer(){this._webgpuRenderer?await this._InitWebGPU():this._webglRenderer&&await this._InitWebGL();const e=this.GetRenderer();e.SetMipmapsEnabled(this._enableMipmaps),e.SupportsGPUProfiling()&&(this._gpuLastUtilisation=0);for(const t of this._runtime._GetAllEffectLists()){for(const s of t.GetAllEffectTypes())s._InitRenderer(e);t._InitRenderer(e),t.UpdateActiveEffects()}this._iRenderer=new self.IRenderer(this._runtime,e)}Release(){this._runtime=null,this._webglRenderer=null,this._canvasLayers.length=0}IsInWorker(){return this._runtime.IsInWorker()}_OnWindowResize(e){const t=this._runtime;if(t.IsExportToVideo())return;const s=e["devicePixelRatio"];this.IsInWorker()&&(self.devicePixelRatio=s),t._SetDevicePixelRatio(s),this._isDocumentFullscreen=!!e["isFullscreen"],this._cssDisplayMode=e["cssDisplayMode"],this.SetSize(e["innerWidth"],e["innerHeight"]),t.UpdateRender();const i=new C3.Event("window-resize");i.data=e,t.Dispatcher().dispatchEventAndWaitAsyncSequential(i);const r=new C3.Event("resize");r.cssWidth=this.GetCssWidth(),r.cssHeight=this.GetCssHeight(),r.deviceWidth=this.GetDeviceWidth(),r.deviceHeight=this.GetDeviceHeight(),t.DispatchUserScriptEvent(r),this._runtime.GetCurrentLayout()?.BoundScrolling(),t.IsDebug()&&(t.HitBreakpoint()||self.C3Debugger.IsDebuggerPaused())&&t.Render()}_OnFullscreenChange(e){this._isDocumentFullscreen=!!e["isFullscreen"],this.SetSize(e["innerWidth"],e["innerHeight"],!0),this._runtime.UpdateRender()}_OnFullscreenError(e){this._isDocumentFullscreen=!!e["isFullscreen"],this.SetSize(e["innerWidth"],e["innerHeight"],!0),this._runtime.UpdateRender()}SetSize(e,t,s=!1){if(e=Math.floor(e),t=Math.floor(t),e<=0||t<=0)throw new Error("invalid size");if(this._windowInnerWidth===e&&this._windowInnerHeight===t&&!s)return;this._windowInnerWidth=e,this._windowInnerHeight=t;const i=this.GetCurrentFullscreenMode();"letterbox-scale"===i?this._CalculateLetterboxScale(e,t):"letterbox-integer-scale"===i?this._CalculateLetterboxIntegerScale(e,t):"off"===i?this._CalculateFixedSizeCanvas(e,t):this._CalculateFullsizeCanvas(e,t),this._UpdateFullscreenScalingQuality(i);for(const{canvas:e}of this._canvasLayers)e.width=this._canvasDeviceWidth,e.height=this._canvasDeviceHeight;this._runtime.PostComponentMessageToDOM("canvas","update-size",{"marginLeft":this._canvasCssOffsetX,"marginTop":this._canvasCssOffsetY,"styleWidth":this._canvasCssWidth,"styleHeight":this._canvasCssHeight,"displayScale":this.GetDisplayScale()});const r=this.GetRenderer();r.SetSize(this._canvasDeviceWidth,this._canvasDeviceHeight,!0);for(const e of this._availableAdditionalRenderTargets)r.DeleteRenderTarget(e);C3.clearArray(this._availableAdditionalRenderTargets),this.UpdateDefaultProjectionMatrix();const a=this._runtime.GetLayoutManager();a.SetAllLayerProjectionChanged(),a.SetAllLayerMVChanged()}UpdateDefaultProjectionMatrix(){this.GetRenderer().CalculatePerspectiveMatrix(this._defaultProjectionMatrix,this.GetDrawWidth()/this.GetDrawHeight())}GetDefaultProjectionMatrix(){return this._defaultProjectionMatrix}_CalculateLetterboxScale(e,t){const s=this._runtime.GetDevicePixelRatio(),i=this._runtime.GetOriginalViewportWidth(),r=this._runtime.GetOriginalViewportHeight(),a=i/r;if(e/t>a){const s=t*a;this._canvasCssWidth=Math.round(s),this._canvasCssHeight=t,this._canvasCssOffsetX=Math.floor((e-this._canvasCssWidth)/2),this._canvasCssOffsetY=0}else{const s=e/a;this._canvasCssWidth=e,this._canvasCssHeight=Math.round(s),this._canvasCssOffsetX=0,this._canvasCssOffsetY=Math.floor((t-this._canvasCssHeight)/2)}this._canvasDeviceWidth=Math.round(this._canvasCssWidth*s),this._canvasDeviceHeight=Math.round(this._canvasCssHeight*s),this._runtime.SetViewportSize(i,r)}_CalculateLetterboxIntegerScale(e,t){const s=this._runtime.GetDevicePixelRatio();1!==s&&(e+=1,t+=1);const i=this._runtime.GetOriginalViewportWidth(),r=this._runtime.GetOriginalViewportHeight(),a=i/r;let n;if(e/t>a){n=t*a*s/i}else{n=e/a*s/r}n>1?n=Math.floor(n):n<1&&(n=1/Math.ceil(1/n)),this._canvasDeviceWidth=Math.round(i*n),this._canvasDeviceHeight=Math.round(r*n),this._canvasCssWidth=this._canvasDeviceWidth/s,this._canvasCssHeight=this._canvasDeviceHeight/s,this._canvasCssOffsetX=Math.max(Math.floor((e-this._canvasCssWidth)/2),0),this._canvasCssOffsetY=Math.max(Math.floor((t-this._canvasCssHeight)/2),0),this._runtime.SetViewportSize(i,r)}_CalculateFullsizeCanvas(e,t){const s=this._runtime.GetDevicePixelRatio();this._canvasCssWidth=e,this._canvasCssHeight=t,this._canvasDeviceWidth=Math.round(this._canvasCssWidth*s),this._canvasDeviceHeight=Math.round(this._canvasCssHeight*s),this._canvasCssOffsetX=0,this._canvasCssOffsetY=0;const i=this.GetDisplayScale();this._runtime.SetViewportSize(this._canvasCssWidth/i,this._canvasCssHeight/i)}_CalculateFixedSizeCanvas(e,t){const s=this._runtime.GetDevicePixelRatio();this._canvasCssWidth=this._runtime.GetViewportWidth(),this._canvasCssHeight=this._runtime.GetViewportHeight(),this._canvasDeviceWidth=Math.round(this._canvasCssWidth*s),this._canvasDeviceHeight=Math.round(this._canvasCssHeight*s),this.IsDocumentFullscreen()?(this._canvasCssOffsetX=Math.floor((e-this._canvasCssWidth)/2),this._canvasCssOffsetY=Math.floor((t-this._canvasCssHeight)/2)):(this._canvasCssOffsetX=0,this._canvasCssOffsetY=0),this._runtime.SetViewportSize(this._runtime.GetViewportWidth(),this._runtime.GetViewportHeight())}_UpdateFullscreenScalingQuality(e){if("high"===this._wantFullscreenScalingQuality)this._drawWidth=this._canvasDeviceWidth,this._drawHeight=this._canvasDeviceHeight,this._fullscreenScalingQuality="high";else{let t,s;if("off"===this.GetCurrentFullscreenMode()?(t=this._runtime.GetViewportWidth(),s=this._runtime.GetViewportHeight()):(t=this._runtime.GetOriginalViewportWidth(),s=this._runtime.GetOriginalViewportHeight()),this._canvasDeviceWidth<t||this._canvasDeviceHeight<s)this._drawWidth=this._canvasDeviceWidth,this._drawHeight=this._canvasDeviceHeight,this._fullscreenScalingQuality="high";else if(this._drawWidth=t,this._drawHeight=s,this._fullscreenScalingQuality="low","scale-inner"===e){const e=t/s,i=this._windowInnerWidth/this._windowInnerHeight;i<e?this._drawWidth=this._drawHeight*i:i>e&&(this._drawHeight=this._drawWidth/i)}else if("scale-outer"===e){const e=t/s,i=this._windowInnerWidth/this._windowInnerHeight;i>e?this._drawWidth=this._drawHeight*i:i<e&&(this._drawHeight=this._drawWidth/i)}}}GetRuntime(){return this._runtime}GetMainCanvas(){return this._canvasLayers[0].canvas}GetEffectChainManager(){return this._effectChainManager}IsDocumentFullscreen(){return this._isDocumentFullscreen}GetCssDisplayMode(){return this._cssDisplayMode}SetFullscreenMode(e){if(!VALID_FULLSCREEN_MODES.has(e))throw new Error("invalid fullscreen mode");this._fullscreenMode=e;const t=this._runtime.GetLayoutManager();t.SetAllLayerProjectionChanged(),t.SetAllLayerMVChanged()}GetFullscreenMode(){return this._fullscreenMode}SetDocumentFullscreenMode(e){if(!VALID_FULLSCREEN_MODES.has(e))throw new Error("invalid fullscreen mode");this._documentFullscreenMode=e;const t=this._runtime.GetLayoutManager();t.SetAllLayerProjectionChanged(),t.SetAllLayerMVChanged()}GetDocumentFullscreenMode(){return this._documentFullscreenMode}GetCurrentFullscreenMode(){return this.IsDocumentFullscreen()?this.GetDocumentFullscreenMode():this.GetFullscreenMode()}SetFullscreenScalingQuality(e){if(!VALID_FULLSCREEN_SCALING_QUALITIES.has(e))throw new Error("invalid fullscreen scaling quality");this._wantFullscreenScalingQuality=e,this._runtime.GetLayoutManager().SetAllLayerProjectionChanged()}GetSetFullscreenScalingQuality(){return this._wantFullscreenScalingQuality}GetCurrentFullscreenScalingQuality(){return this._fullscreenScalingQuality}static _FullscreenModeNumberToString(e){switch(e){case 0:return"off";case 1:return"crop";case 2:return"scale-inner";case 3:return"scale-outer";case 4:return"letterbox-scale";case 5:return"letterbox-integer-scale";default:throw new Error("invalid fullscreen mode")}}GetLastWidth(){return this._windowInnerWidth}GetLastHeight(){return this._windowInnerHeight}GetDrawWidth(){return this._drawWidth}GetDrawHeight(){return this._drawHeight}SetMipmapsEnabled(e){this._enableMipmaps=!!e}_SetTextureAnisotropy(e){this._textureAnisotropy=e}GetTextureAnisotropy(){return this._textureAnisotropy}IsRendererContextLost(){return this.GetRenderer().IsContextLost()}_OnWebGLContextLost(e){console.log("[Construct] WebGL context lost"),e.preventDefault(),this._availableAdditionalRenderTargets=[],this._usedAdditionalRenderTargets.clear(),this._effectChainManager.OnContextLost(),this._webglRenderer.OnContextLost(),this._runtime._OnRendererContextLost()}_OnWebGPUDeviceLost(){console.log("[Construct] WebGPU device lost"),this._availableAdditionalRenderTargets=[],this._usedAdditionalRenderTargets.clear(),this._effectChainManager.OnContextLost(),this._runtime._OnRendererContextLost()}async _OnWebGLContextRestored(e){await this._webglRenderer.OnContextRestored(),await this._InitRenderer(),await this._runtime._OnRendererContextRestored(),console.log("[Construct] WebGL context restored")}async _OnWebGPUDeviceRestored(){await this._InitRenderer(),await this._runtime._OnRendererContextRestored(),console.log("[Construct] WebGPU device restored")}GetWebGLRenderer(){return this._webglRenderer}GetWebGPURenderer(){return this._webgpuRenderer}GetRenderer(){return this._webgpuRenderer||this._webglRenderer}GetIRenderer(){return this._iRenderer}GetRendererString(){let e="";return e=this._runtime.GetWebGPURenderer()?"webgpu":"webgl"+this._runtime.GetWebGLRenderer().GetWebGLVersionNumber(),this._runtime.GetRenderer().HasMajorPerformanceCaveat()&&(e+="-software"),e}GetRendererDetailString(){return this._runtime.GetWebGPURenderer()?this._runtime.GetWebGPURenderer().GetAdapterInfoString():this._runtime.GetWebGLRenderer().GetUnmaskedRenderer()}GetRenderScale(){return"low"===this._fullscreenScalingQuality?1/this._runtime.GetDevicePixelRatio():this.GetDisplayScale()}GetDisplayScale(){const e=this.GetCurrentFullscreenMode();if("off"===e||"crop"===e)return 1;const t=this._runtime.GetOriginalViewportWidth(),s=this._runtime.GetOriginalViewportHeight(),i=t/s,r=this._canvasDeviceWidth/this._canvasDeviceHeight;return"scale-inner"!==e&&r>i||"scale-inner"===e&&r<i?this._canvasCssHeight/s:this._canvasCssWidth/t}GetEffectLayerScaleParam(){return"low"===this.GetCurrentFullscreenScalingQuality()?1:this.GetDisplayScale()}GetEffectDevicePixelRatioParam(){return"low"===this.GetCurrentFullscreenScalingQuality()?1:this._runtime.GetDevicePixelRatio()}SetDeviceTransformOffset(e,t){this._deviceTransformOffX=e,this._deviceTransformOffY=t}SetDeviceTransform(e,t,s,i=!0){t=t||this._drawWidth,s=s||this._drawHeight;const r=t/2+this._deviceTransformOffX,a=s/2+this._deviceTransformOffY;if(i){let i=this.GetDefaultProjectionMatrix();t===this._drawWidth&&s===this._drawHeight||(e.CalculatePerspectiveMatrix(tempProjection,t/s),i=tempProjection),e.SetProjectionMatrix(i)}const n=e.CalculateLookAtModelView2(r,a,e.GetDefaultCameraZ(s),r,a,0,s);e.SetModelViewMatrix(n)}SetCssTransform(e,t=!0){const s=this.GetCssWidth(),i=this.GetCssHeight(),r=s/2,a=i/2;t&&e.SetProjectionMatrix(this.GetDefaultProjectionMatrix());const n=e.CalculateLookAtModelView2(r,a,e.GetDefaultCameraZ(i),r,a,0,i);e.SetModelViewMatrix(n)}GetDeviceWidth(){return this._canvasDeviceWidth}GetDeviceHeight(){return this._canvasDeviceHeight}GetCssWidth(){return this._canvasCssWidth}GetCssHeight(){return this._canvasCssHeight}GetCanvasClientX(){return this._canvasCssOffsetX}GetCanvasClientY(){return this._canvasCssOffsetY}GetHTMLLayerCount(){return this._canvasLayers.length}_CanUseImageBitmapRenderingContext(){return"undefined"!=typeof OffscreenCanvas&&this.GetMainCanvas()instanceof OffscreenCanvas&&("Chromium"!==C3.Platform.BrowserEngine||C3.Platform.BrowserVersionNumber>=124)}async SetHTMLLayerCount(e,t=!1){if(e<1)throw new Error("invalid HTML layer count");if(this._canvasLayers.length===e)return;const s={"count":e,"layersDomState":this._runtime.GetLayoutManager().GetMainRunningLayout()._GetRootLayers().filter((e=>e.IsHTMLElementsLayer())).map((e=>e._GetHTMLLayerDOMState())),"immediate":t,"marginLeft":this._canvasCssOffsetX,"marginTop":this._canvasCssOffsetY,"styleWidth":this._canvasCssWidth,"styleHeight":this._canvasCssHeight};let i;if(i=this.IsInWorker()?await this._runtime.PostComponentMessageToDOMAsync("canvas","set-html-layer-count",s):self["c3_runtimeInterface"]["_OnSetHTMLLayerCount"](s),e<this._canvasLayers.length)this._canvasLayers.length=e;else for(const e of i["addedCanvases"]){e.width=this._canvasDeviceWidth,e.height=this._canvasDeviceHeight;const t=this._CanUseImageBitmapRenderingContext()?"bitmaprenderer":"2d",s=e.getContext(t);if(!s)throw new Error(`failed to acquire '${t}' canvas context`);this._canvasLayers.push({canvas:e,ctx:s})}this._runtime.UpdateRender()}BlitMainCanvasToHTMLLayerCanvas(e){if(e>=this._canvasLayers.length)return;const t=this.GetMainCanvas(),s=this._canvasLayers[e].ctx;this._CanUseImageBitmapRenderingContext()?s["transferFromImageBitmap"](t["transferToImageBitmap"]()):(s.globalCompositeOperation="copy",s.drawImage(t,0,0))}GetAdditionalRenderTarget(e){e.depth=this._runtime.Uses3DFeatures();const t=this._availableAdditionalRenderTargets,s=t.findIndex((t=>t.IsCompatibleWithOptions(e)));let i;return-1!==s?(i=t[s],t.splice(s,1)):i=this.GetRenderer().CreateRenderTarget(e),this._usedAdditionalRenderTargets.add(i),i}ReleaseAdditionalRenderTarget(e){if(!this._usedAdditionalRenderTargets.has(e))throw new Error("render target not in use");this._usedAdditionalRenderTargets.delete(e),this._availableAdditionalRenderTargets.push(e)}GetEffectCompositorRenderTarget(){const e={sampling:this._runtime.GetSampling()};return"low"===this.GetCurrentFullscreenScalingQuality()&&(e.width=this.GetDrawWidth(),e.height=this.GetDrawHeight()),this.GetAdditionalRenderTarget(e)}ReleaseEffectCompositorRenderTarget(e){this.ReleaseAdditionalRenderTarget(e)}*activeLayersGpuProfiles(){for(const e of this._runtime.GetLayoutManager().runningLayouts())for(const t of e.GetLayers()){const e=this._layersGpuProfile.get(t);e&&(yield e)}}GetLayerTimingsBuffer(e){if(!this.GetRenderer().SupportsGPUProfiling())return null;let t=this._layersGpuProfile.get(e);return t||(t={layer:e,name:e.GetName(),timingsBuffer:C3.New(C3.Gfx.WebGLQueryResultBuffer,this._webglRenderer),curUtilisation:0,lastTotalUtilisation:0,lastSelfUtilisation:0},this._layersGpuProfile.set(e,t)),t.timingsBuffer}_Update1sFrameRange(){const e=this.GetRenderer();if(e.SupportsGPUProfiling()&&0===this._gpuTimeEndFrame){this._gpuTimeEndFrame=e.GetFrameNumber(),this._gpuCurUtilisation=NaN;for(const e of this.activeLayersGpuProfiles())e.curUtilisation=NaN}}_UpdateTick(){this._webglRenderer&&this._webglRenderer.SupportsGPUProfiling()&&this._UpdateTick_WebGL(),this._webgpuRenderer&&this._webgpuRenderer.SupportsGPUProfiling()&&this._UpdateTick_WebGPU()}_UpdateTick_WebGL(){if(isNaN(this._gpuCurUtilisation)&&(this._gpuCurUtilisation=this._gpuFrameTimingsBuffer.GetFrameRangeResultSum(this._gpuTimeStartFrame,this._gpuTimeEndFrame),!isNaN(this._gpuCurUtilisation))){if(this._runtime.IsDebug())for(const e of this.activeLayersGpuProfiles())if(e.curUtilisation=e.timingsBuffer.GetFrameRangeResultSum(this._gpuTimeStartFrame,this._gpuTimeEndFrame),isNaN(e.curUtilisation))return;if(this._gpuFrameTimingsBuffer.DeleteAllBeforeFrameNumber(this._gpuTimeEndFrame),this._gpuLastUtilisation=Math.min(this._gpuCurUtilisation,1),this._runtime.IsDebug()){const e=new Map;for(const t of this.activeLayersGpuProfiles())t.timingsBuffer.DeleteAllBeforeFrameNumber(this._gpuTimeEndFrame),t.lastTotalUtilisation=Math.min(t.curUtilisation,1),e.set(t.layer,t.lastTotalUtilisation);for(const t of this.activeLayersGpuProfiles()){const s=t.layer,i=(e.get(s)||0)-s.GetSubLayers().reduce(((t,s)=>t+(e.get(s)||0)),0);t.lastSelfUtilisation=C3.clamp(i,0,1)}const t=this._runtime.GetMainRunningLayout(),s=this._gpuLastUtilisation-t._GetRootLayers().reduce(((t,s)=>t+(e.get(s)||0)),0);self.C3Debugger.UpdateGPUProfile(C3.clamp(s,0,1),this._gpuLastUtilisation,[...this.activeLayersGpuProfiles()])}this._gpuTimeStartFrame=this._gpuTimeEndFrame,this._gpuTimeEndFrame=0}}GetGPUFrameTimingsBuffer(){return this._gpuFrameTimingsBuffer}_UpdateTick_WebGPU(){if(0===this._gpuTimeEndFrame)return;for(let e=this._gpuTimeStartFrame;e<this._gpuTimeEndFrame;++e){const t=this._webgpuFrameTimings.get(e);if(t&&!t.HasResult())return}const e=this._runtime.GetMainRunningLayout(),t=C3.MakeFilledArray(e.GetLayerCount()+1,0);let s=0;for(let e=this._gpuTimeStartFrame;e<this._gpuTimeEndFrame;++e){const i=this._webgpuFrameTimings.get(e);if(!i)continue;const r=i.GetResult();let a=BigInt(0),n=BigInt(0);const h=BigInt(0);for(let e=0,s=Math.min(t.length,r.length/2);e<s;++e){const s=r[2*e],i=r[2*e+1];s!==h&&(a===h||s<a)&&(a=s),i>n&&(n=i);const o=Number(i-s)/1e9;t[e]+=o}s+=Number(n-a)/1e9}if(this._gpuLastUtilisation=C3.clamp(s,0,1),this._runtime.IsDebug()){const s=e.GetLayers(),i=new Map;for(let e=0,r=Math.min(s.length,t.length-1);e<r;++e){const r=t[e+1];i.set(s[e],r)}const r=[],a=new Map;for(const[e,t]of i){const s=[...e.selfAndAllSubLayers()].reduce(((e,t)=>e+(i.get(t)||0)),0);a.set(e,s),r.push({name:e.GetName(),lastSelfUtilisation:C3.clamp(t,0,1),lastTotalUtilisation:C3.clamp(s,0,1)})}const n=this._gpuLastUtilisation-e._GetRootLayers().reduce(((e,t)=>e+(a.get(t)||0)),0);self.C3Debugger.UpdateGPUProfile(C3.clamp(n,0,1),this._gpuLastUtilisation,r)}for(let e=this._gpuTimeStartFrame;e<this._gpuTimeEndFrame;++e)this._webgpuFrameTimings.delete(e);this._gpuTimeStartFrame=this._gpuTimeEndFrame,this._gpuTimeEndFrame=0}_AddWebGPUFrameTiming(e){this._webgpuFrameTimings.set(this._webgpuRenderer.GetFrameNumber(),e)}GetGPUUtilisation(){return this._gpuLastUtilisation}SnapshotCanvas(e,t,s,i,r,a){return this._snapshotFormat=e,this._snapshotQuality=t,this._snapshotArea.setWH(s,i,r,a),this._snapshotPromise||(this._snapshotPromise=new Promise((e=>{this._snapshotResolve=e}))),this._snapshotPromise}_MaybeTakeSnapshot(){if(!this._snapshotFormat)return;let e=this.GetMainCanvas();const t=this._snapshotArea,s=C3.clamp(Math.floor(t.getLeft()),0,e.width),i=C3.clamp(Math.floor(t.getTop()),0,e.height);let r=t.width();r=0===r?e.width-s:C3.clamp(Math.floor(r),0,e.width-s);let a=t.height();if(a=0===a?e.height-i:C3.clamp(Math.floor(a),0,e.height-i),(0!==s||0!==i||r!==e.width||a!==e.height)&&r>0&&a>0){const t=C3.CreateCanvas(r,a);t.getContext("2d").drawImage(e,s,i,r,a,0,0,r,a),e=t}C3.CanvasToBlob(e,this._snapshotFormat,this._snapshotQuality).then((e=>{this._snapshotUrl&&URL.revokeObjectURL(this._snapshotUrl),this._snapshotUrl=URL.createObjectURL(e),this._snapshotPromise=null,this._snapshotResolve(e)})),this._snapshotFormat="",this._snapshotQuality=1}GetCanvasSnapshotUrl(){return this._snapshotUrl}SetIsPastingToDrawingCanvas(e){e?this._isPastingToDrawingCanvas++:this._isPastingToDrawingCanvas--}IsPastingToDrawingCanvas(){return this._isPastingToDrawingCanvas>0}InitLoadingScreen(e){const t=this.GetRenderer();if(2===e)this._percentText=C3.New(C3.Gfx.RendererText,this.GetRenderer()),this._percentText.SetFontName("Arial"),this._percentText.SetFontSize(16),this._percentText.SetHorizontalAlignment("center"),this._percentText.SetVerticalAlignment("center"),this._percentText.SetSize(300,200);else if(0===e){const e=this._runtime.GetLoadingLogoAsset();e&&e.LoadStaticTexture(t).catch((e=>console.warn("[C3 runtime] Failed to create texture for loading logo: ",e)))}else 4===e&&(this._LoadSvgSplashImage("splash-images/splash-logo.svg").then((e=>{"done"===this._splashState?t.DeleteTexture(e):this._splashTextures.logo=e})).catch((e=>console.warn("Failed to load splash image: ",e))),this._LoadBitmapSplashImage("splash-images/splash-poweredby-512.png").then((e=>{"done"===this._splashState?t.DeleteTexture(e):this._splashTextures.powered=e})).catch((e=>console.warn("Failed to load splash image: ",e))),this._LoadBitmapSplashImage("splash-images/splash-website-512.png").then((e=>{"done"===this._splashState?t.DeleteTexture(e):this._splashTextures.website=e})).catch((e=>console.warn("Failed to load splash image: ",e))))}async _LoadSvgSplashImage(e){e=new URL(e,this._runtime.GetRuntimeBaseURL()).toString();const t=await C3.FetchBlob(e),s=await this._runtime.RasterSvgImage(t,2048,2048);return await this.GetRenderer().CreateStaticTextureAsync(s,{mipMapQuality:"high"})}async _LoadBitmapSplashImage(e){e=new URL(e,this._runtime.GetRuntimeBaseURL()).toString();const t=await C3.FetchBlob(e);return await this.GetRenderer().CreateStaticTextureAsync(t,{mipMapQuality:"high"})}HideCordovaSplashScreen(){this._runtime.PostComponentMessageToDOM("runtime","hide-cordova-splash")}StartLoadingScreen(){this._loaderStartTime=Date.now(),this._runtime.Dispatcher().addEventListener("loadingprogress",this._loadingprogress_handler),this._rafId=requestAnimationFrame((()=>this._DrawLoadingScreen()));3!==this._runtime.GetLoaderStyle()&&this.HideCordovaSplashScreen()}async EndLoadingScreen(){const e=this.GetRenderer();this._loadingProgress=1;const t=this._runtime.GetLoaderStyle();4===t&&await this._splashDonePromise,this._splashDoneResolve=null,this._splashDonePromise=null,-1!==this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=-1),this._runtime.Dispatcher().removeEventListener("loadingprogress",this._loadingprogress_handler),this._loadingprogress_handler=null,this._percentText&&(this._percentText.Release(),this._percentText=null),this._runtime.ReleaseLoadingLogoAsset(),e.Start(),this._splashTextures.logo&&(e.DeleteTexture(this._splashTextures.logo),this._splashTextures.logo=null),this._splashTextures.powered&&(e.DeleteTexture(this._splashTextures.powered),this._splashTextures.powered=null),this._splashTextures.website&&(e.DeleteTexture(this._splashTextures.website),this._splashTextures.website=null),e.ClearRgba(0,0,0,0),e.Finish(),this._splashState="done",this._gpuTimeStartFrame=e.GetFrameNumber(),3===t&&this.HideCordovaSplashScreen()}_DrawLoadingScreen(){if(-1===this._rafId)return;const e=this.GetRenderer();e.Start(),this._rafId=-1;const t=this._runtime.GetAssetManager().HasHadErrorLoading(),s=this._runtime.GetLoaderStyle();if(3!==s&&(this.SetCssTransform(e),e.ClearRgba(0,0,0,0),e.ResetColor(),e.SetTextureFillMode(),e.SetTexture(null)),0===s)this._DrawProgressBarAndLogoLoadingScreen(t);else if(1===s)this._DrawProgressBarLoadingScreen(t,120,0);else if(2===s)this._DrawPercentTextLoadingScreen(t);else if(3===s)C3.noop();else{if(4!==s)throw new Error("invalid loader style");this._DrawSplashLoadingScreen(t)}e.Finish(),this._rafId=requestAnimationFrame((()=>this._DrawLoadingScreen()))}_DrawPercentTextLoadingScreen(e){e?this._percentText.SetColorRgb(1,0,0):this._percentText.SetColorRgb(.6,.6,.6),this._percentText.SetText(Math.round(100*this._loadingProgress)+"%");const t=this._canvasCssWidth/2,s=this._canvasCssHeight/2;tempQuad.setRect(t-150,s-100,t+150,s+100);const i=this.GetRenderer();i.SetTexture(this._percentText.GetTexture()),i.Quad3(tempQuad,this._percentText.GetTexRect())}_DrawProgressBarLoadingScreen(e,t,s){const i=this.GetRenderer();i.SetColorFillMode(),e?i.SetColorRgba(1,0,0,1):i.SetColorRgba(.118,.565,1,1);const r=this._canvasCssWidth/2,a=this._canvasCssHeight/2,n=t/2;tempRect.setWH(r-n,a-4+s,Math.floor(t*this._loadingProgress),8),i.Rect(tempRect),tempRect.setWH(r-n,a-4+s,t,8),tempRect.offset(-.5,-.5),tempRect.inflate(.5,.5),i.SetColorRgba(0,0,0,1),i.LineRect2(tempRect),tempRect.inflate(1,1),i.SetColorRgba(1,1,1,1),i.LineRect2(tempRect)}_DrawProgressBarAndLogoLoadingScreen(e){const t=this.GetRenderer(),s=this._runtime.GetLoadingLogoAsset();if(!s)return void this._DrawProgressBarLoadingScreen(e,120,0);const i=s.GetTexture();if(!i)return void this._DrawProgressBarLoadingScreen(e,120,0);const r=i.GetWidth(),a=i.GetHeight(),n=this._canvasCssWidth/2,h=this._canvasCssHeight/2,o=r/2,l=a/2;tempQuad.setRect(n-o,h-l,n+o,h+l),t.SetTexture(i),t.Quad(tempQuad),this._DrawProgressBarLoadingScreen(e,r,l+16)}_DrawSplashLoadingScreen(e){const t=this.GetRenderer(),s=this._splashTextures.logo,i=this._splashTextures.powered,r=this._splashTextures.website,a=Date.now();0===this._splashFrameNumber&&(this._loaderStartTime=a);const n=this._runtime.IsPreview()||this._runtime.IsFBInstantAvailable()&&!this._runtime.IsCordova(),h=n?0:200,o=n?0:3e3;let l=1;"fade-in"===this._splashState?l=Math.min((a-this._loaderStartTime)/300,1):"fade-out"===this._splashState&&(l=Math.max(1-(a-this._splashFadeOutStartTime)/300,0)),t.SetColorFillMode(),t.SetColorRgba(.231*l,.251*l,.271*l,l),tempRect.set(0,0,this._canvasCssWidth,this._canvasCssHeight),t.Rect(tempRect);const c=Math.ceil(this._canvasCssWidth),_=Math.ceil(this._canvasCssHeight);let d,u;this._canvasCssHeight>256?(t.SetColorRgba(.302*l,.334*l,.365*l,l),d=c,u=Math.max(.005*_,2),tempRect.setWH(0,.8*_-u/2,d,u),t.Rect(tempRect),e?t.SetColorRgba(l,0,0,l):t.SetColorRgba(.161*l,.953*l,.816*l,l),d=c*this._loadingProgress,tempRect.setWH(.5*c-d/2,.8*_-u/2,d,u),t.Rect(tempRect),t.SetColorRgba(l,l,l,l),t.SetTextureFillMode(),i&&(d=1.5*C3.clamp(.22*_,105,.6*c),u=d/8,tempRect.setWH(.5*c-d/2,.2*_-u/2,d,u),t.SetTexture(i),t.Rect(tempRect)),s&&(d=Math.min(.395*_,.95*c),u=d,tempRect.setWH(.5*c-d/2,.485*_-u/2,d,u),t.SetTexture(s),t.Rect(tempRect)),r&&(d=1.5*C3.clamp(.22*_,105,.6*c),u=d/8,tempRect.setWH(.5*c-d/2,.868*_-u/2,d,u),t.SetTexture(r),t.Rect(tempRect))):(t.SetColorRgba(.302*l,.334*l,.365*l,l),d=c,u=Math.max(.005*_,2),tempRect.setWH(0,.85*_-u/2,d,u),t.Rect(tempRect),e?t.SetColorRgba(l,0,0,l):t.SetColorRgba(.161*l,.953*l,.816*l,l),d=c*this._loadingProgress,tempRect.setWH(.5*c-d/2,.85*_-u/2,d,u),t.Rect(tempRect),t.SetColorRgba(l,l,l,l),t.SetTextureFillMode(),s&&(d=.55*_,u=d,tempRect.setWH(.5*c-d/2,.45*_-u/2,d,u),t.SetTexture(s),t.Rect(tempRect))),this._splashFrameNumber++,"fade-in"===this._splashState&&a-this._loaderStartTime>=300&&this._splashFrameNumber>=2&&(this._splashState="wait",this._splashFadeInFinishTime=a),"wait"===this._splashState&&a-this._splashFadeInFinishTime>=o&&this._loadingProgress>=1&&(this._splashState="fade-out",this._splashFadeOutStartTime=a),("fade-out"===this._splashState&&a-this._splashFadeOutStartTime>=300+h||n&&this._loadingProgress>=1&&a-this._loaderStartTime<500)&&this._splashDoneResolve()}};
}

// runtime.js
{
const C3=self.C3,C3Debugger=self.C3Debugger,assert=self.assert,ISDKBehaviorInstanceBase=self.ISDKBehaviorInstanceBase,DEFAULT_RUNTIME_OPTS={"messagePort":null,"runtimeBaseUrl":"","headless":!1,"hasDom":!0,"isInWorker":!1,"useAudio":!0,"exportType":""};let ife=!0;C3.Runtime=class extends C3.DefendedBase{constructor(e){e=Object.assign({},DEFAULT_RUNTIME_OPTS,e),super(),this._messagePort=e["messagePort"],this._runtimeBaseUrl=e["runtimeBaseUrl"],this._previewUrl=e["previewUrl"],this._isHeadless=!!e["headless"],this._hasDom=!!e["hasDom"],this._isInWorker=!!e["isInWorker"],ife=e["ife"],this._useAudio=!!e["useAudio"],this._exportType=e["exportType"],this._isNWjs=e["isNWjs"],this._isiOSCordova=!!e["isiOSCordova"],this._isiOSWebView=!!e["isiOSWebView"],this._isWindowsWebView2=!!e["isWindowsWebView2"],this._isAnyWebView2Wrapper=!!e["isAnyWebView2Wrapper"],this._isFBInstantAvailable=!!e["isFBInstantAvailable"],this._isDebug=!("preview"!==this._exportType||!e["isDebug"]),this._breakpointsEnabled=this._isDebug,this._isDebugging=this._isDebug,this._debuggingDisabled=0,this._additionalLoadPromises=[],this._additionalCreatePromises=[],this._isUsingCreatePromises=!1,this._projectName="",this._projectVersion="",this._projectUniqueId="",this._appId="",this._exportTimestamp=0,this._originalViewportWidth=0,this._originalViewportHeight=0,this._devicePixelRatio=self.devicePixelRatio,this._parallaxXorigin=0,this._parallaxYorigin=0,this._viewportWidth=0,this._viewportHeight=0,this._loaderStyle=0,this._usesLoaderLayout=!1,this._isLoading=!0,this._usesAnyBackgroundBlending=!1,this._usesAnyCrossSampling=!1,this._usesAnyDepthSampling=!1,this._loadingLogoAsset=null,this._assetManager=C3.New(C3.AssetManager,this,e),this._layoutManager=C3.New(C3.LayoutManager,this),this._eventSheetManager=C3.New(C3.EventSheetManager,this),this._addonManager=C3.New(C3.AddonManager,this,e["wrapperComponentIds"]),this._collisionEngine=C3.New(C3.CollisionEngine,this),this._timelineManager=C3.New(C3.TimelineManager,this),this._transitionManager=C3.New(C3.TransitionManager,this),this._templateManager=C3.New(C3.TemplateManager,this),this._flowchartManager=C3.New(C3.FlowchartManager,this),this._textIconManager=C3.New(C3.TextIconManager,{getIconSetMeta:e=>this._GetTextIconSetMeta(e),getIconSetContent:e=>this._GetTextIconSetContent(e)}),this._iconChangeHandlers=new Map,this._allObjectClasses=[],this._objectClassesByName=new Map,this._objectClassesBySid=new Map,this._familyCount=0,this._allContainers=[],this._allEffectLists=new Set,this._currentLayoutStack=[],this._instancesPendingCreate=[],this._instancesPendingDestroy=new Map,this._hasPendingInstances=!1,this._isFlushingPendingInstances=!1,this._objectCount=0,this._nextUid=0,this._instancesByUid=new Map,this._instancesPendingRelease=new Set,this._instancesPendingReleaseAffectedObjectClasses=new Set,this._objectReferenceTable=[],this._jsPropNameTable=[],this._canvasManager=null,this._uses3dFeatures=!1,this._framerateMode="vsync",this._sampling="trilinear",this._isPixelRoundingEnabled=!1,this._needRender=!0,this._pauseOnBlur=!1,this._isPausedOnBlur=!1,this._exportToVideo=null,this._tickCallbacks={normal:e=>{this._rafId=-1,this._ruafId=-1,this.Tick(e)},tickOnly:e=>{this._ruafId=-1,this.Tick(e,!1,"skip-render")},renderOnly:()=>{this._rafId=-1,this.Render()}},this._rafId=-1,this._ruafId=-1,this._tickCount=0,this._tickCountNoSave=0,this._hasStarted=!1,this._isInTick=!1,this._hasStartedTicking=!1,this._isLayoutFirstTick=!0,this._isAutoSuspendEnabled=!0,this._isPageVisibilitySuspended=!1,this._suspendCount=0,this._scheduleTriggersThrottle=new C3.PromiseThrottle(1),this._randomNumberCallback=()=>Math.random(),this._startTime=0,this._lastTickTime=0,this._dtRaw=0,this._dt1=0,this._dt=0,this._timeScale=1,this._maxDt=1/30,this._minDt=0,this._gameTime=C3.New(C3.KahanSum),this._gameTimeRaw=C3.New(C3.KahanSum),this._wallTime=C3.New(C3.KahanSum),this._instanceTimes=new Map,this._fpsFrameCount=-1,this._fpsLastTime=0,this._fps=0,this._tpsTickCount=-1,this._tps=0,this._mainThreadTimeCounter=0,this._mainThreadTime=0,this._isLoadingState=!1,this._saveToSlotName="",this._saveToJsonString=!1,this._loadFromSlotName="",this._loadFromJson=null,this._lastSaveJson="",this._projectStorage=null,this._savegamesStorage=null,this._dispatcher=C3.New(C3.Event.Dispatcher),this._domEventHandlers=new Map,this._pendingResponsePromises=new Map,this._nextDomResponseId=0,this._didRequestDeviceOrientationEvent=!1,this._didRequestDeviceMotionEvent=!1,this._isReadyToHandleEvents=!1,this._waitingToHandleEvents=[],this._eventObjects={"pretick":C3.New(C3.Event,"pretick",!1),"tick":C3.New(C3.Event,"tick",!1),"tick2":C3.New(C3.Event,"tick2",!1),"instancecreate":C3.New(C3.Event,"instancecreate",!1),"instancedestroy":C3.New(C3.Event,"instancedestroy",!1),"beforelayoutchange":C3.New(C3.Event,"beforelayoutchange",!1),"layoutchange":C3.New(C3.Event,"layoutchange",!1)},this._eventObjects["instancecreate"].instance=null,this._eventObjects["instancedestroy"].instance=null,this._userScriptDispatcher=C3.New(C3.Event.Dispatcher),this._userScriptEventObjects=null;const t=(e,t)=>C3.BehaviorInstance.SortByTickSequence(this,e,t);this._behInstsToTick=C3.New(C3.RedBlackSet,t),this._behInstsToPostTick=C3.New(C3.RedBlackSet,t),this._behInstsToTick2=C3.New(C3.RedBlackSet,t),this._jobScheduler=C3.New(C3.JobSchedulerRuntime,this,e["jobScheduler"]),e["canvas"]&&(this._canvasManager=C3.New(C3.CanvasManager,this)),this._messagePort.onmessage=e=>this["_OnMessageFromDOM"](e.data),this.AddDOMComponentMessageHandler("runtime","visibilitychange",(e=>this._OnVisibilityChange(e))),this.AddDOMComponentMessageHandler("runtime","wrapper-extension-message",(e=>this._OnWrapperExtensionMessage(e))),this.AddDOMComponentMessageHandler("runtime","get-remote-preview-status-info",(()=>this._GetRemotePreviewStatusInfo())),this.AddDOMComponentMessageHandler("runtime","js-invoke-function",(e=>this._InvokeFunctionFromJS(e))),this.AddDOMComponentMessageHandler("runtime","go-to-last-error-script",self["goToLastErrorScript"]),this.AddDOMComponentMessageHandler("runtime","offline-audio-render-completed",(e=>this._OnOfflineAudioRenderCompleted(e))),this._dispatcher.addEventListener("window-blur",(e=>this._OnWindowBlur(e))),this._dispatcher.addEventListener("window-focus",(()=>this._OnWindowFocus())),this._timelineManager.AddRuntimeListeners(),this._templateManager.AddRuntimeListeners(),this._iRuntime=null,this._interfaceMap=new WeakMap,this._commonScriptInterfaces={keyboard:null,mouse:null,touch:null,timelineController:null},this._instancesNeedingAfterLoadMap=new WeakMap,this._instancesNeedingAfterLoadArray=[]}static Create(e){return C3.New(C3.Runtime,e)}Release(){C3.clearArray(this._allObjectClasses),this._objectClassesByName.clear(),this._objectClassesBySid.clear(),this._layoutManager.Release(),this._layoutManager=null,this._eventSheetManager.Release(),this._eventSheetManager=null,this._addonManager.Release(),this._addonManager=null,this._assetManager.Release(),this._assetManager=null,this._collisionEngine.Release(),this._collisionEngine=null,this._timelineManager.Release(),this._timelineManager=null,this._transitionManager.Release(),this._transitionManager=null,this._templateManager.Release(),this._templateManager=null,this._flowchartManager.Release(),this._flowchartManager=null,this._textIconManager.Release(),this._textIconManager=null,this._canvasManager&&(this._canvasManager.Release(),this._canvasManager=null),this._dispatcher.Release(),this._dispatcher=null,this._tickEvent=null}"_OnMessageFromDOM"(e){const t=e["type"];if("event"===t)this._OnEventFromDOM(e);else{if("result"!==t)throw new Error(`unknown message '${t}'`);this._OnResultFromDOM(e)}}_OnEventFromDOM(e){if(!this._isReadyToHandleEvents)return void this._waitingToHandleEvents.push(e);const t=e["component"],s=e["handler"],i=e["data"],n=e["dispatchOpts"],a=!(!n||!n["dispatchRuntimeEvent"]),r=!(!n||!n["dispatchUserScriptEvent"]),o=e["responseId"];if("runtime"===t){if(a){const e=new C3.Event(s);e.data=i,this._dispatcher.dispatchEventAndWaitAsyncSequential(e)}if(r){const e=new C3.Event(s,!0);for(const[t,s]of Object.entries(i))e[t]=s;this.DispatchUserScriptEvent(e)}}const h=this._domEventHandlers.get(t);if(!h)return void(a||r||console.warn(`[Runtime] No DOM event handlers for component '${t}'`));const l=h.get(s);if(!l)return void(a||r||console.warn(`[Runtime] No DOM handler '${s}' for component '${t}'`));let c=null;try{c=l(i)}catch(e){return console.error(`Exception in '${t}' handler '${s}':`,e),void(null!==o&&this._PostResultToDOM(o,!1,""+e))}null!==o&&(c&&c.then?c.then((e=>this._PostResultToDOM(o,!0,e))).catch((e=>{console.error(`Rejection from '${t}' handler '${s}':`,e),this._PostResultToDOM(o,!1,""+e)})):this._PostResultToDOM(o,!0,c))}_PostResultToDOM(e,t,s){this._messagePort.postMessage({"type":"result","responseId":e,"isOk":t,"result":s})}_OnResultFromDOM(e){const t=e["responseId"],s=e["isOk"],i=e["result"],n=this._pendingResponsePromises.get(t);s?n.resolve(i):n.reject(i),this._pendingResponsePromises.delete(t)}AddDOMComponentMessageHandler(e,t,s){let i=this._domEventHandlers.get(e);if(i||(i=new Map,this._domEventHandlers.set(e,i)),i.has(t))throw new Error(`[Runtime] Component '${e}' already has handler '${t}'`);i.set(t,s)}PostComponentMessageToDOM(e,t,s,i){this._messagePort.postMessage({"type":"event","component":e,"handler":t,"data":s,"responseId":null},i)}PostComponentMessageToDOMAsync(e,t,s,i){const n=this._nextDomResponseId++,a=new Promise(((e,t)=>{this._pendingResponsePromises.set(n,{resolve:e,reject:t})}));return this._messagePort.postMessage({"type":"event","component":e,"handler":t,"data":s,"responseId":n},i),a}SendWrapperExtensionMessage(e,t,s,i=-1){this.PostComponentMessageToDOM("runtime","send-wrapper-extension-message",{"componentId":e,"messageId":t,"params":s,"asyncId":i})}SendWrapperExtensionMessageAsync(e,t,s){const i=this._nextDomResponseId++,n=new Promise(((e,t)=>{this._pendingResponsePromises.set(i,{resolve:e,reject:t})}));return this.SendWrapperExtensionMessage(e,t,s,i),n}_OnWrapperExtensionMessage(e){if(-1!==e["asyncId"]){const t=e["asyncId"];this._pendingResponsePromises.get(t).resolve(e["params"]),this._pendingResponsePromises.delete(t)}else this._OnEventFromDOM({"component":"wrapper-extension:"+e["componentId"],"handler":e["messageId"],"data":e["params"],"responseId":null})}AddWrapperExtensionMessageHandler(e,t,s){this.AddDOMComponentMessageHandler("wrapper-extension:"+e,t,s)}HasWrapperComponentId(e){return this._addonManager.HasWrapperComponentId(e)}PostToDebugger(e){if(!this.IsDebug())throw new Error("not in debug mode");this.PostComponentMessageToDOM("runtime","post-to-debugger",e)}async Init(e){C3.CommonACES_SetRuntime(this),this.IsDebug()?await C3Debugger.Init(this):self.C3Debugger&&self.C3Debugger.InitPreview(this);const t=await this._assetManager.FetchJson("data.json");if(await this._LoadDataJson(t),await this._InitialiseCanvas(e),this.IsPreview()||console.info("%cMade with Construct, the game and animation creation tool. Visit: https://www.construct.net","font-weight: bold"),this.GetWebGLRenderer()){const e=this.GetWebGLRenderer();console.info(`[C3 runtime] Hosted in ${this.IsInWorker()?"worker":"DOM"}, rendering with WebGL ${e.GetWebGLVersionNumber()} [${e.GetUnmaskedRenderer()}]`)}else this.GetWebGPURenderer()&&console.info(`[C3 runtime] Hosted in ${this.IsInWorker()?"worker":"DOM"}, rendering with WebGPU [${this.GetWebGPURenderer().GetAdapterInfoString()}]`);this.GetRenderer().HasMajorPerformanceCaveat()&&console.warn("[C3 runtime] The renderer indicates a major performance caveat. Software rendering may be in use. This can result in significantly degraded performance."),this._isReadyToHandleEvents=!0;for(const e of this._waitingToHandleEvents)this._OnEventFromDOM(e);C3.clearArray(this._waitingToHandleEvents),this._canvasManager&&this._canvasManager.StartLoadingScreen();for(const t of e["runOnStartupFunctions"])this._additionalLoadPromises.push(this._RunOnStartupFunction(t));if(await Promise.all([this._assetManager.WaitForAllToLoad(),...this._additionalLoadPromises]),C3.clearArray(this._additionalLoadPromises),!this._assetManager.HasHadErrorLoading())return this._canvasManager&&await this._canvasManager.EndLoadingScreen(),await this._dispatcher.dispatchEventAndWaitAsync(new C3.Event("beforeruntimestart")),await this.Start(),this._messagePort.postMessage({"type":"runtime-ready"}),this;this._canvasManager&&this._canvasManager.HideCordovaSplashScreen()}async _RunOnStartupFunction(e){try{await e(this._iRuntime)}catch(e){console.error("[C3 runtime] Error in runOnStartup function: ",e)}}async _LoadDataJson(e){const t=e["project"];this._projectName=t[0],this._projectVersion=t[16],this._projectUniqueId=t[31],this._appId=t[38],this._exportTimestamp=t[36];const s=t[39]||"loading-logo.png";this._isPixelRoundingEnabled=!!t[9],this._originalViewportWidth=this._viewportWidth=t[10],this._originalViewportHeight=this._viewportHeight=t[11],this._collisionEngine._InitCollisionCellSize(this._originalViewportWidth,this._originalViewportHeight),this._parallaxXorigin=this._originalViewportWidth/2,this._parallaxYorigin=this._originalViewportHeight/2,this._framerateMode=t[37],this._uses3dFeatures=!!t[40],this._sampling=t[14],this._usesAnyBackgroundBlending=t[15],this._usesAnyCrossSampling=t[42],this._usesAnyDepthSampling=t[17],this._usesLoaderLayout=!!t[18],this._loaderStyle=t[19],this._nextUid=t[21],this._pauseOnBlur=t[22];const i=this._assetManager;if(i._SetFileStructure(t[45]),i._SetAudioFiles(t[7],t[25]),i._SetMediaSubfolder(t[8]),i._SetFontsSubfolder(t[32]),i._SetIconsSubfolder(t[28]),i._SetWebFonts(t[29]),0===this._loaderStyle){let e="";e="flat"===i.GetFileStructure()?i.GetIconsSubfolder()+s:s,e&&(this._loadingLogoAsset=i.LoadImage({url:e}))}this._canvasManager&&(this._canvasManager.SetFullscreenMode(C3.CanvasManager._FullscreenModeNumberToString(t[12])),this._canvasManager.SetFullscreenScalingQuality(t[23]?"high":"low"),this._canvasManager.SetMipmapsEnabled(0!==t[24]),this._canvasManager._SetGPUPowerPreference(t[34]),this._canvasManager._SetTextureAnisotropy(t[41]),this._canvasManager._SetWebGPUEnabled(t[13]),this._canvasManager._SetZAxisScale(t[30]),this._canvasManager._SetZDistances(t[46],t[47]),this._canvasManager._SetInitFieldOfView(t[26]),this._canvasManager._SetLimitedToWebGL1(t[48]),this._canvasManager._SetMultitexturingMode(t[50]));const n=t[43];n&&await this._LoadExportToVideoData(n),this._InitScriptInterfaces(),this._addonManager.CreateSystemPlugin(),this._objectReferenceTable=self.C3_GetObjectRefTable();const a=t[2];for(const e of a[1])this._addonManager.CreateBehavior(e);for(const e of a[0])this._addonManager.CreatePlugin(e);this._objectReferenceTable=self.C3_GetObjectRefTable(),this._LoadJsPropNameTable(),this._addonManager._InitAddonScriptInterfaces();for(const e of t[3]){const t=C3.ObjectClass.Create(this,this._allObjectClasses.length,e);this._allObjectClasses.push(t),this._objectClassesByName.set(t.GetName().toLowerCase(),t),this._objectClassesBySid.set(t.GetSID(),t)}for(const e of t[4]){this._allObjectClasses[e[0]]._LoadFamily(e)}for(const e of t[27]){const t=e.map((e=>this._allObjectClasses[e]));this._allContainers.push(C3.New(C3.Container,this,t))}this._InitObjectsScriptInterface();for(const e of this._allObjectClasses)e._OnAfterCreate();for(const e of t[5])this._layoutManager.Create(e);const r=t[1];if(r){const e=this._layoutManager.GetLayoutByName(r);e&&this._layoutManager.SetFirstLayout(e)}for(const e of t[35])this._transitionManager.Create(e);for(const e of t[33])this._timelineManager.Create(e);for(const e of t[44])this._templateManager.Create(e);this._templateManager.HasTemplates()||(this._templateManager.Release(),this._templateManager=null);for(const e of t[49])this._flowchartManager.Create(e);this._flowchartManager.HasFlowcharts()||(this._flowchartManager.Release(),this._flowchartManager=null);for(const e of t[6])this._eventSheetManager.Create(e);this._eventSheetManager._PostInit(),this._InitGlobalVariableScriptInterface(),C3.clearArray(this._objectReferenceTable),this.FlushPendingInstances();let o="any";const h=t[20];1===h?o="portrait":2===h&&(o="landscape"),this.PostComponentMessageToDOM("runtime","set-target-orientation",{"targetOrientation":o})}async _LoadExportToVideoData(e){const t=e["format"];"image-sequence"===t?this._exportToVideo=new self.C3ExportToImageSequence(this,e):"image-sequence-gif"===t?this._exportToVideo=new self.C3ExportToGIF(this,e):"webm"===t?this._exportToVideo=new self.C3ExportToWebMVideo(this,e):"mp4"===t&&(this._exportToVideo=new self.C3ExportToMP4Video(this,e)),this._framerateMode="unlimited-frame",this._canvasManager.SetFullscreenMode("off"),this._devicePixelRatio=1,self.devicePixelRatio=1,await this.PostComponentMessageToDOMAsync("runtime","set-exporting-to-video",{"message":this._exportToVideo.GetExportingMessageForPercent(0),"duration":this._exportToVideo.GetDuration()})}GetLoaderStyle(){return this._loaderStyle}IsExportToVideo(){return null!==this._exportToVideo}GetExportVideoDuration(){return this._exportToVideo.GetDuration()}GetExportVideoFramerate(){return this._exportToVideo.GetFramerate()}_InitExportToVideo(){return this._exportToVideo.Init({width:this._canvasManager.GetDeviceWidth(),height:this._canvasManager.GetDeviceHeight()})}_ExportToVideoAddFrame(){const e=this._tickCount/this.GetExportVideoFramerate();return this._exportToVideo.AddFrame(this._canvasManager.GetMainCanvas(),e)}_ExportToVideoAddKeyframe(){this._exportToVideo&&this._exportToVideo.AddKeyframe()}_OnOfflineAudioRenderCompleted(e){this._exportToVideo.OnOfflineAudioRenderCompleted(e)}_ExportToVideoFinish(){return this._exportToVideo.Finish()}IsFBInstantAvailable(){return this._isFBInstantAvailable}IsLoading(){return this._isLoading}AddLoadPromise(e){this._additionalLoadPromises.push(e)}SetUsingCreatePromises(e){this._isUsingCreatePromises=!!e}AddCreatePromise(e){this._isUsingCreatePromises&&this._additionalCreatePromises.push(e)}GetCreatePromises(){return this._additionalCreatePromises}_GetNextFamilyIndex(){return this._familyCount++}GetFamilyCount(){return this._familyCount}_AddEffectList(e){this._allEffectLists.add(e)}_RemoveEffectList(e){this._allEffectLists.delete(e)}_GetAllEffectLists(){return this._allEffectLists}async _InitialiseCanvas(e){this._canvasManager&&(await this._canvasManager.CreateCanvas(e),this._canvasManager.InitLoadingScreen(this._loaderStyle))}async Start(){this._hasStarted=!0,this._startTime=Date.now();let e=null;const t=new Promise((t=>e=t));if(this._usesLoaderLayout){for(const e of this._allObjectClasses)e.IsFamily()||e.IsOnLoaderLayout()||!e.IsWorldType()||e.OnCreate();(async()=>{await this._assetManager.WaitForAllToLoad(),await t,this._isLoading=!1,this._OnLoadFinished()})()}else this._isLoading=!1;this._assetManager.SetInitialLoadFinished(),this.IsDebug()&&C3Debugger.RuntimeInit(ife);for(const e of this._layoutManager.GetAllLayouts())e._CreateGlobalNonWorlds();this.IsExportToVideo()&&await this._InitExportToVideo();const s=this._layoutManager.GetFirstLayout();await s._Load(null,this.GetRenderer()),await s._StartRunning(!0),this._fpsLastTime=performance.now(),e(),this._usesLoaderLayout||this._OnLoadFinished();(await this.PostComponentMessageToDOMAsync("runtime","before-start-ticking"))["isSuspended"]&&!this.IsExportToVideo()?(this._suspendCount++,this._isPageVisibilitySuspended=!0):this.Tick()}_OnLoadFinished(){this.Trigger(C3.Plugins.System.Cnds.OnLoadFinished,null,null),this.PostComponentMessageToDOM("runtime","register-sw")}GetObjectReference(e){e=Math.floor(e);const t=this._objectReferenceTable;if(e<0||e>=t.length)throw new Error("invalid object reference");return t[e]}_LoadJsPropNameTable(){for(const e of self.C3_JsPropNameTable){const t=C3.first(Object.keys(e));this._jsPropNameTable.push(t)}}GetJsPropName(e){e=Math.floor(e);const t=this._jsPropNameTable;if(e<0||e>=t.length)throw new Error("invalid prop reference");return t[e]}HasDOM(){return this._hasDom}IsHeadless(){return this._isHeadless}IsInWorker(){return this._isInWorker}GetRuntimeBaseURL(){return this._runtimeBaseUrl}GetPreviewURL(){return this._previewUrl}GetEventSheetManager(){return this._eventSheetManager}GetEventStack(){return this._eventSheetManager.GetEventStack()}GetCurrentEventStackFrame(){return this._eventSheetManager.GetCurrentEventStackFrame()}GetCurrentEvent(){return this._eventSheetManager.GetCurrentEvent()}GetCurrentCondition(){return this._eventSheetManager.GetCurrentCondition()}IsCurrentConditionFirst(){return 0===this.GetCurrentEventStackFrame().GetConditionIndex()}GetCurrentAction(){return this._eventSheetManager.GetCurrentAction()}GetAddonManager(){return this._addonManager}GetSystemPlugin(){return this._addonManager.GetSystemPlugin()}GetObjectClassByIndex(e){if((e=Math.floor(e))<0||e>=this._allObjectClasses.length)throw new RangeError("invalid index");return this._allObjectClasses[e]}GetObjectClassByName(e){return this._objectClassesByName.get(e.toLowerCase())||null}GetObjectClassBySID(e){return this._objectClassesBySid.get(e)||null}GetSingleGlobalObjectClassByCtor(e){const t=C3.AddonManager.GetPluginByConstructorFunction(e);return t?t.GetSingleGlobalObjectClass():null}GetAllObjectClasses(){return this._allObjectClasses}*allInstances(){for(const e of this._allObjectClasses)e.IsFamily()||(yield*e.instances())}Dispatcher(){return this._dispatcher}UserScriptDispatcher(){return this._userScriptDispatcher}DispatchUserScriptEvent(e){e.runtime=this.GetIRuntime();const t=this.IsDebug()&&!this._eventSheetManager.IsInEventEngine();t&&C3Debugger.StartMeasuringScriptTime(),this._userScriptDispatcher.dispatchEvent(e),t&&C3Debugger.AddScriptTime()}DispatchUserScriptEventAsyncWait(e){return e.runtime=this.GetIRuntime(),this._userScriptDispatcher.dispatchEventAndWaitAsync(e)}GetOriginalViewportWidth(){return this._originalViewportWidth}GetOriginalViewportHeight(){return this._originalViewportHeight}SetOriginalViewportSize(e,t){if(this._originalViewportWidth===e&&this._originalViewportHeight===t)return;this._originalViewportWidth=e,this._originalViewportHeight=t;const s=this.GetLayoutManager();s.SetAllLayerProjectionChanged(),s.SetAllLayerMVChanged()}GetViewportWidth(){return this._viewportWidth}GetViewportHeight(){return this._viewportHeight}SetViewportSize(e,t){if(this._viewportWidth===e&&this._viewportHeight===t)return;this._viewportWidth=e,this._viewportHeight=t;const s=this.GetLayoutManager();s.SetAllLayerProjectionChanged(),s.SetAllLayerMVChanged()}_SetDevicePixelRatio(e){this.IsExportToVideo()||(this._devicePixelRatio=e)}GetDevicePixelRatio(){return this._devicePixelRatio}GetParallaxXOrigin(){return this._parallaxXorigin}GetParallaxYOrigin(){return this._parallaxYorigin}GetCanvasManager(){return this._canvasManager}GetDrawWidth(){return this._canvasManager?this._canvasManager.GetDrawWidth():this._viewportWidth}GetDrawHeight(){return this._canvasManager?this._canvasManager.GetDrawHeight():this._viewportHeight}GetRenderScale(){return this._canvasManager?this._canvasManager.GetRenderScale():1}GetDisplayScale(){return this._canvasManager?this._canvasManager.GetDisplayScale():1}GetEffectLayerScaleParam(){return this._canvasManager?this._canvasManager.GetEffectLayerScaleParam():1}GetEffectDevicePixelRatioParam(){return this._canvasManager?this._canvasManager.GetEffectDevicePixelRatioParam():1}GetCanvasClientX(){return this._canvasManager?this._canvasManager.GetCanvasClientX():0}GetCanvasClientY(){return this._canvasManager?this._canvasManager.GetCanvasClientY():0}GetCanvasCssWidth(){return this._canvasManager?this._canvasManager.GetCssWidth():0}GetCanvasCssHeight(){return this._canvasManager?this._canvasManager.GetCssHeight():0}GetFullscreenMode(){return this._canvasManager?this._canvasManager.GetFullscreenMode():"off"}GetAdditionalRenderTarget(e){return this._canvasManager?this._canvasManager.GetAdditionalRenderTarget(e):null}ReleaseAdditionalRenderTarget(e){this._canvasManager&&this._canvasManager.ReleaseAdditionalRenderTarget(e)}UsesAnyBackgroundBlending(){return this._usesAnyBackgroundBlending}UsesAnyCrossSampling(){return this._usesAnyCrossSampling}UsesAnyDepthSampling(){return this._usesAnyDepthSampling}GetGPUUtilisation(){return this._canvasManager?this._canvasManager.GetGPUUtilisation():NaN}IsLinearSampling(){return"nearest"!==this.GetSampling()}GetFramerateMode(){return this._framerateMode}_SetFramerateMode(e){this._framerateMode!==e&&(this._framerateMode=e,-1===this._rafId&&-1===this._ruafId||(this._CancelAnimationFrame(),this._RequestAnimationFrame()))}GetSampling(){return this._sampling}UsesLoaderLayout(){return this._usesLoaderLayout}GetLoadingLogoAsset(){return this._loadingLogoAsset}ReleaseLoadingLogoAsset(){this._loadingLogoAsset&&(this._loadingLogoAsset.ReleaseTexture(),this._loadingLogoAsset.Release(),this._loadingLogoAsset=null)}GetLayoutManager(){return this._layoutManager}GetMainRunningLayout(){return this._layoutManager.GetMainRunningLayout()}GetTimelineManager(){return this._timelineManager}GetTransitionManager(){return this._transitionManager}GetTemplateManager(){return this._templateManager}GetFlowchartManager(){return this._flowchartManager}GetAssetManager(){return this._assetManager}LoadImage(e){return this._assetManager.LoadImage(e)}CreateInstance(e,t,s,i,n,a){if(a&&this._templateManager){if(e instanceof C3.ObjectClass&&e.IsFamily()){const r=e.GetFamilyMembers(),o=Math.floor(this.Random()*r.length);return this.CreateInstance(r[o],t,s,i,n,a)}const r=this._templateManager.GetTemplateData(e,a);if(r){const e=this.CreateInstanceFromData(r,t,!1,s,i,!1,n,void 0,n);return this._templateManager.MapInstanceToTemplateName(e,a),e}}return this.CreateInstanceFromData(e,t,!1,s,i,!1,n,void 0,n)}CreateInstanceFromData(e,t,s,i,n,a,r,o,h){let l=null,c=null;if(e instanceof C3.ObjectClass){if(c=e,c.IsFamily()){const e=c.GetFamilyMembers();c=e[Math.floor(this.Random()*e.length)]}l=c.GetDefaultInstanceData()}else l=e,c=this.GetObjectClassByIndex(l[1]);const d=c.GetPlugin().IsWorldType();if(this._isLoading&&d&&!c.IsOnLoaderLayout())return null;const _=t;let u;d||(t=null),u=s&&!a&&l&&!this._instancesByUid.has(l[2])?l[2]:this._nextUid++;const g=l?l[0]:null,m=C3.New(C3.Instance,{runtime:this,objectType:c,layer:t,worldData:g,instVarData:l?l[3]:null,uid:u,tags:l?l[6]:null});this._instancesByUid.set(u,m);let p=null;if(d&&(p=m.GetWorldInfo(),void 0!==i&&void 0!==n&&(p.SetX(i),p.SetY(n)),c._SetAnyCollisionCellChanged(!0)),t&&(h||t._AddInstance(m,!0),t.GetLayout().MaybeLoadTexturesFor(c)),this._objectCount++,c.IsInContainer()&&!s&&!a){const e=new Set;for(const t of c.GetContainer().objectTypes()){if(t===c)continue;const s=this._MaybeGetChildInstanceForObjectTypeData(t,p,e);if(s){const e=this.CreateInstanceFromData(s,_,!1,p?p.GetX():i,p?p.GetY():n,!0,!1,void 0,h);m._AddSibling(e)}else{const e=this.CreateInstanceFromData(t,_,!1,p?p.GetX():i,p?p.GetY():n,!0,!1,void 0,h);m._AddSibling(e)}}for(const e of m.siblings()){e._AddSibling(m);for(const t of m.siblings())e!==t&&e._AddSibling(t)}}if(d&&!s&&r&&this._CreateChildInstancesFromData(m,g,p,t,i,n,h),c.IsInContainer()&&!s&&!a&&r)for(const e of m.siblings()){const s=e.GetWorldInfo();if(!s)continue;const i=e.GetPlugin(),n=e.GetObjectClass().GetDefaultInstanceData()[0];i.IsWorldType()?this._CreateChildInstancesFromData(e,n,s,t,s.GetX(),s.GetY(),h):this._CreateChildInstancesFromData(e,n,s,t,void 0,void 0,h)}if(!a&&r){void 0===i&&(i=g[0]),void 0===n&&(n=g[1]);const e=p.GetTopParent(),t=i-p.GetX()+e.GetX(),s=n-p.GetY()+e.GetY();e.SetXY(t,s)}c._SetIIDsStale();const f=l?C3.cloneArray(l[5]):null,C=l?l[4].map((e=>C3.cloneArray(e))):null,S=d&&g&&g[13];if(S&&m._SetHasTilemap(),m._CreateSdkInstance(f,C),S){const e=g[13];m.GetSdkInstance().LoadTilemapData(e[2],e[0],e[1])}this._instancesPendingCreate.push(m),this._hasPendingInstances=!0,this.IsDebug()&&C3Debugger.InstanceCreated(m);const I=this._eventObjects["instancecreate"];return I.instance=m,this._dispatcher.dispatchEvent(I),m}_GetInstanceData(e){const t=e[0],s=e[1],i=e[2],n=e[6];if(n)return n;return this._layoutManager.GetLayoutBySID(t).GetLayer(s).GetInitialInstanceData(i)}_MaybeGetChildInstanceForObjectTypeData(e,t,s){const i=t?.GetSceneGraphChildrenExportData()??[];for(const t of i){const i=this._GetInstanceData(t),n=!!t[4],a=this.GetObjectClassByIndex(i[1]);if(!s.has(i)&&(e===a&&n))return s.add(i),i}}_CreateChildInstancesFromData(e,t,s,i,n,a,r){const o=s.GetSceneGraphZIndexExportData(),h=s.GetSceneGraphChildrenExportData();if(e.GetWorldInfo().SetSceneGraphZIndex(o),!h)return;void 0===n&&(n=t[0]),void 0===a&&(a=t[1]);const l=new Set,c=t[0],d=t[1];for(const t of h){const s=t[0],o=t[1],h=t[2],_=t[3],u=!!t[4],g=t[5],m=t[6];let p;if(m)p=m;else{p=this._layoutManager.GetLayoutBySID(s).GetLayer(o).GetInitialInstanceData(h)}const f=this.GetObjectClassByIndex(p[1]),C=e.HasSibling(f),S=l.has(f);if(C&&!S&&u){const t=e.GetSibling(f);t.GetWorldInfo().Init(p[0]);const s=n+p[0][0]-c,i=a+p[0][1]-d;t.GetWorldInfo().SetXY(s,i),t.GetWorldInfo().SetSceneGraphZIndex(g),e.AddChild(t,{transformX:!!(1&_),transformY:!!(_>>1&1),transformWidth:!!(_>>2&1),transformHeight:!!(_>>3&1),transformAngle:!!(_>>4&1),destroyWithParent:!!(_>>5&1),transformZElevation:!!(_>>6&1),transformOpacity:!!(_>>7&1),transformVisibility:!!(_>>8&1)}),l.add(f)}else{const t=n+p[0][0]-c,s=a+p[0][1]-d,o=this.CreateInstanceFromData(p,i,!1,t,s,!1,!0,e,r);o.GetWorldInfo().SetSceneGraphZIndex(g),e.AddChild(o,{transformX:!!(1&_),transformY:!!(_>>1&1),transformWidth:!!(_>>2&1),transformHeight:!!(_>>3&1),transformAngle:!!(_>>4&1),destroyWithParent:!!(_>>5&1),transformZElevation:!!(_>>6&1),transformOpacity:!!(_>>7&1),transformVisibility:!!(_>>8&1)})}}}DestroyInstance(e){if(this._instancesPendingRelease.has(e))return;const t=e.GetObjectClass();let s=this._instancesPendingDestroy.get(t);if(s){if(s.has(e))return;s.add(e)}else s=new Set,s.add(e),this._instancesPendingDestroy.set(t,s);if(this.IsDebug()&&C3Debugger.InstanceDestroyed(e),e._MarkDestroyed(),this._hasPendingInstances=!0,e.IsInContainer())for(const t of e.siblings())this.DestroyInstance(t);for(const t of e.children())t.GetDestroyWithParent()&&this.DestroyInstance(t);if(!this._layoutManager.IsEndingLayout()&&!this._isLoadingState){const t=this.GetEventSheetManager();t.BlockFlushingInstances(!0),e._TriggerOnDestroyed(),t.BlockFlushingInstances(!1)}e._FireDestroyedScriptEvents(this._layoutManager.IsEndingLayout())}FlushPendingInstances(){this._hasPendingInstances&&(this._isFlushingPendingInstances=!0,this._FlushInstancesPendingCreate(),this._FlushInstancesPendingDestroy(),this._isFlushingPendingInstances=!1,this._hasPendingInstances=!1,this.UpdateRender())}_FlushInstancesPendingCreate(){for(const e of this._instancesPendingCreate){const t=e.GetObjectClass();t._AddInstance(e);for(const s of t.GetFamilies())s._AddInstance(e),s._SetIIDsStale()}C3.clearArray(this._instancesPendingCreate)}_FlushInstancesPendingDestroy(){this._dispatcher.SetDelayRemoveEventsEnabled(!0);for(const[e,t]of this._instancesPendingDestroy.entries())this._FlushInstancesPendingDestroyForObjectClass(e,t),t.clear();this._instancesPendingDestroy.clear(),this._dispatcher.SetDelayRemoveEventsEnabled(!1)}_FlushInstancesPendingDestroyForObjectClass(e,t){for(const e of t){const t=this._eventObjects["instancedestroy"];t.instance=e,this._dispatcher.dispatchEvent(t),this._instancesByUid.delete(e.GetUID()),this._instanceTimes.delete(e);const s=e.GetWorldInfo();s&&(s._RemoveFromCollisionCells(),s._RemoveFromRenderCells(),s._MarkDestroyed()),this._instancesPendingRelease.add(e),this._objectCount--}C3.arrayRemoveAllInSet(e.GetInstances(),t),e._SetIIDsStale(),this._instancesPendingReleaseAffectedObjectClasses.add(e);for(const s of e.GetFamilies())C3.arrayRemoveAllInSet(s.GetInstances(),t),s._SetIIDsStale(),this._instancesPendingReleaseAffectedObjectClasses.add(s);if(e.GetPlugin().IsWorldType()){const e=new Set([...t].map((e=>e.GetWorldInfo().GetLayer())));for(const s of e)s._RemoveAllInstancesInSet(t)}}_GetInstancesPendingCreate(){return this._instancesPendingCreate}*instancesPendingCreateForObjectClass(e){for(const t of this._GetInstancesPendingCreate())e.IsFamily()?t.GetObjectClass().BelongsToFamily(e)&&(yield t):t.GetObjectClass()===e&&(yield t)}_GetNewUID(){return this._nextUid++}_MapInstanceByUID(e,t){this._instancesByUid.set(e,t)}_SetAutoSuspendEnabled(e){e=!!e,this._isAutoSuspendEnabled!==e&&(this._isAutoSuspendEnabled=!!e,this._isAutoSuspendEnabled&&this._isPageVisibilitySuspended&&(this.SetSuspended(!1),this._isPageVisibilitySuspended=!1))}_IsAutoSuspendEnabled(){return this._isAutoSuspendEnabled}_OnRendererContextLost(){this._dispatcher.dispatchEvent(C3.New(C3.Event,"renderercontextlost")),this.SetSuspended(!0);for(const e of this._allObjectClasses)!e.IsFamily()&&e.HasLoadedTextures()&&e.ReleaseTextures();const e=this.GetMainRunningLayout();e&&e._OnRendererContextLost(),C3.ImageInfo.OnRendererContextLost(),C3.ImageAsset.OnRendererContextLost()}async _OnRendererContextRestored(){await this.GetMainRunningLayout()._Load(null,this.GetRenderer()),this._dispatcher.dispatchEvent(C3.New(C3.Event,"renderercontextrestored")),this.SetSuspended(!1),this.UpdateRender()}_OnVisibilityChange(e){if(!this._isAutoSuspendEnabled)return;const t=e["hidden"];this.SetSuspended(t),this._isPageVisibilitySuspended=t,t||this.UpdateRender()}_OnWindowBlur(e){this.IsPreview()&&this._pauseOnBlur&&!C3.Platform.IsMobile&&(e.data["parentHasFocus"]||(this.SetSuspended(!0),this._isPausedOnBlur=!0))}_OnWindowFocus(){this._isPausedOnBlur&&(this.SetSuspended(!1),this._isPausedOnBlur=!1)}_RequestAnimationFrame(){const e=this._tickCallbacks;"vsync"===this._framerateMode?-1===this._rafId&&(this._rafId=self.requestAnimationFrame(e.normal)):"unlimited-tick"===this._framerateMode?(-1===this._ruafId&&(this._ruafId=C3.RequestUnlimitedAnimationFrame(e.tickOnly)),-1===this._rafId&&(this._rafId=self.requestAnimationFrame(e.renderOnly))):-1===this._ruafId&&(this._ruafId=C3.RequestUnlimitedAnimationFrame(e.normal))}_CancelAnimationFrame(){-1!==this._rafId&&(self.cancelAnimationFrame(this._rafId),this._rafId=-1),-1!==this._ruafId&&(C3.CancelUnlimitedAnimationFrame(this._ruafId),this._ruafId=-1)}IsSuspended(){return this._suspendCount>0}SetSuspended(e){if(this.IsExportToVideo())return;const t=this.IsSuspended();this._suspendCount+=e?1:-1,this._suspendCount<0&&(this._suspendCount=0);const s=this.IsSuspended();if(!t&&s)console.log("[Construct] Suspending"),this._CancelAnimationFrame(),this._dispatcher.dispatchEvent(C3.New(C3.Event,"suspend")),this.DispatchUserScriptEvent(C3.New(C3.Event,"suspend")),this.Trigger(C3.Plugins.System.Cnds.OnSuspend,null,null);else if(t&&!s){console.log("[Construct] Resuming");const e=performance.now();this._lastTickTime=e,this._fpsLastTime=e,this._fpsFrameCount=0,this._fps=0,this._tpsTickCount=0,this._tps=0,this._mainThreadTime=0,this._mainThreadTimeCounter=0,this._dispatcher.dispatchEvent(C3.New(C3.Event,"resume")),this.DispatchUserScriptEvent(C3.New(C3.Event,"resume")),this.Trigger(C3.Plugins.System.Cnds.OnResume,null,null),this.HitBreakpoint()||this.Tick(e)}}_AddBehInstToTick(e){this._behInstsToTick.Add(e)}_AddBehInstToPostTick(e){this._behInstsToPostTick.Add(e)}_AddBehInstToTick2(e){this._behInstsToTick2.Add(e)}_RemoveBehInstToTick(e){this._behInstsToTick.Remove(e)}_RemoveBehInstToPostTick(e){this._behInstsToPostTick.Remove(e)}_RemoveBehInstToTick2(e){this._behInstsToTick2.Remove(e)}_CallBehaviorTickMethod(e,t){const s=t?performance.now():0;let i;return e instanceof ISDKBehaviorInstanceBase?(i=e._tick(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.behavior,performance.now()-s)):(i=e.Tick(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.GetBehavior(),performance.now()-s)),i}_BehaviorTick(){const e=this.IsDebug();this._behInstsToTick.SetQueueingEnabled(!0);for(const t of this._behInstsToTick)this._CallBehaviorTickMethod(t,e);this._behInstsToTick.SetQueueingEnabled(!1)}_CallBehaviorPostTickMethod(e,t){const s=t?performance.now():0;let i;return e instanceof ISDKBehaviorInstanceBase?(i=e._postTick(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.behavior,performance.now()-s)):(i=e.PostTick(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.GetBehavior(),performance.now()-s)),i}_BehaviorPostTick(){const e=this.IsDebug();this._behInstsToPostTick.SetQueueingEnabled(!0);for(const t of this._behInstsToPostTick)this._CallBehaviorPostTickMethod(t,e);this._behInstsToPostTick.SetQueueingEnabled(!1)}_CallBehaviorTick2Method(e,t){const s=t?performance.now():0;let i;return e instanceof ISDKBehaviorInstanceBase?(i=e._tick2(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.behavior,performance.now()-s)):(i=e.Tick2(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.GetBehavior(),performance.now()-s)),i}_BehaviorTick2(){const e=this.IsDebug();this._behInstsToTick2.SetQueueingEnabled(!0);for(const t of this._behInstsToTick2)this._CallBehaviorTick2Method(t,e);this._behInstsToTick2.SetQueueingEnabled(!1)}*_DebugBehaviorTick(){const e=this.IsDebug();this._behInstsToTick.SetQueueingEnabled(!0);for(const t of this._behInstsToTick){const s=this._CallBehaviorTickMethod(t,e);C3.IsIterator(s)&&(yield*s)}this._behInstsToTick.SetQueueingEnabled(!1)}*_DebugBehaviorPostTick(){const e=this.IsDebug();this._behInstsToPostTick.SetQueueingEnabled(!0);for(const t of this._behInstsToPostTick){const s=this._CallBehaviorPostTickMethod(t,e);C3.IsIterator(s)&&(yield*s)}this._behInstsToPostTick.SetQueueingEnabled(!1)}*_DebugBehaviorTick2(){const e=this.IsDebug();this._behInstsToTick2.SetQueueingEnabled(!0);for(const t of this._behInstsToTick2){const s=this._CallBehaviorTick2Method(t,e);C3.IsIterator(s)&&(yield*s)}this._behInstsToTick2.SetQueueingEnabled(!1)}async Tick(e,t,s){this._hasStartedTicking=!0;const i="background-wake"===s,n="background-wake"!==s&&"skip-render"!==s,a=this.GetLayoutManager(),r=this.GetCanvasManager();if(!this._hasStarted||this.IsSuspended()&&!t&&!i)return;const o=performance.now();this._isInTick=!0,this._MeasureDt(e||0),this._tpsTickCount++,this._ReleasePendingInstances();const h=this.Step_BeforePreTick();this.IsDebugging()&&await h;const l=this._dispatcher.dispatchEventAndWait_AsyncOptional(this._eventObjects["pretick"]);l instanceof Promise&&await l,this.DispatchUserScriptEvent(this._userScriptEventObjects["pretick"]);const c=this.Step_AfterPreTick();this.IsDebugging()&&await c,this._NeedsHandleSaveOrLoad()&&await this._HandleSaveOrLoad(),a.IsPendingChangeMainLayout()&&await this._MaybeChangeLayout();const d=this.Step_RunEventsEtc();this.IsDebugging()&&await d;const _=a.GetMainRunningLayout(),u=_._GetPendingSetHTMLLayerCount();let g=!1;if(-1!==u&&(_._ResetPendingHTMLLayerCount(),r.GetHTMLLayerCount()!==u)){const e=this.GetCanvasManager().SetHTMLLayerCount(u);this.IsInWorker()&&(g=!0,await e)}this.PostComponentMessageToDOM("canvas","update-html-layer-dom-state",{"layersDomState":_._GetRootLayers().filter((e=>e.IsHTMLElementsLayer())).map((e=>e._GetHTMLLayerDOMState()))}),n&&this.Render(),g&&this.PostComponentMessageToDOM("canvas","cleanup-html-layers"),this.IsExportToVideo()&&(await this._ExportToVideoAddFrame(),this.GetGameTime()>=this.GetExportVideoDuration())?this._ExportToVideoFinish():(this.IsSuspended()||i||this._RequestAnimationFrame(),this._tickCount++,this._tickCountNoSave++,this._isInTick=!1,this._mainThreadTimeCounter+=performance.now()-o)}async Step_BeforePreTick(){const e=this._eventSheetManager,t=this.IsDebug();this.FlushPendingInstances(),e.BlockFlushingInstances(!0),this.PushCurrentLayout(this.GetMainRunningLayout()),t&&C3Debugger.StartMeasuringTime(),this.IsDebugging()?await e.DebugRunScheduledWaits():e.RunScheduledWaits(),t&&C3Debugger.AddEventsTime(),this.PopCurrentLayout(),e.BlockFlushingInstances(!1),this.FlushPendingInstances(),e.BlockFlushingInstances(!0)}async Step_AfterPreTick(){const e=this._eventSheetManager,t=this.IsDebug(),s=this.IsDebugging(),i=this._dispatcher,n=this._eventObjects,a=this._userScriptEventObjects;t&&C3Debugger.StartMeasuringTime(),s?await this.DebugIterateAndBreak(this._DebugBehaviorTick()):this._BehaviorTick(),s?await this.DebugIterateAndBreak(this._DebugBehaviorPostTick()):this._BehaviorPostTick(),t&&C3Debugger.AddBehaviorTotalTickTime(),t&&C3Debugger.StartMeasuringTime(),s?await this.DebugFireGeneratorEventAndBreak(n["tick"]):i.dispatchEvent(n["tick"]),t&&C3Debugger.AddPluginTotalTickTime(),e.BlockFlushingInstances(!1),this.DispatchUserScriptEvent(a["tick"])}async Step_RunEventsEtc(){const e=this._eventSheetManager,t=this._dispatcher,s=this._eventObjects,i=this._userScriptEventObjects,n=this.IsDebug(),a=this.IsDebugging();n&&C3Debugger.StartMeasuringTime(),a?await e.DebugRunEvents(this._layoutManager):e.RunEvents(this._layoutManager),n&&C3Debugger.AddEventsTime(),this._collisionEngine.ClearRegisteredCollisions(),this._ReleasePendingInstances(),this._isLayoutFirstTick=!1,e.BlockFlushingInstances(!0),n&&C3Debugger.StartMeasuringTime(),a?await this.DebugIterateAndBreak(this._DebugBehaviorTick2()):this._BehaviorTick2(),n&&C3Debugger.AddBehaviorTotalTickTime(),n&&C3Debugger.StartMeasuringTime(),a?await this.DebugFireGeneratorEventAndBreak(s["tick2"]):t.dispatchEvent(s["tick2"]),n&&C3Debugger.AddPluginTotalTickTime(),e.BlockFlushingInstances(!1),this.DispatchUserScriptEvent(i["tick2"]),a&&await e.RunQueuedDebugTriggersAsync(),this.FlushPendingInstances(),this._ReleasePendingInstances()}_ReleasePendingInstances(){if(0===this._instancesPendingRelease.size)return;const e=this._dispatcher;e.SetDelayRemoveEventsEnabled(!0);for(const e of this._instancesPendingReleaseAffectedObjectClasses)e.GetSolStack().RemoveInstances(this._instancesPendingRelease);this._instancesPendingReleaseAffectedObjectClasses.clear(),this._eventSheetManager._OnInstancesReleased(this._instancesPendingRelease);for(const e of this._instancesPendingRelease)e.Release();this._instancesPendingRelease.clear(),e.SetDelayRemoveEventsEnabled(!1)}async _MaybeChangeLayout(){const e=this.GetLayoutManager();let t=0;for(;e.IsPendingChangeMainLayout()&&t++<10;)await this._DoChangeLayout(e.GetPendingChangeMainLayout())}_MeasureDt(e){let t=0;if(this.IsExportToVideo())t=1/this.GetExportVideoFramerate(),this._dtRaw=t,this._dt1=t;else if(0!==this._lastTickTime){t=Math.max(e-this._lastTickTime,0)/1e3,t>.5&&(t=0),this._dtRaw=t,this._dt1=C3.clamp(t,this._minDt,this._maxDt)}this._lastTickTime=e,this._dt=this._dt1*this._timeScale,this._gameTime.Add(this._dt),this._gameTimeRaw.Add(t*this._timeScale),this._wallTime.Add(this._dt1);for(const[e,t]of this._instanceTimes)t.Add(this._dt1*e.GetTimeScale());this._canvasManager&&this._canvasManager._UpdateTick(),e-this._fpsLastTime>=1e3&&(this._fpsLastTime+=1e3,e-this._fpsLastTime>=1e3&&(this._fpsLastTime=e),this._fps=this._fpsFrameCount,this._fpsFrameCount=0,this._tps=this._tpsTickCount,this._tpsTickCount=0,this._mainThreadTime=Math.min(this._mainThreadTimeCounter/1e3,1),this._mainThreadTimeCounter=0,this._canvasManager&&this._canvasManager._Update1sFrameRange(),this._collisionEngine._Update1sStats(),this.IsDebug()&&C3Debugger.Update1sPerfStats())}_SetTrackingInstanceTime(e,t){if(t){if(!this._instanceTimes.has(e)){const t=C3.New(C3.KahanSum);t.Copy(this._gameTime),this._instanceTimes.set(e,t)}}else this._instanceTimes.delete(e)}_GetInstanceGameTime(e){const t=this._instanceTimes.get(e);return t?t.Get():this.GetGameTime()}async _DoChangeLayout(e){const t=this._dispatcher,s=this.GetLayoutManager().GetMainRunningLayout();await s._StopRunning(),s._Unload(e,this.GetRenderer()),s===e&&this._eventSheetManager.ClearAllScheduledWaits(),this._collisionEngine.ClearRegisteredCollisions(),this._ReleasePendingInstances(),t.dispatchEvent(this._eventObjects["beforelayoutchange"]),C3.Asyncify.SetHighThroughputMode(!0),await e._Load(s,this.GetRenderer()),C3.Asyncify.SetHighThroughputMode(!1),await e._StartRunning(!1),t.dispatchEvent(this._eventObjects["layoutchange"]),this.UpdateRender(),this._isLayoutFirstTick=!0,this.FlushPendingInstances(),this._ExportToVideoAddKeyframe()}UpdateRender(){this._needRender=!0}GetWebGLRenderer(){return this._canvasManager?this._canvasManager.GetWebGLRenderer():null}GetWebGPURenderer(){return this._canvasManager?this._canvasManager.GetWebGPURenderer():null}GetRenderer(){return this._canvasManager?this._canvasManager.GetRenderer():null}Render(){const e=this._canvasManager;if(!e||e.IsRendererContextLost())return;const t=this.GetRenderer(),s=t.SupportsGPUProfiling(),i=s&&t.IsWebGL(),n=s&&t.IsWebGPU();if(i&&t.CheckForQueryResults(),!this._needRender&&!this.IsExportToVideo())return void t.IncrementFrameNumber();const a=this._layoutManager.GetMainRunningLayout();this._fpsFrameCount++,t.Start();const r=this.IsDebug();r&&C3Debugger.StartMeasuringTime(),this._needRender=!1;let o=null;i&&(o=e.GetGPUFrameTimingsBuffer().AddTimeElapsedQuery(),t.StartQuery(o));let h=null;n&&(h=t.StartFrameTiming(2*(1+a.GetLayerCount())),t.StartMeasuringRenderPassTime(0,1)),this.Uses3DFeatures()&&"low"===e.GetCurrentFullscreenScalingQuality()?t.SetFixedSizeDepthBuffer(e.GetDrawWidth(),e.GetDrawHeight()):t.SetAutoSizeDepthBuffer(),this._Render(this.GetRenderer(),a),o&&t.EndQuery(o),n&&(t.StopMeasuringRenderPassTime(),this._canvasManager._AddWebGPUFrameTiming(h)),t.Finish(),r&&(C3Debugger.AddDrawCallsTime(),C3Debugger.UpdateInspectHighlight()),e&&e._MaybeTakeSnapshot()}_NeedsHTMLLayerCompositing(e){return"low"===this.GetCanvasManager().GetCurrentFullscreenScalingQuality()||e.IsWebGL()&&(this.UsesAnyBackgroundBlending()||this.Uses3DFeatures())}_Render(e,t){e.SetTextureFillMode(),e.SetAlphaBlend(),e.SetColorRgba(1,1,1,1),e.SetRenderTarget(null),e.SetTexture(null),e.SetDepthEnabled(this.Uses3DFeatures()),this._NeedsHTMLLayerCompositing(e)&&t._MaybeStartDrawToOwnTexture(e);const s=t.GetHTMLLayerCount();for(let i=1;i<s;++i)t.DrawForHTMLLayerIndex(e,i),e.IsWebGPU()&&e.Restart();this._NeedsHTMLLayerCompositing(e)||t._MaybeStartDrawToOwnTexture(e),t.DrawMain(e)}Trigger(e,t,s){if(!this._hasStarted)return!1;const i=!this._isInTick&&!this._eventSheetManager.IsInTrigger();let n=0;i&&(n=performance.now());const a=this.IsDebug();a&&this.SetDebuggingEnabled(!1);const r=this._eventSheetManager._Trigger(this._layoutManager,e,t,s);if(i){const e=performance.now()-n;this._mainThreadTimeCounter+=e,a&&C3Debugger.AddTriggersTime(e)}return a&&this.SetDebuggingEnabled(!0),r}DebugTrigger(e,t,s){if(!this.IsDebugging())return this.Trigger(e,t,s);if(this.HitBreakpoint())throw new Error("called DebugTrigger() while stopped on breakpoint");if(!this._isInTick&&!this._eventSheetManager.IsInTrigger())throw new Error("called DebugTrigger() outside of event code - use TriggerAsync() instead");return this._eventSheetManager._DebugTrigger(this._layoutManager,e,t,s)}async TriggerAsync(e,t,s){if(!this.IsDebugging())return this.Trigger(e,t,s);if(!this._hasStarted)return!1;if(this.HitBreakpoint())return this._eventSheetManager.QueueDebugTrigger(e,t,s);if(!this.GetMainRunningLayout())return this._eventSheetManager.QueueTrigger(e,t,s);const i=performance.now(),n=this._eventSheetManager._DebugTrigger(this._layoutManager,e,t,s);let a=n.next();for(;!a.done;)await this.DebugBreak(a.value),a=n.next();return this.IsSuspended()||this._eventSheetManager.IsInTrigger()||(await this._eventSheetManager.RunQueuedDebugTriggersAsync(),this._hasStartedTicking&&!this._isInTick&&this._RequestAnimationFrame()),this._mainThreadTimeCounter+=performance.now()-i,a.value}FastTrigger(e,t,s){const i=this.IsDebug();i&&this.SetDebuggingEnabled(!1);const n=this._eventSheetManager._FastTrigger(this._layoutManager,e,t,s);return i&&this.SetDebuggingEnabled(!0),n}DebugFastTrigger(e,t,s){return this._eventSheetManager._DebugFastTrigger(this._layoutManager,e,t,s)}ScheduleTriggers(e){return this._scheduleTriggersThrottle.Add(e)}PushCurrentLayout(e){this._currentLayoutStack.push(e)}PopCurrentLayout(){if(!this._currentLayoutStack.length)throw new Error("layout stack empty");this._currentLayoutStack.pop()}GetCurrentLayout(){return this._currentLayoutStack.length?this._currentLayoutStack.at(-1):this.GetMainRunningLayout()}GetDt(e){return e&&-1!==e.GetTimeScale()?this._dt1*e.GetTimeScale():this._dt}_GetDtFast(){return this._dt}GetDt1(){return this._dt1}GetDtRaw(){return this._dtRaw}GetTimeScale(){return this._timeScale}SetTimeScale(e){(isNaN(e)||e<0)&&(e=0),this._timeScale=e}SetMinDt(e){this._minDt=Math.max(e,0)}GetMinDt(){return this._minDt}SetMaxDt(e){this._maxDt=Math.max(e,0)}GetMaxDt(){return this._maxDt}GetFramesPerSecond(){return this._fps}GetTicksPerSecond(){return this._tps}GetMainThreadTime(){return this._mainThreadTime}GetStartTime(){return this._startTime}GetGameTime(){return this._gameTime.Get()}GetGameTimeRaw(){return this._gameTimeRaw.Get()}GetWallTime(){return this._wallTime.Get()}GetTickCount(){return this._tickCount}GetTickCountNoSave(){return this._tickCountNoSave}GetObjectCount(){return this._objectCount}GetProjectName(){return this._projectName}GetProjectVersion(){return this._projectVersion}GetProjectUniqueId(){return this._projectUniqueId}GetAppId(){return this._appId}GetExportTimestamp(){return this._exportTimestamp}GetInstanceByUID(e){if(this._isLoadingState)throw new Error("cannot call while loading state - wait until afterload event");return this._instancesByUid.get(e)||null}_RemoveInstanceFromUIDMap(e){if(this._isLoadingState)throw new Error("cannot call while loading state - wait until afterload event");this._instancesByUid.delete(e)}_RefreshUidMap(){this._instancesByUid.clear();for(const e of this._allObjectClasses)if(!e.IsFamily())for(const t of e.GetInstances())this._instancesByUid.set(t.GetUID(),t)}IsPreview(){return"preview"===this._exportType}IsDebug(){return this._isDebug}GetExportType(){return this._exportType}IsNWjs(){return"nwjs"===this.GetExportType()||this._isNWjs}IsCordova(){return"cordova"===this._exportType}IsAndroidWebView(){return"Android"===C3.Platform.OS&&("cordova"===this._exportType||"playable-ad-single-file"===this._exportType||"playable-ad-zip"===this._exportType||"instant-games"===this._exportType)}IsiOSCordova(){return this._isiOSCordova}IsiOSWebView(){return this._isiOSWebView}IsWindowsWebView2(){return this._isWindowsWebView2}IsAnyWebView2Wrapper(){return this._isAnyWebView2Wrapper}GetCollisionEngine(){return this._collisionEngine}GetSolidBehavior(){return this._addonManager.GetSolidBehavior()}GetJumpthruBehavior(){return this._addonManager.GetJumpthruBehavior()}Uses3DFeatures(){return this._uses3dFeatures}GetZScaleFactor(){return this.GetRenderer().GetZAxisScaleFactor(this.GetViewportHeight())}GetDefaultCameraZ(e){return this.GetRenderer().GetDefaultCameraZ(e||this.GetViewportHeight())}IsLayoutFirstTick(){return this._isLayoutFirstTick}SetPixelRoundingEnabled(e){e=!!e,this._isPixelRoundingEnabled!==e&&(this._isPixelRoundingEnabled=e,this.GetLayoutManager().SetAllLayerMVChanged(),this.UpdateRender())}IsPixelRoundingEnabled(){return this._isPixelRoundingEnabled}GetTextIconSet(e){if(!this._iconChangeHandlers.has(e)){const t=()=>this.DeleteTextIconSet(e);this._iconChangeHandlers.set(e,t),e.Dispatcher().addEventListener("animationframeimagechange",t)}const t=this._textIconManager.GetIconSet(e);return t.HasLoaded()||t.LoadContent().then((()=>this.UpdateRender())),t}DeleteTextIconSet(e){this._textIconManager.DeleteIconSet(e)}_GetTextIconSetMeta(e){const t=[];for(const s of e.GetAnimations())for(const e of s.GetFrames()){const s=e.GetImageInfo();t.push({source:e,width:s.GetWidth(),height:s.GetHeight(),tag:e.GetTag()})}return{icons:t}}async _GetTextIconSetContent(e){const t=C3.New(C3.PromiseThrottle),s=[],i=new Map;for(const n of e.GetAnimations())for(const e of n.GetFrames()){const n=e.GetImageInfo().GetImageAsset();i.has(n)||(i.set(n,null),s.push(t.Add((async()=>{const e=await n.LoadToDrawable();i.set(n,e)}))))}await Promise.all(s);const n=[];for(const s of e.GetAnimations())for(const e of s.GetFrames())n.push(t.Add((async()=>{const t=e.GetImageInfo(),s=i.get(t.GetImageAsset()),n=await t.ExtractImageToCanvas(s);return{drawable:await createImageBitmap(n)}})));const a=await Promise.all(n);for(const e of i.values())e instanceof ImageBitmap&&e["close"]&&e["close"]();return{icons:a}}SaveToSlot(e){this._saveToSlotName=e,this._saveToJsonString=!1}SaveToJsonString(){this._saveToSlotName="",this._saveToJsonString=!0}LoadFromSlot(e){this._loadFromSlotName=e}LoadFromJsonString(e){this._loadFromJson=e}GetLastSaveJsonString(){return this._lastSaveJson}_NeedsHandleSaveOrLoad(){return!!(this._saveToSlotName||this._saveToJsonString||this._loadFromSlotName||null!==this._loadFromJson)}async _HandleSaveOrLoad(){if(this._saveToSlotName&&(this.FlushPendingInstances(),await this._DoSaveToSlot(this._saveToSlotName),this._ClearSaveOrLoad()),this._loadFromSlotName&&(await this._DoLoadFromSlot(this._loadFromSlotName),this._ClearSaveOrLoad(),this.IsDebug()&&C3Debugger.StepIfPausedInDebugger()),this._saveToJsonString){const e=await this._SaveToJsonString();this._lastSaveJson=e,await this.TriggerAsync(C3.Plugins.System.Cnds.OnSaveComplete,null),this._lastSaveJson="",this._ClearSaveOrLoad()}if(null!==this._loadFromJson){this.FlushPendingInstances();try{await this._DoLoadFromJsonString(this._loadFromJson),this._lastSaveJson=this._loadFromJson,await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadComplete,null),this._lastSaveJson=""}catch(e){console.error("[Construct] Failed to load state from JSON string: ",e),await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadFailed,null)}this._ClearSaveOrLoad()}}_ClearSaveOrLoad(){this._saveToSlotName="",this._saveToJsonString=!1,this._loadFromSlotName="",this._loadFromJson=null}_GetProjectStorage(){return this._projectStorage||(this._projectStorage=localforage.createInstance({name:"c3-localstorage-"+this.GetProjectUniqueId(),description:this.GetProjectName()})),this._projectStorage}_GetSavegamesStorage(){return this._savegamesStorage||(this._savegamesStorage=localforage.createInstance({name:"c3-savegames-"+this.GetProjectUniqueId(),description:this.GetProjectName()})),this._savegamesStorage}async _DoSaveToSlot(e){const t=await this._SaveToJsonString();try{await this._GetSavegamesStorage().setItem(e,t),console.log("[Construct] Saved state to storage ("+t.length+" chars)"),this._lastSaveJson=t,await this.TriggerAsync(C3.Plugins.System.Cnds.OnSaveComplete,null),this._lastSaveJson=""}catch(e){console.error("[Construct] Failed to save state to storage: ",e),await this.TriggerAsync(C3.Plugins.System.Cnds.OnSaveFailed,null)}}async _DoLoadFromSlot(e){try{const t=await this._GetSavegamesStorage().getItem(e);if(!t)throw new Error("empty slot");console.log("[Construct] Loaded state from storage ("+t.length+" chars)"),await this._DoLoadFromJsonString(t),this._lastSaveJson=t,await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadComplete,null),this._lastSaveJson=""}catch(e){console.error("[Construct] Failed to load state from storage: ",e),await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadFailed,null)}}async _SaveToJsonString(){const e={"c3save":!0,"version":1,"rt":{"time":this.GetGameTime(),"timeRaw":this.GetGameTimeRaw(),"walltime":this.GetWallTime(),"timescale":this.GetTimeScale(),"tickcount":this.GetTickCount(),"next_uid":this._nextUid,"running_layout":this.GetMainRunningLayout().GetSID(),"start_time_offset":Date.now()-this._startTime},"types":{},"layouts":{},"events":this._eventSheetManager._SaveToJson(),"timelines":this._timelineManager._SaveToJson(),"user_script_data":null};for(const t of this._allObjectClasses)t.IsFamily()||t.HasNoSaveBehavior()||(e["types"][t.GetSID().toString()]=t._SaveToJson());for(const t of this._layoutManager.GetAllLayouts())e["layouts"][t.GetSID().toString()]=t._SaveToJson();const t=this._CreateUserScriptEvent("save");return t.saveData=null,await this.DispatchUserScriptEventAsyncWait(t),e["user_script_data"]=t.saveData,JSON.stringify(e)}IsLoadingState(){return this._isLoadingState}async _DoLoadFromJsonString(e){const t=this.GetLayoutManager(),s=JSON.parse(e);if(s["c2save"])throw new Error("C2 saves are incompatible with C3 runtime");if(!s["c3save"])throw new Error("not valid C3 save data");if(s["version"]>1)throw new Error("C3 save data from future version");this.ClearIntancesNeedingAfterLoad(),this._dispatcher.dispatchEvent(C3.New(C3.Event,"beforeload"));for(const e of this.allInstances()){e.GetObjectClass().HasNoSaveBehavior()||e._OnBeforeLoad()}const i=s["rt"];this._gameTime.Set(i["time"]),i.hasOwnProperty("timeRaw")&&this._gameTimeRaw.Set(i["timeRaw"]),this._wallTime.Set(i["walltime"]),this._timeScale=i["timescale"],this._tickCount=i["tickcount"],this._startTime=Date.now()-i["start_time_offset"];const n=i["running_layout"];this._isLoadingState=!0;let a=!1;if(n!==this.GetMainRunningLayout().GetSID()){const e=t.GetLayoutBySID(n);if(!e)return;await this._DoChangeLayout(e),a=!0}for(const[e,i]of Object.entries(s["layouts"])){const s=parseInt(e,10),n=t.GetLayoutBySID(s);n&&n._LoadFromJson(i)}const r=new Set;for(const[e,t]of Object.entries(s["types"])){const s=parseInt(e,10),i=this.GetObjectClassBySID(s);!i||i.IsFamily()||i.HasNoSaveBehavior()||i._LoadFromJson(t,r)}for(const e of this._layoutManager.GetAllLayouts())for(const t of e.allLayers())t._LoadFromJsonAfterInstances();if(this.FlushPendingInstances(),this._RefreshUidMap(),this._isLoadingState=!1,a){for(const e of this.allInstances())e.SetupInitialSceneGraphConnections();for(const[e,t]of Object.entries(s["types"])){const s=parseInt(e,10),i=this.GetObjectClassBySID(s);!i||i.IsFamily()||i.HasNoSaveBehavior()||i._SetupSceneGraphConnectionsOnChangeOfLayout(t)}}this._nextUid=i["next_uid"],this._eventSheetManager._LoadFromJson(s["events"]);for(const e of this._allObjectClasses)if(!e.IsFamily()&&e.IsInContainer())for(const t of e.GetInstances()){const s=t.GetIID();t._ClearSiblings();for(const i of e.GetContainer().objectTypes()){if(i===e)continue;const n=i.GetInstances();if(s<0||s>=n.length)throw new Error("missing sibling instance");t._AddSibling(n[s])}}this._timelineManager._LoadFromJson(s["timelines"]),t.SetAllLayerProjectionChanged(),t.SetAllLayerMVChanged();for(const e of r)e._OnCreatedForLoadingSavegame();this.DoAfterLoad(),this._dispatcher.dispatchEvent(C3.New(C3.Event,"afterload")),this.DispatchUserScriptEvent(this._CreateUserScriptEvent("afterload"));for(const[e,t]of Object.entries(s["types"])){const t=parseInt(e,10),s=this.GetObjectClassBySID(t);s&&s._ClearLoadInstancesJson()}const o=this._CreateUserScriptEvent("load");o.saveData=s["user_script_data"],await this.DispatchUserScriptEventAsyncWait(o),this.UpdateRender()}SortOnTmpHierarchyPosition(e,t){return t.GetWorldInfo().GetTmpHierarchyPosition()-e.GetWorldInfo().GetTmpHierarchyPosition()}AddInstanceNeedingAfterLoad(e,t){e.GetWorldInfo()&&(this._instancesNeedingAfterLoadMap.has(e)||(this._instancesNeedingAfterLoadMap.set(e,t),this._instancesNeedingAfterLoadArray.push(e)))}ClearIntancesNeedingAfterLoad(){this._instancesNeedingAfterLoadMap=new WeakMap,C3.clearArray(this._instancesNeedingAfterLoadArray),C3.SceneGraphInfo.ClearUpdatedInstances()}DoAfterLoad(e="full",t=null){this._instancesNeedingAfterLoadArray.sort(this.SortOnTmpHierarchyPosition),t||(t={}),t.processedWorldInfo=new Set;const s=this._instancesNeedingAfterLoadArray.length;for(const s of this._instancesNeedingAfterLoadArray)s._OnAfterLoad(this._instancesNeedingAfterLoadMap.get(s),e,t);for(const s of this._instancesNeedingAfterLoadArray)s._OnAfterLoad2(this._instancesNeedingAfterLoadMap.get(s),e,t);if(this.ClearIntancesNeedingAfterLoad(),s){this.FlushPendingInstances(),this._RefreshUidMap();for(const e of this._layoutManager.GetAllLayouts())for(const t of e.allLayers())t._SortInstancesByLastCachedZIndex(),t.SetZIndicesChanged()}}async AddJobWorkerScripts(e){const t=await Promise.all(e.map((async e=>{if(this.IsCordova()&&this._assetManager.IsFileProtocol()||"playable-ad-single-file"===this.GetExportType()){const t=await this._assetManager.FetchBlob(e);return URL.createObjectURL(t)}return new URL(e,location.href).toString()})));this._jobScheduler.ImportScriptsToJobWorkers(t)}AddJobWorkerBlob(e,t){this._jobScheduler.SendBlobToJobWorkers(e,t)}AddJobWorkerBuffer(e,t){this._jobScheduler.SendBufferToJobWorkers(e,t)}AddJob(e,t,s,i){return this._jobScheduler.AddJob(e,t,s,null,null,i)}BroadcastJob(e,t,s,i){return this._jobScheduler.BroadcastJob(e,t,s,i)}GetMaxNumJobWorkers(){return this._jobScheduler.GetMaxNumWorkers()}InvokeDownload(e,t){this.PostComponentMessageToDOM("runtime","invoke-download",{"url":e,"filename":t})}async RasterSvgImage(e,t,s,i,n,a){if(i=i||t,n=n||s,this.IsInWorker()){return(await this.PostComponentMessageToDOMAsync("runtime","raster-svg-image",{"blob":e,"imageWidth":t,"imageHeight":s,"surfaceWidth":i,"surfaceHeight":n,"imageBitmapOpts":a}))["imageBitmap"]}{const r=await self["C3_RasterSvgImageBlob"](e,t,s,i,n);return a?await self.createImageBitmap(r,a):r}}async GetSvgImageSize(e){return this.IsInWorker()?await this.PostComponentMessageToDOMAsync("runtime","get-svg-image-size",{"blob":e}):await self["C3_GetSvgImageSize"](e)}RequestDeviceOrientationEvent(){this._didRequestDeviceOrientationEvent||(this._didRequestDeviceOrientationEvent=!0,this.PostComponentMessageToDOM("runtime","enable-device-orientation"))}RequestDeviceMotionEvent(){this._didRequestDeviceMotionEvent||(this._didRequestDeviceMotionEvent=!0,this.PostComponentMessageToDOM("runtime","enable-device-motion"))}Random(){return this._randomNumberCallback()}SetRandomNumberGeneratorCallback(e){this._randomNumberCallback=e}_GetRemotePreviewStatusInfo(){const e=this.GetRenderer();return{"fps":this.GetFramesPerSecond(),"tps":this.GetTicksPerSecond(),"cpu":this.GetMainThreadTime(),"gpu":this.GetGPUUtilisation(),"layout":this.GetMainRunningLayout()?this.GetMainRunningLayout().GetName():"","renderer":e.IsWebGL()?e.GetUnmaskedRenderer():e.GetAdapterInfoString()}}HitBreakpoint(){return!!this.IsDebug()&&C3Debugger.HitBreakpoint()}DebugBreak(e){return this.IsDebugging()?C3Debugger.DebugBreak(e):Promise.resolve()}DebugBreakNext(){return!!this.IsDebugging()&&C3Debugger.BreakNext()}SetDebugBreakpointsEnabled(e){this._breakpointsEnabled=!!e,this._UpdateDebuggingFlag()}AreDebugBreakpointsEnabled(){return this._breakpointsEnabled}IsDebugging(){return this._isDebugging}SetDebuggingEnabled(e){e?this._debuggingDisabled--:this._debuggingDisabled++,this._UpdateDebuggingFlag()}_UpdateDebuggingFlag(){this._isDebugging=this.IsDebug()&&this._breakpointsEnabled&&0===this._debuggingDisabled}IsCPUProfiling(){return this.IsDebug()&&C3Debugger.IsCPUProfiling()}IsGPUProfiling(){return this.IsDebug()&&this.GetRenderer().SupportsGPUProfiling()&&C3Debugger.IsGPUProfiling()}async DebugIterateAndBreak(e){if(e)for(const t of e)await this.DebugBreak(t)}DebugFireGeneratorEventAndBreak(e){return this.DebugIterateAndBreak(this._dispatcher.dispatchGeneratorEvent(e))}_InvokeFunctionFromJS(e){return this._eventSheetManager._InvokeFunctionFromJS(e["name"],e["params"])}_GetHTMLLayerWrapElement(e){if(this.IsInWorker())throw new Error("not supported in worker mode");return self["c3_runtimeInterface"]["_GetHTMLWrapElement"](e)}GetIRuntime(){return this._iRuntime}_CreateUserScriptEvent(e){const t=C3.New(C3.Event,e,!1);return t.runtime=this._iRuntime,t}_InitScriptInterfaces(){this._iRuntime=new self.IRuntime(this),this._userScriptEventObjects={"pretick":this._CreateUserScriptEvent("pretick"),"tick":this._CreateUserScriptEvent("tick"),"tick2":this._CreateUserScriptEvent("tick2")}}_InitObjectsScriptInterface(){const e={};for(const t of this._allObjectClasses)e[t.GetJsPropName()]={value:t.GetIObjectClass(),enumerable:!0,writable:!1};this._iRuntime._InitObjects(e)}_InitGlobalVariableScriptInterface(){const e={};for(const t of this.GetEventSheetManager().GetAllGlobalVariables())e[t.GetJsPropName()]=t._GetScriptInterfaceDescriptor();this._iRuntime._InitGlobalVars(e)}_GetCommonScriptInterfaces(){return this._commonScriptInterfaces}_MapScriptInterface(e,t){this._interfaceMap.set(e,t)}_UnwrapScriptInterface(e){return this._interfaceMap.get(e)}_UnwrapIObjectClass(e){if(!(e instanceof self.IObjectClass))throw new TypeError("expected IObjectClass");const t=this._UnwrapScriptInterface(e);if(!(t&&t instanceof C3.ObjectClass))throw new Error("invalid IObjectClass");return t}_UnwrapIInstance(e){if(!(e instanceof self.IInstance))throw new TypeError("expected IInstance");const t=this._UnwrapScriptInterface(e);if(!(t&&t instanceof C3.Instance))throw new Error("invalid IInstance");return t}_UnwrapIWorldInstance(e){if(!(e instanceof self.IWorldInstance))throw new TypeError("expected IWorldInstance");const t=this._UnwrapScriptInterface(e);if(!(t&&t instanceof C3.Instance))throw new Error("invalid IInstance");return t}},self["C3_CreateRuntime"]=C3.Runtime.Create,self["C3_InitRuntime"]=(e,t)=>e.Init(t);
}

// workers/jobSchedulerRuntime.js
{
const C3=self.C3;C3.JobSchedulerRuntime=class extends C3.DefendedBase{constructor(r,e){super(),this._runtime=r,this._jobPromises=new Map,this._nextJobId=0,this._inputPort=e["inputPort"],e["outputPort"].onmessage=r=>this._OnJobWorkerMessage(r),this._maxNumWorkers=e["maxNumWorkers"],this._jobWorkerCount=1,this._isCreatingWorker=!1,this._hadErrorCreatingWorker=!1}GetMaxNumWorkers(){return this._maxNumWorkers}ImportScriptsToJobWorkers(r){this._inputPort.postMessage({"type":"_import_scripts","scripts":r})}SendBlobToJobWorkers(r,e){this._inputPort.postMessage({"type":"_send_blob","blob":r,"id":e})}SendBufferToJobWorkers(r,e){this._inputPort.postMessage({"type":"_send_buffer","buffer":r,"id":e},[r])}AddJob(r,e,o,s,t,i){if(o||(o=[]),"number"==typeof i&&(i=Math.floor(i))<=0)throw new Error("invalid maxWorkerNum");const n=this._nextJobId++,a={"type":r,"isBroadcast":!1,"maxWorkerNum":i,"jobId":n,"params":e,"transferables":o},_=new Promise(((r,e)=>{this._jobPromises.set(n,{resolve:r,progress:s,reject:e,cancelled:!1,maxWorkerNum:i})}));return t&&t.SetAction((()=>this._CancelJob(n))),this._inputPort.postMessage(a,o),this._MaybeCreateExtraWorker(),_}BroadcastJob(r,e,o,s){if(o||(o=[]),"number"==typeof s&&(s=Math.floor(s))<=0)throw new Error("invalid maxWorkerNum");const t={"type":r,"isBroadcast":!0,"maxWorkerNum":s,"jobId":this._nextJobId++,"params":e,"transferables":o};this._inputPort.postMessage(t,o)}_CancelJob(r){const e=this._jobPromises.get(r);e&&(e.cancelled=!0,e.resolve=null,e.progress=null,e.reject=null,this._inputPort.postMessage({"type":"_cancel","jobId":r}))}_OnJobWorkerMessage(r){const e=r.data,o=e["type"],s=e["jobId"];switch(o){case"result":this._OnJobResult(s,e["result"]);break;case"progress":this._OnJobProgress(s,e["progress"]);break;case"error":this._OnJobError(s,e["error"]);break;case"ready":this._OnJobWorkerReady();break;default:throw new Error(`unknown message from worker '${o}'`)}}_OnJobResult(r,e){const o=this._jobPromises.get(r);if(!o)throw new Error("invalid job ID");o.cancelled||o.resolve(e),this._jobPromises.delete(r)}_OnJobProgress(r,e){const o=this._jobPromises.get(r);if(!o)throw new Error("invalid job ID");!o.cancelled&&o.progress&&o.progress(e)}_OnJobError(r,e){const o=this._jobPromises.get(r);if(!o)throw new Error("invalid job ID");o.cancelled||o.reject(e),this._jobPromises.delete(r)}_OnJobWorkerReady(){this._isCreatingWorker&&(this._isCreatingWorker=!1,this._jobWorkerCount++,this._jobWorkerCount<this._maxNumWorkers?this._MaybeCreateExtraWorker():this._inputPort.postMessage({"type":"_no_more_workers"}))}_GetWorkerCountNeededForPendingJobs(){let r=0;const e=[...this._jobPromises.values()].sort(((r,e)=>(r.maxWorkerNum||1/0)-(e.maxWorkerNum||1/0)));for(const o of e){r<(o.maxWorkerNum||1/0)&&r++}return r}async _MaybeCreateExtraWorker(){if(!(this._jobWorkerCount>=this._maxNumWorkers||this._isCreatingWorker||this._hadErrorCreatingWorker||this._GetWorkerCountNeededForPendingJobs()<=this._jobWorkerCount))try{this._isCreatingWorker=!0;(await this._runtime.PostComponentMessageToDOMAsync("runtime","create-job-worker"))["outputPort"].onmessage=r=>this._OnJobWorkerMessage(r)}catch(r){this._hadErrorCreatingWorker=!0,this._isCreatingWorker=!1,console.error(`[Construct] Failed to create job worker; stopping creating any more (created ${this._jobWorkerCount} so far)`,r)}}};
}

// scripts/shaders.js
{
self["C3_Shaders"] = {};

}

// scripts/plugins/system/c3runtime/runtime.js
{
{const e=self.C3;let t=null,n="",r="",a=[],i="",s="",o="";const u=e.New(e.ArrayStack);function ForEachOrdered_SortInstances(e,t){const n=e[1],r=t[1];if("number"==typeof n&&"number"==typeof r)return n-r;{const e=""+n,t=""+r;return e<t?-1:e>t?1:0}}e.Plugins.System=class extends e.SDKPluginBase{constructor(e){super(e),this._loopStack=this._runtime.GetEventSheetManager().GetLoopStack(),this._eventStack=this._runtime.GetEventSheetManager().GetEventStack(),this._imagesLoadingTotal=0,this._imagesLoadingComplete=0,this._functionMaps=new Map}Release(){super.Release()}UpdateRender(){this._runtime.UpdateRender()}Trigger(e){this._runtime.Trigger(e,null,null)}GetRegex(e,a){return t&&e===n&&a===r||(t=new RegExp(e,a),n=e,r=a),t.lastIndex=0,t}GetRegexMatches(e,t,n){if(e===i&&t===s&&n===o)return a;const r=this.GetRegex(t,n);return a=e.match(r),i=e,s=t,o=n,a}async _LoadTexturesForObjectClasses(t,n){if(!n.length)return;this._imagesLoadingTotal+=n.length;const r=[];for(const e of n)r.push(t.MaybeLoadTexturesFor(e));await e.PromiseAllWithProgress(r,(()=>{this._imagesLoadingComplete++})),this._imagesLoadingComplete++,this._imagesLoadingComplete===this._imagesLoadingTotal&&(this._imagesLoadingComplete=0,this._imagesLoadingTotal=0,this._runtime.Trigger(e.Plugins.System.Cnds.OnImageLoadingComplete,null,null))}GetImageLoadingProgress(){return 0===this._imagesLoadingTotal?1:this._imagesLoadingComplete/this._imagesLoadingTotal}_UnloadTexturesForObjectClasses(e,t){for(const n of t)0===n.GetInstanceCount()&&e.MaybeUnloadTexturesFor(n)}_GetForEachStack(){return u}_Repeat(e){const t=this._runtime.GetEventSheetManager(),n=t.GetEventStack(),r=n.GetCurrentStackFrame(),a=r.GetCurrentEvent(),i=a.GetSolModifiers(),s=r.IsSolModifierAfterCnds(),o=n.Push(a),u=t.GetLoopStack(),l=u.Push();if(l.SetEnd(e),s)for(let n=0;n<e&&!l.IsStopped();++n)t.PushCopySol(i),l.SetIndex(n),a.Retrigger(r,o),t.PopSol(i);else for(let t=0;t<e&&!l.IsStopped();++t)l.SetIndex(t),a.Retrigger(r,o);return n.Pop(),u.Pop(),!1}*_DebugRepeat(e){const t=this._runtime.GetEventSheetManager(),n=t.GetEventStack(),r=n.GetCurrentStackFrame(),a=r.GetCurrentEvent(),i=a.GetSolModifiers(),s=r.IsSolModifierAfterCnds(),o=n.Push(a),u=t.GetLoopStack(),l=u.Push();if(l.SetEnd(e),s)for(let n=0;n<e&&!l.IsStopped();++n)t.PushCopySol(i),l.SetIndex(n),yield*a.DebugRetrigger(r,o),t.PopSol(i);else for(let t=0;t<e&&!l.IsStopped();++t)l.SetIndex(t),yield*a.DebugRetrigger(r,o);return n.Pop(),u.Pop(),!1}_While(){const e=this._runtime.GetEventSheetManager(),t=e.GetEventStack(),n=t.GetCurrentStackFrame(),r=n.GetCurrentEvent(),a=r.GetSolModifiers(),i=n.IsSolModifierAfterCnds(),s=t.Push(r),o=e.GetLoopStack(),u=o.Push();if(i)for(let t=0;!u.IsStopped();++t)e.PushCopySol(a),u.SetIndex(t),r.Retrigger(n,s)||u.Stop(),e.PopSol(a);else for(let e=0;!u.IsStopped();++e)u.SetIndex(e),r.Retrigger(n,s)||u.Stop();return t.Pop(),o.Pop(),!1}*_DebugWhile(){const e=this._runtime.GetEventSheetManager(),t=e.GetEventStack(),n=t.GetCurrentStackFrame(),r=n.GetCurrentEvent(),a=r.GetSolModifiers(),i=n.IsSolModifierAfterCnds(),s=t.Push(r),o=e.GetLoopStack(),u=o.Push();if(i)for(let t=0;!u.IsStopped();++t){e.PushCopySol(a),u.SetIndex(t);(yield*r.DebugRetrigger(n,s))||u.Stop(),e.PopSol(a)}else for(let e=0;!u.IsStopped();++e){u.SetIndex(e);(yield*r.DebugRetrigger(n,s))||u.Stop()}return t.Pop(),o.Pop(),!1}_For(e,t,n){const r=this._runtime.GetEventSheetManager(),a=r.GetEventStack(),i=a.GetCurrentStackFrame(),s=i.GetCurrentEvent(),o=s.GetSolModifiers(),u=i.IsSolModifierAfterCnds(),l=a.Push(s),c=r.GetLoopStack(),h=c.Push();if(h.SetName(e),h.SetEnd(n),n<t)if(u)for(let e=t;e>=n&&!h.IsStopped();--e)r.PushCopySol(o),h.SetIndex(e),s.Retrigger(i,l),r.PopSol(o);else for(let e=t;e>=n&&!h.IsStopped();--e)h.SetIndex(e),s.Retrigger(i,l);else if(u)for(let e=t;e<=n&&!h.IsStopped();++e)r.PushCopySol(o),h.SetIndex(e),s.Retrigger(i,l),r.PopSol(o);else for(let e=t;e<=n&&!h.IsStopped();++e)h.SetIndex(e),s.Retrigger(i,l);return a.Pop(),c.Pop(),!1}*_DebugFor(e,t,n){const r=this._runtime.GetEventSheetManager(),a=r.GetEventStack(),i=a.GetCurrentStackFrame(),s=i.GetCurrentEvent(),o=s.GetSolModifiers(),u=i.IsSolModifierAfterCnds(),l=a.Push(s),c=r.GetLoopStack(),h=c.Push();if(h.SetName(e),h.SetEnd(n),n<t)if(u)for(let e=t;e>=n&&!h.IsStopped();--e)r.PushCopySol(o),h.SetIndex(e),yield*s.DebugRetrigger(i,l),r.PopSol(o);else for(let e=t;e>=n&&!h.IsStopped();--e)h.SetIndex(e),yield*s.DebugRetrigger(i,l);else if(u)for(let e=t;e<=n&&!h.IsStopped();++e)r.PushCopySol(o),h.SetIndex(e),yield*s.DebugRetrigger(i,l),r.PopSol(o);else for(let e=t;e<=n&&!h.IsStopped();++e)h.SetIndex(e),yield*s.DebugRetrigger(i,l);return a.Pop(),c.Pop(),!1}_ForEach(t){const n=t.GetCurrentSol(),r=n.GetInstances();if(0===r.length)return!1;const a=this._runtime.GetEventSheetManager(),i=a.GetEventStack(),s=i.GetCurrentStackFrame(),o=s.GetCurrentEvent(),l=o.GetSolModifiers(),c=s.IsSolModifierAfterCnds(),h=i.Push(o),g=a.GetLoopStack(),S=g.Push(),d=t.IsInContainer(),p=u.Push();if(e.shallowAssignArray(p,r),S.SetEnd(p.length),c)for(let e=0,n=p.length;e<n&&!S.IsStopped();++e){a.PushCopySol(l);const n=p[e];t.GetCurrentSol().SetSinglePicked(n),d&&n.SetSiblingsSinglePicked(),S.SetIndex(e),o.Retrigger(s,h),a.PopSol(l)}else{n._SetSelectAll(!1);const t=n._GetOwnInstances();e.clearArray(t),t.push(null);for(let e=0,n=p.length;e<n&&!S.IsStopped();++e){const n=p[e];t[0]=n,d&&n.SetSiblingsSinglePicked(),S.SetIndex(e),o.Retrigger(s,h)}}return i.Pop(),g.Pop(),e.clearArray(p),u.Pop(),!1}*_DebugForEach(t){const n=t.GetCurrentSol(),r=n.GetInstances();if(0===r.length)return!1;const a=this._runtime.GetEventSheetManager(),i=a.GetEventStack(),s=i.GetCurrentStackFrame(),o=s.GetCurrentEvent(),l=o.GetSolModifiers(),c=s.IsSolModifierAfterCnds(),h=i.Push(o),g=a.GetLoopStack(),S=g.Push(),d=t.IsInContainer(),p=u.Push();if(e.shallowAssignArray(p,r),S.SetEnd(p.length),c)for(let e=0,n=p.length;e<n&&!S.IsStopped();++e){a.PushCopySol(l);const n=p[e];t.GetCurrentSol().SetSinglePicked(n),d&&n.SetSiblingsSinglePicked(),S.SetIndex(e),yield*o.DebugRetrigger(s,h),a.PopSol(l)}else{n._SetSelectAll(!1);const t=n._GetOwnInstances();e.clearArray(t),t.push(null);for(let e=0,n=p.length;e<n&&!S.IsStopped();++e){const n=p[e];t[0]=n,d&&n.SetSiblingsSinglePicked(),S.SetIndex(e),yield*o.DebugRetrigger(s,h)}}return i.Pop(),g.Pop(),e.clearArray(p),u.Pop(),!1}_ForEachOrdered(t,n){const r=t.GetCurrentSol(),a=r.GetInstances();if(0===a.length)return!1;const i=this._runtime.GetEventSheetManager(),s=i.GetEventStack(),o=i.GetCurrentCondition(),l=s.GetCurrentStackFrame(),c=l.GetCurrentEvent(),h=c.GetSolModifiers(),g=l.IsSolModifierAfterCnds(),S=s.Push(c),d=i.GetLoopStack(),p=d.Push(),m=t.IsInContainer(),G=u.Push();e.clearArray(G),p.SetEnd(a.length);for(let e=0,t=a.length;e<t;++e)G.push([a[e],o.ReevaluateParameter(1,e)]);if(G.sort(ForEachOrdered_SortInstances),1===n&&G.reverse(),g)for(let e=0,n=G.length;e<n&&!p.IsStopped();++e){i.PushCopySol(h);const n=G[e][0];t.GetCurrentSol().SetSinglePicked(n),m&&n.SetSiblingsSinglePicked(),p.SetIndex(e),c.Retrigger(l,S),i.PopSol(h)}else{r._SetSelectAll(!1);const t=r._GetOwnInstances();e.clearArray(t),t.push(null);for(let e=0,n=G.length;e<n&&!p.IsStopped();++e){const n=G[e][0];t[0]=n,m&&n.SetSiblingsSinglePicked(),p.SetIndex(e),c.Retrigger(l,S)}}return s.Pop(),d.Pop(),e.clearArray(G),u.Pop(),!1}*_DebugForEachOrdered(t,n){const r=t.GetCurrentSol(),a=r.GetInstances();if(0===a.length)return!1;const i=this._runtime.GetEventSheetManager(),s=i.GetEventStack(),o=i.GetCurrentCondition(),l=s.GetCurrentStackFrame(),c=l.GetCurrentEvent(),h=c.GetSolModifiers(),g=l.IsSolModifierAfterCnds(),S=s.Push(c),d=i.GetLoopStack(),p=d.Push(),m=t.IsInContainer(),G=u.Push();e.clearArray(G),p.SetEnd(a.length);for(let e=0,t=a.length;e<t;++e)G.push([a[e],o.ReevaluateParameter(1,e)]);if(G.sort(ForEachOrdered_SortInstances),1===n&&G.reverse(),g)for(let e=0,n=G.length;e<n&&!p.IsStopped();++e){i.PushCopySol(h);const n=G[e][0];t.GetCurrentSol().SetSinglePicked(n),m&&n.SetSiblingsSinglePicked(),p.SetIndex(e),yield*c.DebugRetrigger(l,S),i.PopSol(h)}else{r._SetSelectAll(!1);const t=r._GetOwnInstances();e.clearArray(t),t.push(null);for(let e=0,n=G.length;e<n&&!p.IsStopped();++e){const n=G[e][0];t[0]=n,m&&n.SetSiblingsSinglePicked(),p.SetIndex(e),yield*c.DebugRetrigger(l,S)}}return s.Pop(),d.Pop(),e.clearArray(G),u.Pop(),!1}_GetFunctionMap(e,t){let n=this._functionMaps.get(e);return n||(t?(n={defaultFunc:null,strMap:new Map},this._functionMaps.set(e,n),n):null)}_DoCallMappedFunction(e,t,n,r,a){t.GetEventBlock().RunAsMappedFunctionCall(n,t.IsCopyPicked()),r&&e.PopSol(a)}*_DebugDoCallMappedFunction(e,t,n,r,a){yield*t.GetEventBlock().DebugRunAsMappedFunctionCall(n,t.IsCopyPicked()),r&&e.PopSol(a)}}}{const l=self.C3;l.Plugins.System.Type=class extends l.DefendedBase{constructor(e){super(),this._objectClass=e,this._runtime=e.GetRuntime(),this._plugin=e.GetPlugin()}OnCreate(){}Release(){this._objectClass=null,this._runtime=null,this._plugin=null}}}{const c=self.C3;c.Plugins.System.Instance=class extends c.DefendedBase{constructor(e,t){super(),this._inst=e,this._objectClass=this._inst.GetObjectClass(),this._sdkType=this._objectClass.GetSdkType(),this._runtime=this._inst.GetRuntime()}Release(){this._inst=null,this._objectClass=null,this._sdkType=null,this._runtime=null}}}{const h=self.C3,g=[];h.Plugins.System.Cnds={EveryTick:()=>!0,OnLayoutStart:()=>!0,OnLayoutEnd:()=>!0,OnSuspend:()=>!0,OnResume:()=>!0,IsSuspended(){return this._runtime.IsSuspended()},Else(){const e=this._runtime.GetCurrentEventStackFrame();return!e.GetElseBranchRan()&&!e.GetLastEventTrue()},TriggerOnce(){const e=this._runtime.GetCurrentCondition().GetSavedDataMap();let t=e.get("TriggerOnce_lastTick");void 0===t&&(t=-1,e.set("TriggerOnce_lastTick",-1));const n=this._runtime.GetTickCount();return e.set("TriggerOnce_lastTick",n),this._runtime.IsLayoutFirstTick()||t!==n-1},Every(e){const t=this._runtime.GetCurrentCondition().GetSavedDataMap(),n=t.get("Every_lastTime")||0,r=this._runtime.GetGameTime();t.has("Every_seconds")||t.set("Every_seconds",e);const a=t.get("Every_seconds");return r>=n+a?(t.set("Every_lastTime",n+a),r>=t.get("Every_lastTime")+.04&&t.set("Every_lastTime",r),t.set("Every_seconds",e),!0):(r<n-.1&&t.set("Every_lastTime",r),!1)},IsGroupActive(e){const t=this._runtime.GetEventSheetManager().GetEventGroupByName(e);return t&&t.IsGroupActive()},IsPreview(){return this._runtime.IsPreview()},IsMobile:()=>h.Platform.IsMobile,OnLoadFinished:()=>!0,OnCanvasSnapshot:()=>!0,EffectsSupported:()=>!0,OnSaveComplete:()=>!0,OnSaveFailed:()=>!0,OnLoadComplete:()=>!0,OnLoadFailed:()=>!0,ObjectUIDExists(e){return!!this._runtime.GetInstanceByUID(e)},IsOnPlatform(e){switch(e){case 0:return"browser"===h.Platform.Context;case 1:return"iOS"===h.Platform.OS;case 2:return"Android"===h.Platform.OS;case 8:return"cordova"===h.Platform.Context;case 9:return"scirra-arcade"===this._runtime.GetExportType();case 10:return"nwjs"===h.Platform.Context;case 13:return"windows-uwp"===this._runtime.GetExportType();default:return!1}},RegexTest(e,t,n){return this.GetRegex(t,n).test(e)},Compare:(e,t,n)=>h.compare(e,t,n),CompareBetween:(e,t,n)=>e>=t&&e<=n,CompareVar:(e,t,n)=>h.compare(e.GetValue(),t,n),CompareBoolVar:e=>!!e.GetValue(),CompareTime(e,t){const n=this._runtime.GetGameTime();if(0===e){const e=this._runtime.GetCurrentCondition().GetSavedDataMap();return!e.get("CompareTime_executed")&&n>=t&&(e.set("CompareTime_executed",!0),!0)}return h.compare(n,e,t)},IsNaN:e=>isNaN(e),AngleWithin:(e,t,n)=>h.angleDiff(h.toRadians(e),h.toRadians(n))<=h.toRadians(t),IsClockwiseFrom:(e,t)=>h.angleClockwise(h.toRadians(e),h.toRadians(t)),IsBetweenAngles(e,t,n){let r=h.toRadians(e),a=h.toRadians(t),i=h.toRadians(n);return!h.angleClockwise(i,a)?!(!h.angleClockwise(r,a)&&h.angleClockwise(r,i)):h.angleClockwise(r,a)&&!h.angleClockwise(r,i)},IsValueType:(e,t)=>"number"==typeof e?0===t:1===t,EvaluateExpression:e=>!!e,OnSignal(e){return e.toLowerCase()===this._runtime.GetEventSheetManager().GetCurrentSignalTag()},PickByComparison(e,t,n,r){if(!e)return!1;const a=this._GetForEachStack(),i=a.Push(),s=e.GetCurrentSol();h.shallowAssignArray(i,s.GetInstances()),s.IsSelectAll()&&h.clearArray(s._GetOwnElseInstances());const o=this._runtime.GetCurrentCondition();let u=0;for(let e=0,a=i.length;e<a;++e){const a=i[e];i[u]=a,t=o.ReevaluateParameter(1,e),r=o.ReevaluateParameter(3,e),h.compare(t,n,r)?++u:s._PushElseInstance(a)}h.truncateArray(i,u),s.SetArrayPicked(i);const l=!!i.length;return h.clearArray(i),a.Pop(),e.ApplySolToContainer(),l},PickByEvaluate(e,t){if(!e)return!1;const n=this._GetForEachStack(),r=n.Push(),a=e.GetCurrentSol();h.shallowAssignArray(r,a.GetInstances()),a.IsSelectAll()&&h.clearArray(a._GetOwnElseInstances());const i=this._runtime.GetCurrentCondition();let s=0;for(let e=0,t=r.length;e<t;++e){const t=r[e];r[s]=t,i.ReevaluateParameter(1,e)?++s:a._PushElseInstance(t)}h.truncateArray(r,s),a.SetArrayPicked(r);const o=!!r.length;return h.clearArray(r),n.Pop(),e.ApplySolToContainer(),o},PickByHighestLowestValue(e,t,n){if(!e)return!1;const r=e.GetCurrentSol(),a=r.GetInstances();if(0===a.length)return!1;const i=this._runtime.GetCurrentCondition();let s=null,o=0;for(let e=0,r=a.length;e<r;++e){const r=a[e];n=i.ReevaluateParameter(2,e),(null===s||0===t&&n<o||1===t&&n>o)&&(o=n,s=r)}return r.PickOne(s),e.ApplySolToContainer(),!0},PickNth(e,t){if(!e)return!1;const n=e.GetCurrentSol(),r=n.GetInstances();if((t=Math.floor(t))>=r.length)return!1;const a=r[t];return n.PickOne(a),e.ApplySolToContainer(),!0},PickRandom(e){if(!e)return!1;const t=e.GetCurrentSol(),n=t.GetInstances(),r=Math.floor(this._runtime.Random()*n.length);if(r>=n.length)return!1;const a=n[r];return t.PickOne(a),e.ApplySolToContainer(),!0},PickAll(e){if(!e)return!1;if(!e.GetInstanceCount())return!1;return e.GetCurrentSol()._SetSelectAll(!0),e.ApplySolToContainer(),!0},PickOverlappingPoint(e,t,n){if(!e)return!1;const r=e.GetCurrentSol(),a=r.GetInstances(),i=this._runtime.GetCurrentEvent().IsOrBlock(),s=this._runtime.GetCurrentCondition().IsInverted();r.IsSelectAll()?(h.shallowAssignArray(g,a),r.ClearArrays(),r._SetSelectAll(!1)):i?(h.shallowAssignArray(g,r._GetOwnElseInstances()),h.clearArray(r._GetOwnElseInstances())):(h.shallowAssignArray(g,r._GetOwnInstances()),h.clearArray(r._GetOwnInstances()));for(let e=0,a=g.length;e<a;++e){const a=g[e];h.xor(a.GetWorldInfo().ContainsPoint(t,n),s)?r._PushInstance(a):r._PushElseInstance(a)}return e.ApplySolToContainer(),h.xor(!!r._GetOwnInstances().length,s)},PickLastCreated(e){if(!e)return!1;const t=e.IsFamily();let n=null;const r=this._runtime._GetInstancesPendingCreate();for(let a=r.length-1;a>=0;--a){const i=r[a];if(t){if(i.GetObjectClass().BelongsToFamily(e)){n=i;break}}else if(i.GetObjectClass()===e){n=i;break}}if(!n){const t=e.GetInstances();t.length&&(n=t.at(-1))}if(!n)return!1;return e.GetCurrentSol().PickOne(n),e.ApplySolToContainer(),!0},Repeat(e){return this._runtime.IsDebugging()?this._DebugRepeat(e):this._Repeat(e)},While(){return this._runtime.IsDebugging()?this._DebugWhile():this._While()},For(e,t,n){return this._runtime.IsDebugging()?this._DebugFor(e,t,n):this._For(e,t,n)},ForEach(e){return this._runtime.IsDebugging()?this._DebugForEach(e):this._ForEach(e)},ForEachOrdered(e,t,n){return this._runtime.IsDebugging()?this._DebugForEachOrdered(e,n):this._ForEachOrdered(e,n)},LayerVisible:e=>!!e&&e.IsVisible(),LayerInteractive:e=>!!e&&e.IsSelfAndParentsInteractive(),LayerIsHTML:e=>!!e&&e.IsHTMLElementsLayer(),LayerEmpty:e=>!!e&&!e.GetInstanceCount(),LayerCmpOpacity:(e,t,n)=>!!e&&h.compare(100*e.GetOpacity(),t,n),LayerNameExists(e){const t=this._runtime.GetMainRunningLayout();return!!t&&t.HasLayerByName(e)},OnImageLoadingComplete:()=>!0,IsLoadingImages(){return this._imagesLoadingTotal>0},TemplateExists(e,t){const n=this._runtime.GetTemplateManager();return!!n&&(!!t&&!!n.GetTemplateData(e,t))}}}{const S=self.C3;function SortZOrderList(e,t){const n=e[0]-t[0];if(0!==n)return n;return e[1]-t[1]}function SortInstancesByValue(e,t){return e[1]-t[1]}const d=[],p=[],m=S.New(S.Rect),G=S.New(S.Color),y=[];S.Plugins.System.Acts={SetVar(e,t){e.SetValue(t)},AddVar(e,t){e.IsNumber()&&"number"!=typeof t&&(t=parseFloat(t)),e.SetValue(e.GetValue()+t)},SubVar(e,t){e.IsNumber()&&e.SetValue(e.GetValue()-t)},SetBoolVar(e,t){e.SetValue(!!t)},ToggleBoolVar(e){e.SetValue(!e.GetValue())},ResetEventVar(e){e.SetValue(e.GetInitialValue())},ResetGlobals(e){this._runtime.GetEventSheetManager().ResetAllGlobalsToInitialValue(e)},CreateObject(e,t,n,r,a,i){if(!e||!t)return;const s=this._runtime.CreateInstance(e,t,n,r,a,i);if(!s)return;a&&t.SortAndAddInstancesByZIndex(s);const o=this._runtime.GetEventSheetManager();o.BlockFlushingInstances(!0),s._TriggerOnCreatedOnSelfAndRelated(),o.BlockFlushingInstances(!1);const u=new Map;s.CollectInstancesToPick(u,e,a);for(const[e,t]of u)e.GetCurrentSol().SetSetPicked(t)},CreateObjectByName(e,t,n,r,a,i){if(!e||!t)return;const s=this._runtime.GetObjectClassByName(e);s&&S.Plugins.System.Acts.CreateObject.call(this,s,t,n,r,a,i)},RecreateInitialObjects(e,t,n,r,a,i,s,o,u,l,c){if(!e)return;const h=this._runtime.GetCurrentLayout();let g=h;if(i){const e=this._runtime.GetLayoutManager().GetLayoutByName(i);if(!e)return;g=e}let S=null;if(("number"!=typeof s||s>=0)&&(S=g.GetLayer(s),!S))return;let d=null;if(("number"!=typeof o||o>=0)&&(d=h.GetLayer(o),!d))return;m.set(t,n,r,a);const p=g.RecreateInitialObjects(e,m,S,d,u,l,c);e.GetCurrentSol().SetArrayPicked(p),e.ApplySolToContainer()},StopLoop(){const e=this._loopStack;e.IsInLoop()&&e.GetCurrent().Stop()},SetGroupActive(e,t){const n=this._runtime.GetEventSheetManager().GetEventGroupByName(e);n&&(0===t?n.SetGroupActive(!1):1===t?n.SetGroupActive(!0):n.SetGroupActive(!n.IsGroupActive()))},SetTimescale(e){this._runtime.SetTimeScale(e)},SetObjectTimescale(e,t){if(t<0&&(t=0),!e)return;const n=e.GetCurrentSol().GetInstances();for(const e of n)e.SetTimeScale(t)},RestoreObjectTimescale(e){if(!e)return;const t=e.GetCurrentSol().GetInstances();for(const e of t)e.RestoreTimeScale()},Wait(e,t){if(e<0)return;const n=this._runtime.GetEventSheetManager().AddScheduledWait();return t?n.InitTimer(e):n.InitWallTimer(e),!0},WaitForSignal(e){return this._runtime.GetEventSheetManager().AddScheduledWait().InitSignal(e),!0},WaitForPreviousActions(){const e=this._runtime.GetEventSheetManager();return e.AddScheduledWait().InitPromise(e.GetPromiseForAllAsyncActions()),!0},Signal(e){this._runtime.GetEventSheetManager().Signal(e)},async SnapshotCanvas(e,t,n,r,a,i){const s=this._runtime.GetCanvasManager();s&&(this.UpdateRender(),await s.SnapshotCanvas(0===e?"image/png":"image/jpeg",t/100,n,r,a,i),await this._runtime.TriggerAsync(S.Plugins.System.Cnds.OnCanvasSnapshot,null))},SetCanvasSize(e,t){if(e<=0||t<=0)return;this._runtime.SetViewportSize(e,t),this._runtime.GetCurrentLayout().BoundScrolling();const n=this._runtime.GetCanvasManager();n&&("off"===n.GetCurrentFullscreenMode()||this._runtime.SetOriginalViewportSize(e,t),n.SetSize(n.GetLastWidth(),n.GetLastHeight(),!0),this._runtime.UpdateRender())},SetFullscreenQuality(e){const t=this._runtime.GetCanvasManager();t&&"off"!==t.GetCurrentFullscreenMode()&&(t.SetFullscreenScalingQuality(0!==e?"high":"low"),t.SetSize(t.GetLastWidth(),t.GetLastHeight(),!0))},SaveState(e){this._runtime.SaveToSlot(e)},SaveStateJSON(){this._runtime.SaveToJsonString()},LoadState(e){this._runtime.LoadFromSlot(e)},LoadStateJSON(e){this._runtime.LoadFromJsonString(e)},SetHalfFramerateMode(e){},ResetPersisted(){for(const e of this._runtime.GetLayoutManager().GetAllLayouts())e.ResetPersistData()},SetPixelRounding(e){this._runtime.SetPixelRoundingEnabled(0!==e)},SetFramerateMinMax(e,t){this._runtime.SetMaxDt(1/e),this._runtime.SetMinDt(1/t)},SetDeltaTimeMinMax(e,t){this._runtime.SetMinDt(e),this._runtime.SetMaxDt(t)},SetFramerateMode(e){this._runtime._SetFramerateMode(["vsync","unlimited-tick","unlimited-frame"][e])},SortZOrderByInstVar(e,t){if(!e)return;const n=e.GetCurrentSol().GetInstances(),r=d,a=p,i=this._runtime.GetCurrentLayout(),s=e.IsFamily(),o=e.GetFamilyIndex();for(let e=0,i=n.length;e<i;++e){const i=n[e],u=i.GetWorldInfo();if(!u)continue;let l;l=s?i.GetInstanceVariableValue(t+i.GetObjectClass().GetFamilyInstanceVariableOffset(o)):i.GetInstanceVariableValue(t),r.push([u.GetLayer().GetIndex(),u.GetZIndex()]),a.push([i,l])}if(!r.length)return;r.sort(SortZOrderList),a.sort(SortInstancesByValue);let u=!1;for(let e=0,t=r.length;e<t;++e){const t=a[e][0],n=i.GetLayerByIndex(r[e][0]),s=r[e][1],o=n._GetInstances();o[s]!==t&&(o[s]=t,t.GetWorldInfo()._SetLayer(n,!0),n.SetZIndicesChanged(t),u=!0)}u&&this._runtime.UpdateRender(),S.clearArray(d),S.clearArray(p)},SetCollisionCellSize(e,t){e=Math.floor(e),t=Math.floor(t),e<=0||t<=0||!Number.isFinite(e)||!Number.isFinite(t)||this._runtime.GetCollisionEngine().SetCollisionCellSize(e,t)},GoToLayout(e){if(this._runtime.IsLoading())return;const t=this._runtime.GetLayoutManager();t.IsPendingChangeMainLayout()||t.ChangeMainLayout(e)},GoToLayoutByName(e){if(this._runtime.IsLoading())return;const t=this._runtime.GetLayoutManager();if(t.IsPendingChangeMainLayout())return;const n=t.GetLayoutByName(e);n&&t.ChangeMainLayout(n)},NextPrevLayout(e){if(this._runtime.IsLoading())return;const t=this._runtime.GetLayoutManager();if(t.IsPendingChangeMainLayout())return;const n=t.GetAllLayouts(),r=n.indexOf(t.GetMainRunningLayout());if(e&&0===r)return;if(!e&&r===n.length-1)return;const a=n[r+(e?-1:1)];t.ChangeMainLayout(a)},RestartLayout(){if(this._runtime.IsLoading())return;const e=this._runtime.GetLayoutManager();e.IsPendingChangeMainLayout()||(e.ChangeMainLayout(e.GetMainRunningLayout()),this._runtime.GetEventSheetManager().ResetAllGroupsInitialActivation())},SetLayerVisible(e,t){e&&e.SetVisible(t)},SetLayerInteractive(e,t){e&&e.SetInteractive(t)},SetLayerHTML(e,t){e&&e.SetIsHTMLElementsLayer(t)},SetLayerOpacity(e,t){e&&e.SetOpacity(t/100)},SetLayerScale(e,t){e&&e.SetOwnScale(t)},SetLayerScaleRate(e,t){e&&e.SetScaleRate(t)},SetLayerAngle(e,t){e&&e.SetAngle(S.toRadians(+t))},SetLayerScroll(e,t,n){e&&(e.SetOwnScrollPositionEnabled(!0),e.SetScrollX(t),e.SetScrollY(n))},RestoreLayerScroll(e){e&&e.SetOwnScrollPositionEnabled(!1)},SetLayerParallax(e,t,n){e&&e.SetParallax(t/100,n/100)},SetLayerZElevation(e,t){e&&e.SetZElevation(+t)},SetLayerRenderingMode(e,t){e&&e.SetRenderAs3D(1===t)},SetLayerBackground(e,t){if(!e)return;G.setFromRgbValue(t),G.clamp();const n=e.GetBackgroundColor();n.equalsIgnoringAlpha(G)||(n.copyRgb(G),this.UpdateRender())},SetLayerTransparent(e,t){e&&e.SetTransparent(t)},SetLayerBlendMode(e,t){e&&e.SetBlendMode(t)},SetLayerEffectEnabled(e,t,n){if(!e)return;const r=e.GetEffectList().GetEffectTypeByName(n);if(!r)return;const a=1===t;r.IsActive()!==a&&(r.SetActive(a),e.UpdateActiveEffects(),this._runtime.UpdateRender())},SetLayerEffectParam(e,t,n,r){if(!e)return;const a=e.GetEffectList(),i=a.GetEffectTypeByName(t);if(!i)return;n=Math.floor(n);const s=i.GetShaderProgram().GetParameterType(n);if(!s)return;"color"===s?(G.setFromRgbValue(r),r=G):"percent"===s&&(r/=100);a.SetEffectParameter(i.GetIndex(),n,r)&&i.IsActive()&&this._runtime.UpdateRender()},SetLayerForceOwnTexture(e,t){e&&e.SetForceOwnTexture(t)},SetLayoutScale(e){this._runtime.GetCurrentLayout().SetScale(+e)},SetLayoutAngle(e){this._runtime.GetCurrentLayout().SetAngle(S.toRadians(+e))},SetLayoutEffectEnabled(e,t){const n=this._runtime.GetCurrentLayout(),r=n.GetEffectList().GetEffectTypeByName(t);if(!r)return;const a=1===e;r.IsActive()!==a&&(r.SetActive(a),n.UpdateActiveEffects(),this._runtime.UpdateRender())},SetLayoutEffectParam(e,t,n){const r=this._runtime.GetCurrentLayout().GetEffectList(),a=r.GetEffectTypeByName(e);if(!a)return;t=Math.floor(t);const i=a.GetShaderProgram().GetParameterType(t);if(!i)return;"color"===i?(G.setFromRgbValue(n),n=G):"percent"===i&&(n/=100);r.SetEffectParameter(a.GetIndex(),t,n)&&a.IsActive()&&this._runtime.UpdateRender()},SetLayoutVanishingPoint(e,t){this._runtime.GetCurrentLayout().SetVanishingPointXY(e/100,t/100)},SetLayoutProjection(e){const t=this._runtime.GetCurrentLayout();0===e?t.SetPerspectiveProjection():t.SetOrthographicProjection()},ScrollX(e){this._runtime.GetCurrentLayout().SetScrollX(e)},ScrollY(e){this._runtime.GetCurrentLayout().SetScrollY(e)},Scroll(e,t){const n=this._runtime.GetCurrentLayout();n.SetScrollX(e),n.SetScrollY(t)},ScrollToObject(e){if(!e)return;const t=e.GetFirstPicked();if(!t)return;const n=t.GetWorldInfo();if(!n)return;const r=this._runtime.GetCurrentLayout();r.SetScrollX(n.GetX()),r.SetScrollY(n.GetY())},AddLayer(e,t,n){const r=this._runtime.GetCurrentLayout();try{r.AddLayer(e,t,n)}catch(e){console.warn("[Construct] Cannot add layer: ",e)}},MoveLayer(e,t,n){if(!e)return;const r=this._runtime.GetCurrentLayout();try{r.MoveLayer(e,t,n)}catch(e){console.warn("[Construct] Cannot move layer: ",e)}},RemoveLayer(e){if(!e)return;this._runtime.GetCurrentLayout().RemoveLayer(e)},RemoveAllDynamicLayers(){this._runtime.GetCurrentLayout().RemoveAllDynamicLayers()},async LoadObjectTextures(e){const t=this._runtime.GetMainRunningLayout();if(!t||!e||this._runtime.IsLoading())return;const n=e.IsFamily()?e.GetFamilyMembers():[e];await this._LoadTexturesForObjectClasses(t,n)},async LoadObjectTexturesByName(e){await S.Plugins.System.Acts.LoadObjectTextures.call(this,this._runtime.GetObjectClassByName(e))},UnloadObjectTextures(e){const t=this._runtime.GetMainRunningLayout();if(!t||!e)return;const n=e.IsFamily()?e.GetFamilyMembers():[e];this._UnloadTexturesForObjectClasses(t,n)},UnloadObjectTexturesByName(e){S.Plugins.System.Acts.UnloadObjectTextures.call(this,this._runtime.GetObjectClassByName(e))},UnloadUnusedTextures(){const e=this._runtime.GetMainRunningLayout();if(!e)return;const t=e._GetTextureLoadedObjectTypes();this._UnloadTexturesForObjectClasses(e,t)},async LoadLayoutTextures(e){const t=this._runtime.GetMainRunningLayout();e&&t&&!this._runtime.IsLoading()&&await this._LoadTexturesForObjectClasses(t,e._GetInitialObjectClasses())},async LoadLayoutTexturesByName(e){const t=this._runtime.GetMainRunningLayout(),n=this._runtime.GetLayoutManager().GetLayoutByName(e);n&&t&&!this._runtime.IsLoading()&&await this._LoadTexturesForObjectClasses(t,n._GetInitialObjectClasses())},SetFunctionReturnValue(e){const t=this._eventStack.GetCurrentExpFuncStackFrame();if(t)switch(t.GetFunctionReturnType()){case 1:"number"==typeof e&&t.SetFunctionReturnValue(e);break;case 2:"string"==typeof e&&t.SetFunctionReturnValue(e);break;case 3:t.SetFunctionReturnValue(e)}},MapFunction(e,t,n){const r=this._GetFunctionMap(e.toLowerCase(),!0),a=r.strMap,i=t.toLowerCase();a.has(i)&&console.warn(`[Construct] Function map '${e}' string '${t}' already in map; overwriting entry`);const s=S.first(a.values())||r.defaultFunc;if(s){if(0!==s.GetReturnType()!==(0!==n.GetReturnType()))return void console.error(`[Construct] Function map '${e}' string '${t}' function return type not compatible with other functions in the map; entry ignored`)}a.set(i,n)},MapFunctionDefault(e,t){const n=this._GetFunctionMap(e.toLowerCase(),!0);n.defaultFunc&&console.warn(`[Construct] Function map '${e}' already has a default; overwriting entry`);const r=S.first(n.strMap.values())||n.defaultFunc;if(r){if(0!==r.GetReturnType()!==(0!==t.GetReturnType()))return void console.error(`[Construct] Function map '${e}' default: function return type not compatible with other functions in the map; entry ignored`)}n.defaultFunc=t},CallMappedFunction(e,t,n){const r=this._runtime,a=r.IsDebugging()?y:null;n=Math.floor(n);const i=this._GetFunctionMap(e.toLowerCase(),!1);if(!i)return console.warn(`[Construct] Call mapped function: map name '${e}' not found; call ignored`),a;let s=i.strMap.get(t.toLowerCase());if(!s){if(!i.defaultFunc)return console.warn(`[Construct] Call mapped function: no function associated with map '${e}' string '${t}'; call ignored (consider setting a default)`),a;s=i.defaultFunc,n=0}if(!s.IsEnabled())return a;if(0!==s.GetReturnType())return console.warn(`[Construct] Call mapped function: map '${e}' string '${t}' has a return type so cannot be called`),a;const o=r.GetEventSheetManager(),u=o.GetCurrentEvent(),l=u.GetSolModifiersIncludingParents(),c=l.length>0;c&&(s.IsCopyPicked()?o.PushCopySol(l):o.PushCleanSol(l));const h=[],g=o.FindFirstFunctionBlockParent(u);if(g){const e=g.GetFunctionParameters();for(let t=n,r=e.length;t<r;++t)h.push(e[t].GetValue())}const S=s.GetFunctionParameters();for(let e=h.length,t=S.length;e<t;++e)h.push(S[e].GetInitialValue());return r.IsDebugging()?this._DebugDoCallMappedFunction(o,s,h,c,l):this._DoCallMappedFunction(o,s,h,c,l)}}}{const f=self.C3;f.Plugins.System.Exps={int:function(e){return"string"==typeof e&&(e=parseInt(e,10),isNaN(e)&&(e=0)),Math.floor(e)},float:function(e){return"string"==typeof e&&(e=parseFloat(e),isNaN(e)&&(e=0)),e},str:e=>e.toString(),len:e=>"string"==typeof e?e.length:0,random(e,t){return void 0===t?this._runtime.Random()*e:this._runtime.Random()*(t-e)+e},choose(...e){return e[Math.floor(this._runtime.Random()*e.length)]},chooseindex:(e,...t)=>("number"!=typeof e&&(e=0),t[e=f.clamp(Math.floor(e),0,t.length-1)]),pi:()=>Math.PI,infinity:()=>1/0,sqrt:e=>Math.sqrt(e),abs:e=>Math.abs(e),round:e=>Math.round(e),roundtodp(e,t){t=Math.max(Math.floor(t),0);const n=Math.pow(10,t);return Math.round((e+Number.EPSILON)*n)/n},floor:e=>Math.floor(e),ceil:e=>Math.ceil(e),sign:e=>Math.sign(e),sin:e=>Math.sin(f.toRadians(e)),cos:e=>Math.cos(f.toRadians(e)),tan:e=>Math.tan(f.toRadians(e)),asin:e=>f.toDegrees(Math.asin(e)),acos:e=>f.toDegrees(Math.acos(e)),atan:e=>f.toDegrees(Math.atan(e)),exp:e=>Math.exp(e),ln:e=>Math.log(e),log10:e=>Math.log10(e),max(...e){let t=e[0];"number"!=typeof t&&(t=0);for(let n=1,r=e.length;n<r;++n){let r=e[n];"number"==typeof r&&(t<r&&(t=r))}return t},min(...e){let t=e[0];"number"!=typeof t&&(t=0);for(let n=1,r=e.length;n<r;++n){let r=e[n];"number"==typeof r&&(t>r&&(t=r))}return t},clamp:(e,t,n)=>f.clamp(e,t,n),distance:(e,t,n,r)=>f.distanceTo(e,t,n,r),angle:(e,t,n,r)=>f.toDegrees(f.angleTo(e,t,n,r)),lerp:(e,t,n)=>f.lerp(e,t,n),unlerp:(e,t,n)=>f.unlerp(e,t,n),qarp:(e,t,n,r)=>f.qarp(e,t,n,r),cubic:(e,t,n,r,a)=>f.cubic(e,t,n,r,a),cosp:(e,t,n)=>f.cosp(e,t,n),anglediff:(e,t)=>f.toDegrees(f.angleDiff(f.toRadians(e),f.toRadians(t))),anglelerp:(e,t,n)=>f.toDegrees(f.angleLerp(f.toRadians(e),f.toRadians(t),n)),anglerotate:(e,t,n)=>f.toDegrees(f.angleRotate(f.toRadians(e),f.toRadians(t),f.toRadians(n))),setbit:(e,t,n)=>(e|=0)&~(1<<(t|=0))|(n=0!==n?1:0)<<t,togglebit:(e,t)=>(e|=0)^1<<(t|=0),getbit:(e,t)=>(e|=0)&1<<(t|=0)?1:0,newline:()=>"\n",uppercase:e=>"string"==typeof e?e.toUpperCase():"",lowercase:e=>"string"==typeof e?e.toLowerCase():"",left:(e,t)=>"string"==typeof e?e.substr(0,t):"",mid:(e,t,n)=>"string"!=typeof e?"":n<0?e.substr(t):e.substr(t,n),right:(e,t)=>"string"==typeof e?e.substr(Math.max(e.length-t,0)):"",trim:e=>"string"==typeof e?e.trim():"",tokenat(e,t,n){if("string"!=typeof e||"string"!=typeof n)return"";let r=e.split(n);return(t=Math.floor(t))<0||t>=r.length?"":r[t]},tokencount:(e,t)=>"string"==typeof e&&"string"==typeof t&&e.length?e.split(t).length:0,find:(e,t)=>"string"==typeof e&&"string"==typeof t?e.search(new RegExp(f.EscapeRegex(t),"i")):-1,findcase:(e,t)=>"string"==typeof e&&"string"==typeof t?e.search(new RegExp(f.EscapeRegex(t),"")):-1,replace:(e,t,n)=>"string"==typeof e&&"string"==typeof t&&"string"==typeof n?e.replace(new RegExp(f.EscapeRegex(t),"gi"),n):"string"==typeof e?e:"",stringsub(e,...t){let n=e;for(let e=0,r=t.length;e<r;++e)n=n.replaceAll(`{${e}}`,t[e].toString());return n},regexsearch(e,t,n){const r=this.GetRegex(t,n);return e?e.search(r):-1},regexreplace(e,t,n,r){const a=this.GetRegex(t,n);return e?e.replace(a,r):""},regexmatchcount(e,t,n){const r=this.GetRegexMatches(e.toString(),t,n);return r?r.length:0},regexmatchat(e,t,n,r){r=Math.floor(r);const a=this.GetRegexMatches(e.toString(),t,n);return!a||r<0||r>=a.length?"":a[r]},zeropad(e,t){let n=e<0?"-":"";e<0&&(e=-e);const r=t-e.toString().length;return n+="0".repeat(Math.max(r,0)),n+e.toString()},urlencode:e=>encodeURIComponent(e),urldecode:e=>decodeURIComponent(e),dt(){return this._runtime._GetDtFast()},wallclockdt(){return this._runtime.GetDt1()},timescale(){return this._runtime.GetTimeScale()},wallclocktime(){return(Date.now()-this._runtime.GetStartTime())/1e3},unixtime:()=>Date.now(),time(){return this._runtime.GetGameTime()},tickcount(){return this._runtime.GetTickCount()},objectcount(){return this._runtime.GetObjectCount()},fps(){return this._runtime.GetFramesPerSecond()},cpuutilisation(){return this._runtime.GetMainThreadTime()},gpuutilisation(){return this._runtime.GetGPUUtilisation()},windowwidth(){return this._runtime.GetCanvasManager().GetDeviceWidth()},windowheight(){return this._runtime.GetCanvasManager().GetDeviceHeight()},originalwindowwidth(){return this._runtime.GetOriginalViewportWidth()},originalwindowheight(){return this._runtime.GetOriginalViewportHeight()},originalviewportwidth(){return this._runtime.GetOriginalViewportWidth()},originalviewportheight(){return this._runtime.GetOriginalViewportHeight()},scrollx(){return this._runtime.GetCurrentLayout().GetScrollX()},scrolly(){return this._runtime.GetCurrentLayout().GetScrollY()},layoutname(){return this._runtime.GetCurrentLayout().GetName()},layoutscale(){return this._runtime.GetCurrentLayout().GetScale()},layoutangle(){return f.toDegrees(this._runtime.GetCurrentLayout().GetAngle())},layoutwidth(){return this._runtime.GetCurrentLayout().GetWidth()},layoutheight(){return this._runtime.GetCurrentLayout().GetHeight()},vanishingpointx(){return 100*this._runtime.GetCurrentLayout().GetVanishingPointX()},vanishingpointy(){return 100*this._runtime.GetCurrentLayout().GetVanishingPointY()},viewportleft(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().getLeft():0},viewporttop(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().getTop():0},viewportright(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().getRight():0},viewportbottom(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().getBottom():0},viewportwidth(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().width():0},viewportheight(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().height():0},viewportmidx(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);if(t){const e=t.GetViewport3D();return(e.getLeft()+e.getRight())/2}return 0},viewportmidy(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);if(t){const e=t.GetViewport3D();return(e.getTop()+e.getBottom())/2}return 0},canvastolayerx(e,t,n){const r=this._runtime.GetCurrentLayout().GetLayer(e);return r?r.CanvasCssToLayer(t,n)[0]:0},canvastolayery(e,t,n){const r=this._runtime.GetCurrentLayout().GetLayer(e);return r?r.CanvasCssToLayer(t,n)[1]:0},layertocanvasx(e,t,n){const r=this._runtime.GetCurrentLayout().GetLayer(e);return r?r.LayerToCanvasCss(t,n)[0]:0},layertocanvasy(e,t,n){const r=this._runtime.GetCurrentLayout().GetLayer(e);return r?r.LayerToCanvasCss(t,n)[1]:0},layertolayerx(e,t,n,r){const a=this._runtime.GetCurrentLayout(),i=a.GetLayer(e),s=a.GetLayer(t);if(!i||!s||i===s)return n;const[o,u]=i.LayerToCanvasCss(n,r);return s.CanvasCssToLayer(o,u)[0]},layertolayery(e,t,n,r){const a=this._runtime.GetCurrentLayout(),i=a.GetLayer(e),s=a.GetLayer(t);if(!i||!s||i===s)return r;const[o,u]=i.LayerToCanvasCss(n,r);return s.CanvasCssToLayer(o,u)[1]},layerscale(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetOwnScale():0},layerangle(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?f.toDegrees(t.GetOwnAngle()):0},layeropacity(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?100*t.GetOpacity():0},layerscalerate(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetScaleRate():0},layerscrollx(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetScrollX():0},layerscrolly(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetScrollY():0},layerparallaxx(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?100*t.GetParallaxX():0},layerparallaxy(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?100*t.GetParallaxY():0},layerzelevation(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetZElevation():0},layerindex(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetIndex():-1},canvassnapshot(){const e=this._runtime.GetCanvasManager();return e?e.GetCanvasSnapshotUrl():""},loopindex(e){const t=this._loopStack;if(!t.IsInLoop())return 0;if(e){const n=t.FindByName(e);return n?n.GetIndex():0}return t.GetCurrent().GetIndex()},savestatejson(){return this._runtime.GetLastSaveJsonString()},callmapped(e,t,...n){const r=this._GetFunctionMap(e.toLowerCase(),!1);if(!r)return console.warn(`[Construct] Call mapped function: map name '${e}' not found; returning 0`),0;let a=r.strMap.get(t.toLowerCase());if(!a){if(!r.defaultFunc)return console.warn(`[Construct] Call mapped function: no function associated with map '${e}' string '${t}'; returning 0 (consider setting a default)`),0;a=r.defaultFunc}const i=a.GetReturnType(),s=a.GetDefaultReturnValue();if(0===i)return console.warn(`[Construct] Call mapped function: map '${e}' string '${t}' has no return type so cannot be called from an expression; returning 0`),0;if(!a.IsEnabled())return s;const o=this._runtime.GetEventSheetManager(),u=o.GetCurrentEvent().GetSolModifiersIncludingParents(),l=u.length>0;l&&(a.IsCopyPicked()?o.PushCopySol(u):o.PushCleanSol(u));const c=a.GetFunctionParameters();for(let e=n.length,t=c.length;e<t;++e)n.push(c[e].GetInitialValue());const h=a.GetEventBlock(),g=h.RunAsExpressionFunctionCall(h.GetSolModifiersIncludingParents(),a.IsCopyPicked(),i,s,...n);return l&&o.PopSol(u),g},loadingprogress(){return this._runtime.GetAssetManager().GetLoadProgress()},imageloadingprogress(){return this.GetImageLoadingProgress()},renderer(){return this._runtime.GetWebGPURenderer()?"webgpu":"webgl"},rendererdetail(){return this._runtime.GetWebGPURenderer()?this._runtime.GetWebGPURenderer().GetAdapterInfoString():this._runtime.GetWebGLRenderer().GetUnmaskedRenderer()},imagememoryusage(){let e=this._runtime.GetRenderer().GetEstimatedTextureMemoryUsage();return Math.round(100*e/1048576)/100},rgb:(e,t,n)=>f.PackRGB(e,t,n),rgbex:(e,t,n)=>f.PackRGBEx(e/100,t/100,n/100),rgba:(e,t,n,r)=>f.PackRGBAEx(e/100,t/100,n/100,r/100),rgbex255:(e,t,n)=>f.PackRGBEx(e/255,t/255,n/255),rgba255:(e,t,n,r)=>f.PackRGBAEx(e/255,t/255,n/255,r/255),projectname(){return this._runtime.GetProjectName()},projectversion(){return this._runtime.GetProjectVersion()},projectid(){return this._runtime.GetAppId()},projectuniqueid(){return this._runtime.GetProjectUniqueId()},currenteventsheetname(){return this._runtime.GetCurrentEvent().GetEventSheet().GetName()},currenteventnumber(){return this._runtime.GetCurrentEvent().GetDisplayNumber()}}}
}

// scripts/plugins/Sprite/c3runtime/runtime.js
{
{const t=self.C3;t.Plugins.Sprite=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3,e=self.C3X,n=[];t.Plugins.Sprite.Type=class extends t.SDKTypeBase{constructor(t){super(t),this._animations=t.GetAnimations()}Release(){t.clearArray(this._animations),super.Release()}OnCreate(){for(const t of this._animations)t.LoadAllAssets(this._runtime)}LoadTextures(t){const e={sampling:this._runtime.GetSampling()};return Promise.all(this._animations.map((n=>n.LoadAllTextures(t,e))))}ReleaseTextures(){for(const t of this._animations)t.ReleaseAllTextures()}OnDynamicTextureLoadComplete(){this._UpdateAllCurrentTexture()}_UpdateAllCurrentTexture(){for(const t of this._objectClass.instancesIncludingPendingCreate())t.GetSdkInstance()._UpdateCurrentTexture()}FinishCondition(e){t.Plugins.Sprite.FinishCollisionCondition(this,e)}BeforeRunAction(t){n.push({objectClass:null,createHierarchy:!1,instances:[]})}_SpawnPickInstance(t,e,i){const r=n.at(-1);r.objectClass=t,r.createHierarchy=i,r.instances.push(e)}AfterRunAction(t){const e=n.pop(),i=e.objectClass,r=e.createHierarchy;if(!i)return;const a=new Map;for(const t of e.instances)t.CollectInstancesToPick(a,i,r);for(const[t,e]of a)t.GetCurrentSol().SetSetPicked(e)}_AddAnimation(t){const e=this.GetObjectClass().AddAnimation(t),n=this.GetRuntime();return e.GetFrameAt(0).GetImageInfo().LoadStaticTexture(n.GetRenderer(),{sampling:n.GetSampling()}).then((()=>this._UpdateAllCurrentTexture())),e}_RemoveAnimation(t){for(const e of this._objectClass.instancesIncludingPendingCreate())e.GetSdkInstance()._OnAnimationRemoved(t);this.GetObjectClass().RemoveAnimation(t)}_AddAnimationFrame(e,n){const i=this._objectClass.GetAnimationByName(e);if(!i)throw new Error(`cannot find animation name '${e}'`);let r=i.FrameTagOrIndexToIndex(n);r<0&&(r+=i.GetFrameCount()+1);const a=t.AnimationFrameInfo.CreateDynamic(this.GetRuntime());i.InsertFrameAt(a,r);const s=this.GetRuntime();a.GetImageInfo().LoadStaticTexture(s.GetRenderer(),{sampling:s.GetSampling()}).then((()=>this._UpdateAllCurrentTexture()));for(const t of this._objectClass.instancesIncludingPendingCreate())t.GetSdkInstance()._OnAnimationFramesChanged();return a}_RemoveAnimationFrame(t,e){const n=this._objectClass.GetAnimationByName(t);if(!n)throw new Error(`cannot find animation name '${t}'`);if(1===n.GetFrameCount())throw new Error(`cannot remove last frame from animation '${t}'`);let i=n.FrameTagOrIndexToIndex(e);i<0&&(i+=n.GetFrameCount()),n.RemoveFrameAt(i);for(const t of this._objectClass.instancesIncludingPendingCreate())t.GetSdkInstance()._OnAnimationFramesChanged()}GetScriptInterfaceClass(){return self.ISpriteObjectType}};const i=new WeakMap;self.ISpriteObjectType=class extends self.IObjectType{constructor(t){super(t),i.set(this,t.GetSdkType())}getAnimation(t){e.RequireString(t);const n=i.get(this).GetObjectClass().GetAnimationByName(t);return n?n.GetIAnimation():null}getAllAnimations(){return i.get(this).GetObjectClass().GetAllAnimations().map((t=>t.GetIAnimation()))}addAnimation(t){return e.RequireString(t),i.get(this)._AddAnimation(t).GetIAnimation()}removeAnimation(t){e.RequireString(t),i.get(this)._RemoveAnimation(t)}addAnimationFrame(t,n){if(e.RequireString(t),"number"!=typeof n&&"string"!=typeof n)throw new TypeError("invalid insert location");return i.get(this)._AddAnimationFrame(t,n).GetIAnimationFrame()}removeAnimationFrame(t,n){if(e.RequireString(t),"number"!=typeof n&&"string"!=typeof n)throw new TypeError("invalid insert location");i.get(this)._RemoveAnimationFrame(t,n)}}}{const t=self.C3,e=self.C3X,n=0,i=1,r=2,a=3,s=t.New(t.Rect),o=t.New(t.Quad),m=t.New(t.Vector2),h=1,u=2,c=4;t.Plugins.Sprite.Instance=class extends t.SDKWorldInstanceBase{constructor(e,s){super(e);let o=!0,m="",c=0,l=!0;s&&(o=!!s[n],m=s[i],c=s[r],l=s[a]),this._currentAnimation=this._objectClass.GetAnimationByName(m)||this._objectClass.GetAnimations()[0],this._currentFrameIndex=t.clamp(c,0,this._currentAnimation.GetFrameCount()-1),this._currentAnimationFrame=this._currentAnimation.GetFrameAt(this._currentFrameIndex);const d=this._currentAnimationFrame.GetImageInfo();this._currentTexture=d.GetTexture(),this._currentRcTex=d.GetTexRect(),this._currentQuadTex=d.GetTexQuad(),this.HandleRendererContextLoss(),e.SetFlag(u,!0),e.SetFlag(h,this._currentAnimation.GetSpeed()>=0),this._currentAnimationSpeed=Math.abs(this._currentAnimation.GetSpeed()),this._currentAnimationRepeatTo=this._currentAnimation.GetRepeatTo(),this._animationTimer=t.New(t.KahanSum),this._frameStartTime=0,this._animationRepeats=0,this._animTriggerName="",this._changeAnimFrameIndex=-1,this._changeAnimationName="",this._changeAnimationFrom=0;const g=this.GetWorldInfo();this._bquadRef=g.GetBoundingQuad(),g.SetVisible(o),g.SetCollisionEnabled(l),g.SetOriginX(this._currentAnimationFrame.GetOriginX()),g.SetOriginY(this._currentAnimationFrame.GetOriginY()),g.SetSourceCollisionPoly(this._currentAnimationFrame.GetCollisionPoly()),g.SetBboxChanged(),1===this._objectClass.GetAnimationCount()&&1===this._objectClass.GetAnimations()[0].GetFrameCount()||0===this._currentAnimationSpeed||this._StartTicking()}Release(){this._currentAnimation=null,this._currentAnimationFrame=null,this._currentTexture=null,this._animationTimer=null,super.Release()}GetCurrentImageInfo(){return this._currentAnimationFrame.GetImageInfo()}IsOriginalSizeKnown(){return!0}OnRendererContextLost(){this._currentTexture=null}OnRendererContextRestored(){this._UpdateCurrentTexture()}Draw(t){const e=this._currentTexture;if(null===e)return;t.SetTexture(e);const n=this.GetWorldInfo();n.HasMesh()?this._DrawMesh(n,t):this._DrawStandard(n,t)}_DrawStandard(t,e){let n=this._bquadRef;this._runtime.IsPixelRoundingEnabled()&&(n=t.PixelRoundQuad(n)),e.Quad4(n,this._currentQuadTex)}_DrawMesh(t,e){const n=t.GetTransformedMesh();if(t.IsMeshChanged()){t.CalculateBbox(s,o,!1);let e=o;this._runtime.IsPixelRoundingEnabled()&&(e=t.PixelRoundQuad(e)),n.CalculateTransformedMesh(t.GetSourceMesh(),e,this._currentQuadTex),t.SetMeshChanged(!1)}n.Draw(e)}GetAnimationTime(){return this._animationTimer.Get()}IsAnimationPlaying(){return this._inst.GetFlag(u)}SetAnimationPlaying(t){this._inst.SetFlag(u,t)}IsPlayingForwards(){return this._inst.GetFlag(h)}SetPlayingForwards(t){this._inst.SetFlag(h,t)}IsInAnimationTrigger(){return this._inst.GetFlag(c)}SetInAnimationTrigger(t){this._inst.SetFlag(c,t)}Tick(){this._changeAnimationName&&this._DoChangeAnimation(),this._changeAnimFrameIndex>=0&&this._DoChangeAnimFrame();const e=this._currentAnimationSpeed;if(!this.IsAnimationPlaying()||0===e)return void this._StopTicking();const n=this._runtime.GetDt(this._inst);this._animationTimer.Add(n);const i=this.GetAnimationTime(),r=this._currentAnimationFrame,a=r.GetDuration()/e;if(i<this._frameStartTime+a)return;const s=this._currentAnimation,o=this._currentAnimationRepeatTo,m=s.GetFrameCount(),h=s.GetRepeatCount(),u=s.IsLooping(),c=s.IsPingPong();this.IsPlayingForwards()?this._currentFrameIndex++:this._currentFrameIndex--,this._frameStartTime+=a,this._currentFrameIndex>=m&&(c?(this.SetPlayingForwards(!1),this._currentFrameIndex=m-2):u?this._currentFrameIndex=o:(this._animationRepeats++,this._animationRepeats>=h?this._FinishAnimation(!1):this._currentFrameIndex=o)),this._currentFrameIndex<0&&(c?(this._currentFrameIndex=1,this.SetPlayingForwards(!0),u||(this._animationRepeats++,this._animationRepeats>=h&&this._FinishAnimation(!0))):u?this._currentFrameIndex=o:(this._animationRepeats++,this._animationRepeats>=h?this._FinishAnimation(!0):this._currentFrameIndex=o)),this._currentFrameIndex=t.clamp(this._currentFrameIndex,0,m-1);const l=s.GetFrameAt(this._currentFrameIndex);i>this._frameStartTime+l.GetDuration()/e&&(this._frameStartTime=i),this._OnFrameChanged(r,l)}_FinishAnimation(e){this._currentFrameIndex=e?0:this._currentAnimation.GetFrameCount()-1,this.SetAnimationPlaying(!1),this._animTriggerName=this._currentAnimation.GetName(),this.SetInAnimationTrigger(!0),this.DispatchScriptEvent("animationend",!1,{animationName:this._animTriggerName}),this.Trigger(t.Plugins.Sprite.Cnds.OnAnyAnimFinished),this.Trigger(t.Plugins.Sprite.Cnds.OnAnimFinished),this.SetInAnimationTrigger(!1),this._animationRepeats=0}_OnFrameChanged(e,n,i){if(e===n)return;const r=this.GetWorldInfo(),a=e.GetImageInfo(),s=n.GetImageInfo(),o=a.GetWidth(),m=a.GetHeight(),h=s.GetWidth(),u=s.GetHeight();i&&i.onFrameChange?i.onFrameChange(r,o,m,h,u):(o!==h&&r.SetWidth(r.GetWidth()*(h/o)),m!==u&&r.SetHeight(r.GetHeight()*(u/m))),r.SetOriginX(n.GetOriginX()),r.SetOriginY(n.GetOriginY()),r.SetSourceCollisionPoly(n.GetCollisionPoly()),r.SetBboxChanged(),this._currentAnimationFrame=n,this._currentTexture=s.GetTexture(),this._currentRcTex=s.GetTexRect(),this._currentQuadTex=s.GetTexQuad();const c=this.GetInstance().GetBehaviorInstances();for(let t=0,i=c.length;t<i;++t)c[t].OnSpriteFrameChanged(e,n);this.DispatchScriptEvent("framechange",!1,{animationName:this._currentAnimation.GetName(),animationFrame:this._currentFrameIndex}),this.Trigger(t.Plugins.Sprite.Cnds.OnFrameChanged),this._runtime.UpdateRender()}_StartAnim(t){this.SetAnimationPlaying(!0),this._frameStartTime=this.GetAnimationTime(),1===t&&0!==this._currentFrameIndex&&(this._changeAnimFrameIndex=0,this.IsInAnimationTrigger()||this._DoChangeAnimFrame()),this._StartTicking()}_SetAnim(t,e,n){this._changeAnimationName=t,this._changeAnimationFrom=e,this._StartTicking(),!n&&this.IsInAnimationTrigger()||this._DoChangeAnimation()}_GetCurrentAnimation(){return this._currentAnimation}_GetCurrentAnimationName(){return this._changeAnimationName?this._changeAnimationName:this._currentAnimation.GetName()}_OnAnimationRemoved(e){t.equalsNoCase(e,this._GetCurrentAnimationName())&&this._SetAnim(this._objectClass.GetFirstAnimation().GetName(),1,!0)}_SetAnimFrame(t){if("string"==typeof t)if(String(Number(t))===t)t=Number(t);else{const e=this._objectClass.GetAnimationByName(this._GetCurrentAnimationName());if(!e)return;if(-1===(t=e.GetFrameIndexByTag(t)))return}isFinite(t)&&(this._changeAnimFrameIndex=t,this.IsInAnimationTrigger()||this._DoChangeAnimFrame())}_OnAnimationFramesChanged(){if(this._changeAnimationName||-1!==this._changeAnimFrameIndex)return;const e=this._currentAnimationFrame,n=this._currentAnimation.GetFrameAt(t.clamp(this._currentFrameIndex,0,this._currentAnimation.GetFrameCount()-1));e!==n&&this._OnFrameChanged(e,n),this._currentAnimation.GetFrameCount()>1&&this._currentAnimationSpeed>0&&this._StartTicking()}_GetAnimFrame(){return this._currentFrameIndex}_GetAnimFrameTag(){return this._currentAnimationFrame.GetTag()}_SetAnimSpeed(t){this._currentAnimationSpeed=Math.abs(t),this.SetPlayingForwards(t>=0),this._currentAnimationSpeed>0&&this._StartTicking()}_GetAnimSpeed(){return this.IsPlayingForwards()?this._currentAnimationSpeed:-this._currentAnimationSpeed}_SetAnimRepeatToFrame(e){"string"==typeof e&&-1===(e=this._currentAnimation.GetFrameIndexByTag(e))||(e=t.clamp(Math.floor(e),0,this._currentAnimation.GetFrameCount()-1),this._currentAnimationRepeatTo=e)}_GetAnimRepeatToFrame(){return this._currentAnimationRepeatTo}_DoChangeAnimation(e){const n=this._currentAnimationFrame,i=this._objectClass.GetAnimationByName(this._changeAnimationName);if(this._changeAnimationName="",!i)return;if(i===this._currentAnimation&&this.IsAnimationPlaying())return;this._currentAnimation=i,this.SetPlayingForwards(i.GetSpeed()>=0),this._currentAnimationSpeed=Math.abs(i.GetSpeed()),this._currentAnimationRepeatTo=i.GetRepeatTo(),this._currentFrameIndex=t.clamp(this._currentFrameIndex,0,this._currentAnimation.GetFrameCount()-1),1===this._changeAnimationFrom&&(this._currentFrameIndex=0),this.SetAnimationPlaying(!0),this._frameStartTime=this.GetAnimationTime();const r=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._OnFrameChanged(n,r,e)}_DoChangeAnimFrame(e){const n=this._currentAnimationFrame,i=this._currentFrameIndex;if(this._currentFrameIndex=t.clamp(Math.floor(this._changeAnimFrameIndex),0,this._currentAnimation.GetFrameCount()-1),this._changeAnimFrameIndex=-1,!e&&i===this._currentFrameIndex)return;const r=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._OnFrameChanged(n,r),this._frameStartTime=this.GetAnimationTime()}_UpdateCurrentTexture(){const t=this._currentAnimationFrame.GetImageInfo();this._currentTexture=t.GetTexture(),this._currentRcTex=t.GetTexRect(),this._currentQuadTex=t.GetTexQuad(),this.GetWorldInfo().SetMeshChanged(!0)}GetTexture(){return this._currentTexture}GetTexRect(){return this._currentRcTex}GetTexQuad(){return this._currentQuadTex}GetImagePointCount(){return this._currentAnimationFrame.GetImagePointCount()}GetImagePoint(t){const e=this._currentAnimationFrame,n=this.GetWorldInfo();let i=null;if("string"==typeof t)i=e.GetImagePointByName(t);else{if("number"!=typeof t)throw new TypeError("expected string or number");i=e.GetImagePointByIndex(t-1)}let r=n.GetTotalZElevation();if(!i)return[n.GetX(),n.GetY(),r];if(m.copy(i.GetVec2()),n.HasMesh()){const[t,e,i]=n.GetSourceMesh().TransformPoint(m.getX(),m.getY());m.set(t,e),r+=i}return m.offset(-e.GetOriginX(),-e.GetOriginY()),m.scale(n.GetWidth(),n.GetHeight()),m.rotate(n.GetAngle()),m.offset(n.GetX(),n.GetY()),[m.getX(),m.getY(),r]}GetCollisionPolyPointCount(){return this.GetWorldInfo().GetTransformedCollisionPoly().pointCount()}GetCollisionPolyPoint(t){t=Math.floor(t);const e=this.GetWorldInfo(),n=e.GetTransformedCollisionPoly(),i=n.pointCount();if(t===i&&(t=0),t<0||t>=i)return[0,0];const r=n.pointsArr();return[r[2*t+0]+e.GetX(),r[2*t+1]+e.GetY()]}GetDebuggerProperties(){const e=t.Plugins.Sprite.Acts,n="plugins.sprite.debugger.animation-properties";return[{title:n+".title",properties:[{name:n+".current-animation",value:this._currentAnimation.GetName(),onedit:t=>this.CallAction(e.SetAnim,t,0)},{name:n+".current-frame",value:this._currentFrameIndex,onedit:t=>this.CallAction(e.SetAnimFrame,t)},{name:n+".is-playing",value:this.IsAnimationPlaying(),onedit:t=>t?this.CallAction(e.StartAnim,0):this.CallAction(e.StopAnim)},{name:n+".speed",value:this._currentAnimationSpeed,onedit:t=>this.CallAction(e.SetAnimSpeed,t)},{name:n+".repeats",value:this._animationRepeats,onedit:t=>this._animationRepeats=t}]}]}SaveToJson(){const t={"a":this._currentAnimation.GetSID()};0!==this._frameStartTime&&(t["fs"]=this._frameStartTime);const e=this.GetAnimationTime();0!==e&&(t["at"]=e),0!==this._currentFrameIndex&&(t["f"]=this._currentFrameIndex),0!==this._currentAnimationSpeed&&(t["cas"]=this._currentAnimationSpeed),1!==this._animationRepeats&&(t["ar"]=this._animationRepeats),0!==this._currentAnimationRepeatTo&&(t["rt"]=this._currentAnimationRepeatTo),this.IsAnimationPlaying()||(t["ap"]=this.IsAnimationPlaying()),this.IsPlayingForwards()||(t["af"]=this.IsPlayingForwards());const n=this.GetWorldInfo();return n.IsCollisionEnabled()&&(t["ce"]=n.IsCollisionEnabled()),t}LoadFromJson(e){const n=this.GetObjectClass().GetAnimationBySID(e["a"]);n&&(this._currentAnimation=n),this._frameStartTime=e.hasOwnProperty("fs")?e["fs"]:0,this._animationTimer.Set(e.hasOwnProperty("at")?e["at"]:0);const i=e.hasOwnProperty("f")?e["f"]:0;this._currentFrameIndex=t.clamp(i,0,this._currentAnimation.GetFrameCount()-1),this._currentAnimationSpeed=e.hasOwnProperty("cas")?e["cas"]:0,this._animationRepeats=e.hasOwnProperty("ar")?e["ar"]:1;const r=e.hasOwnProperty("rt")?e["rt"]:0;this._currentAnimationRepeatTo=t.clamp(r,0,this._currentAnimation.GetFrameCount()-1),this.SetAnimationPlaying(!e.hasOwnProperty("ap")||!!e["ap"]),this.SetPlayingForwards(!e.hasOwnProperty("af")||!!e["af"]);const a=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._currentAnimationFrame=a,this._UpdateCurrentTexture();const s=this.GetWorldInfo();s.SetOriginX(a.GetOriginX()),s.SetOriginY(a.GetOriginY()),s.SetSourceCollisionPoly(a.GetCollisionPoly()),s.SetCollisionEnabled(!!e["ce"]),this.IsAnimationPlaying()&&this._StartTicking()}GetPropertyValueByIndex(e){const n=this.GetWorldInfo();switch(e){case a:return n.IsCollisionEnabled();case r:return t.clamp(this._currentFrameIndex,0,this._currentAnimation.GetFrameCount()-1);case i:return this._currentAnimation.GetName()}}SetPropertyValueByIndex(e,n,s){const o=this.GetWorldInfo();switch(e){case a:o.SetCollisionEnabled(!!n);break;case r:{this.SetAnimationPlaying(!1);const e=this._currentAnimation.GetFrameCount()-1,i=n=t.clamp(n,0,e),r=this._currentAnimation.GetFrameAt(this._currentFrameIndex),a=this._currentAnimation.GetFrameAt(i);this._OnFrameChanged(r,a,s),this._currentFrameIndex=t.clamp(i,0,e);break}case i:this._changeAnimationName=n,this._DoChangeAnimation(s);this._currentAnimation.GetFrameCount()>1&&this._currentAnimation.GetSpeed()>0?this._StartTicking():this._StopTicking();break}}GetScriptInterfaceClass(){return self.ISpriteInstance}};const l=new WeakMap,d=new Map([["current-frame",0],["beginning",1]]);self.ISpriteInstance=class extends self.IWorldInstance{constructor(){super(),l.set(this,self.IInstance._GetInitInst().GetSdkInstance())}getImagePointCount(){return l.get(this).GetImagePointCount()}getImagePointX(t){return this.getImagePoint(t)[0]}getImagePointY(t){return this.getImagePoint(t)[1]}getImagePointZ(t){return this.getImagePoint(t)[2]}getImagePoint(t){if("string"!=typeof t&&"number"!=typeof t)throw new TypeError("expected string or number");return l.get(this).GetImagePoint(t)}getPolyPointCount(){return l.get(this).GetCollisionPolyPointCount()}getPolyPointX(t){return e.RequireFiniteNumber(t),l.get(this).GetCollisionPolyPoint(t)[0]}getPolyPointY(t){return e.RequireFiniteNumber(t),l.get(this).GetCollisionPolyPoint(t)[1]}getPolyPoint(t){return e.RequireFiniteNumber(t),l.get(this).GetCollisionPolyPoint(t)}stopAnimation(){l.get(this).SetAnimationPlaying(!1)}startAnimation(t="current-frame"){e.RequireString(t);const n=d.get(t);if(void 0===n)throw new Error("invalid mode");l.get(this)._StartAnim(n)}setAnimation(t,n="beginning"){e.RequireString(t),e.RequireString(n);const i=d.get(n);if(void 0===i)throw new Error("invalid mode");const r=l.get(this);if(!r.GetObjectClass().GetAnimationByName(t))throw new Error(`animation name "${t}" does not exist`);r._SetAnim(t,i)}getAnimation(t){e.RequireString(t);const n=l.get(this).GetObjectClass().GetAnimationByName(t);return n?n.GetIAnimation():null}get animation(){return l.get(this)._GetCurrentAnimation().GetIAnimation()}get animationName(){return l.get(this)._GetCurrentAnimationName()}set animationFrame(t){e.RequireFiniteNumber(t),l.get(this)._SetAnimFrame(t)}get animationFrame(){return l.get(this)._GetAnimFrame()}set animationFrameTag(t){e.RequireString(t),l.get(this)._SetAnimFrame(t)}get animationFrameTag(){return l.get(this)._GetAnimFrameTag()}set animationSpeed(t){e.RequireFiniteNumber(t),l.get(this)._SetAnimSpeed(t)}get animationSpeed(){return l.get(this)._GetAnimSpeed()}set animationRepeatToFrame(t){e.RequireFiniteNumber(t),l.get(this)._SetAnimRepeatToFrame(t)}get animationRepeatToFrame(){return l.get(this)._GetAnimRepeatToFrame()}get imageWidth(){return l.get(this).GetCurrentImageInfo().GetWidth()}get imageHeight(){return l.get(this).GetCurrentImageInfo().GetHeight()}getImageSize(){const t=l.get(this).GetCurrentImageInfo();return[t.GetWidth(),t.GetHeight()]}async replaceCurrentAnimationFrame(n){e.RequireInstanceOf(n,Blob);const i=l.get(this),r=i.GetRuntime(),a=i.GetCurrentImageInfo(),s=t.New(t.ImageInfo);if(s.LoadDynamicBlobAsset(r,n),await s.LoadStaticTexture(r.GetRenderer(),{sampling:r.GetSampling()}),i.WasReleased())return void s.Release();a.ReplaceWith(s);const o=i.GetSdkType();o._UpdateAllCurrentTexture(),o.GetObjectClass().Dispatcher().dispatchEvent(new t.Event("animationframeimagechange")),r.UpdateRender()}setSolidCollisionFilter(t,n){e.RequireString(n),l.get(this).GetWorldInfo().SetSolidCollisionFilter(!!t,n)}}}{const t=self.C3;t.Plugins.Sprite.Cnds={IsAnimPlaying(e){return t.equalsNoCase(this._GetCurrentAnimationName(),e)},CompareFrame(e,n){return t.compare(this._currentFrameIndex,e,n)},CompareFrameTag(e,n){if("string"!=typeof n)return!1;const i=this._currentAnimationFrame.GetTag();return t.compare(i.toLowerCase(),e,n.toLowerCase())},CompareAnimSpeed(e,n){return t.compare(this._GetAnimSpeed(),e,n)},OnAnimFinished(e){return t.equalsNoCase(this._animTriggerName,e)},OnAnyAnimFinished:()=>!0,OnFrameChanged:()=>!0,IsMirrored(){return this.GetWorldInfo().GetWidth()<0},IsFlipped(){return this.GetWorldInfo().GetHeight()<0},OnURLLoaded:()=>!0,OnURLFailed:()=>!0,IsCollisionEnabled(){return this.GetWorldInfo().IsCollisionEnabled()}}}{const t=self.C3;t.Plugins.Sprite.Acts={Spawn(t,e,n,i,r){if(!t||!e)return;const[a,s]=this.GetImagePoint(n),o=this._runtime.CreateInstance(t,e,a,s,i,r);if(!o)return;if(i&&e.SortAndAddInstancesByZIndex(o),t.GetPlugin().IsRotatable()){const t=o.GetWorldInfo();t.SetAngle(this.GetWorldInfo().GetAngle()),t.SetBboxChanged()}const m=this._runtime.GetEventSheetManager();m.BlockFlushingInstances(!0),o._TriggerOnCreatedOnSelfAndRelated(),m.BlockFlushingInstances(!1),t!==this._runtime.GetCurrentAction().GetObjectClass()&&this._sdkType._SpawnPickInstance(t,o,i)},StopAnim(){this.SetAnimationPlaying(!1)},StartAnim(t){this._StartAnim(t)},SetAnim(t,e){this._SetAnim(t,e)},SetAnimFrame(t){this._SetAnimFrame(t)},SetAnimSpeed(t){this._SetAnimSpeed(t)},SetAnimRepeatToFrame(t){this._SetAnimRepeatToFrame(t)},AddRemoveAnimation(t,e){try{0===t?this.GetSdkType()._AddAnimation(e):this.GetSdkType()._RemoveAnimation(e)}catch(e){console.error(`[Construct] Error ${0===t?"adding":"removing"} animation: `,e)}},AddRemoveAnimationFrame(t,e,n){try{0===t?this.GetSdkType()._AddAnimationFrame(e,n):this.GetSdkType()._RemoveAnimationFrame(e,n)}catch(e){console.error(`[Construct] Error ${0===t?"adding":"removing"} animation frame: `,e)}},SetMirrored(t){const e=this.GetWorldInfo(),n=e.GetWidth(),i=Math.abs(n)*(0===t?-1:1);n!==i&&(e.SetWidth(i),e.SetBboxChanged())},SetFlipped(t){const e=this.GetWorldInfo(),n=e.GetHeight(),i=Math.abs(n)*(0===t?-1:1);n!==i&&(e.SetHeight(i),e.SetBboxChanged())},SetScale(t){const e=this._currentAnimationFrame.GetImageInfo(),n=this.GetWorldInfo(),i=n.GetWidth()<0?-1:1,r=n.GetHeight()<0?-1:1,a=e.GetWidth()*t*i,s=e.GetHeight()*t*r;n.GetWidth()===a&&n.GetHeight()===s||(n.SetSize(a,s),n.SetBboxChanged())},async LoadURL(e,n,i){const r=this._currentAnimationFrame.GetImageInfo(),a=this.GetWorldInfo(),s=this._runtime,o=this._sdkType;if(r.GetURL()===e)return 0===n&&(a.SetSize(r.GetWidth(),r.GetHeight()),a.SetBboxChanged()),void this.Trigger(t.Plugins.Sprite.Cnds.OnURLLoaded);const m=t.New(t.ImageInfo);try{if(await m.LoadDynamicAsset(s,e),!m.IsLoaded())throw new Error("image failed to load");if(this.WasReleased())return void m.Release();await m.LoadStaticTexture(s.GetRenderer(),{sampling:s.GetSampling()})}catch(e){return console.error("Load image from URL failed: ",e),void(this.WasReleased()||this.Trigger(t.Plugins.Sprite.Cnds.OnURLFailed))}this.WasReleased()?m.Release():(r.ReplaceWith(m),o._UpdateAllCurrentTexture(),o.GetObjectClass().Dispatcher().dispatchEvent(new t.Event("animationframeimagechange")),s.UpdateRender(),0===n&&(a.SetSize(r.GetWidth(),r.GetHeight()),a.SetBboxChanged()),await this.TriggerAsync(t.Plugins.Sprite.Cnds.OnURLLoaded))},SetCollisions(t){this.GetWorldInfo().SetCollisionEnabled(t)},SetSolidCollisionFilter(t,e){this.GetWorldInfo().SetSolidCollisionFilter(0===t,e)},SetEffect(t){this.GetWorldInfo().SetBlendMode(t),this._runtime.UpdateRender()}}}self.C3.Plugins.Sprite.Exps={AnimationFrame(){return this._GetAnimFrame()},AnimationFrameTag(){return this._GetAnimFrameTag()},AnimationFrameCount(){return this._currentAnimation.GetFrameCount()},AnimationName(){return this._currentAnimation.GetName()},AnimationSpeed(){return this._GetAnimSpeed()},OriginalAnimationSpeed(){return this._currentAnimation.GetSpeed()},ImagePointX(t){return this.GetImagePoint(t)[0]},ImagePointY(t){return this.GetImagePoint(t)[1]},ImagePointZ(t){return this.GetImagePoint(t)[2]},ImagePointCount(){return this.GetImagePointCount()},ImageWidth(){return this.GetCurrentImageInfo().GetWidth()},ImageHeight(){return this.GetCurrentImageInfo().GetHeight()},PolyPointXAt(t){return this.GetCollisionPolyPoint(t)[0]},PolyPointYAt(t){return this.GetCollisionPolyPoint(t)[1]},PolyPointCount(){return this.GetCollisionPolyPointCount()}};
}

// scripts/plugins/TiledBg/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.TiledBg=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const t=self.C3;function WrapModeToStr(e){switch(e){case 0:return"clamp-to-edge";case 1:return"repeat";case 2:return"mirror-repeat"}return"repeat"}t.Plugins.TiledBg.Type=class extends t.SDKTypeBase{constructor(e,t){super(e),this._wrapX="repeat",this._wrapY="repeat",t&&(this._wrapX=WrapModeToStr(t[0]),this._wrapY=WrapModeToStr(t[1]))}Release(){super.Release()}OnCreate(){this.GetImageInfo().LoadAsset(this._runtime)}LoadTextures(e){return this.GetImageInfo().LoadStaticTexture(e,{sampling:this._runtime.GetSampling(),wrapX:this._wrapX,wrapY:this._wrapY})}ReleaseTextures(){this.GetImageInfo().ReleaseTexture()}GetWrapModeX(){return this._wrapX}GetWrapModeY(){return this._wrapY}}}{const i=self.C3,a=self.C3X,n=0,s=4,l=5,r=6,g=7,m=8,d=9,h=10,o=11,_=12,u=13,R=14,f=i.New(i.Rect),S=i.New(i.Quad),I=i.New(i.Rect),c=i.New(i.Quad);i.Plugins.TiledBg.Instance=class extends i.SDKWorldInstanceBase{constructor(e,t){super(e),this._imageOffsetX=0,this._imageOffsetY=0,this._imageScaleX=1,this._imageScaleY=1,this._imageAngle=0,this._enableTileRandomization=!1,this._tileXRandom=0,this._tileYRandom=0,this._tileAngleRandom=0,this._tileBlendMarginX=0,this._tileBlendMarginY=0,this._ownImageInfo=null,t&&(this.GetWorldInfo().SetVisible(!!t[n]),this._imageOffsetX=t[s],this._imageOffsetY=t[l],this._imageScaleX=t[r],this._imageScaleY=t[g],this._imageAngle=i.toRadians(t[m]),this._enableTileRandomization=!!t[d],this._tileXRandom=t[h],this._tileYRandom=t[o],this._tileAngleRandom=t[_],this._tileBlendMarginX=t[u],this._tileBlendMarginY=t[R])}Release(){this._ReleaseOwnImage(),super.Release()}_ReleaseOwnImage(){this._ownImageInfo&&(this._ownImageInfo.Release(),this._ownImageInfo=null)}CalculateTextureCoordsFor3DFace(e,t,i){const a=this.GetCurrentImageInfo(),n=a.GetWidth(),s=a.GetHeight(),l=this._imageOffsetX/n,r=this._imageOffsetY/s,g=this._imageAngle;I.set(0,0,e/(n*this._imageScaleX),t/(s*this._imageScaleY)),I.offset(-l,-r),0===g?i.setFromRect(I):i.setFromRotatedRect(I,-g)}SetTilingShaderProgram(e,t=!0){if(this._enableTileRandomization){const t=this.GetCurrentImageInfo();e.SetTileRandomizationMode(),e.SetTileRandomizationInfo(t.GetWidth()*this._imageScaleX,t.GetHeight()*this._imageScaleY,this._tileXRandom,this._tileYRandom,this._tileAngleRandom,this._tileBlendMarginX,this._tileBlendMarginY)}else t&&e.SetTextureFillMode()}Draw(e){const t=this.GetCurrentImageInfo(),i=t.GetTexture();if(null===i)return;this.SetTilingShaderProgram(e),e.SetTexture(i);const a=t.GetWidth(),n=t.GetHeight();let s=this._imageOffsetX/a,l=this._imageOffsetY/n;0!==this._imageAngle||this._enableTileRandomization||("repeat"===this.GetSdkType().GetWrapModeX()&&(s%=1),"repeat"===this.GetSdkType().GetWrapModeY()&&(l%=1));const r=this.GetWorldInfo();I.set(0,0,r.GetWidth()/(a*this._imageScaleX),r.GetHeight()/(n*this._imageScaleY)),I.offset(-s,-l),r.HasMesh()?this._DrawMesh(r,e):this._DrawStandard(r,e)}_DrawStandard(e,t){let i=e.GetBoundingQuad();this._runtime.IsPixelRoundingEnabled()&&(i=e.PixelRoundQuad(i)),0===this._imageAngle?t.Quad3(i,I):(c.setFromRotatedRect(I,-this._imageAngle),t.Quad4(i,c))}_DrawMesh(e,t){const i=e.GetTransformedMesh();if(e.IsMeshChanged()){e.CalculateBbox(f,S,!1);let t=S;this._runtime.IsPixelRoundingEnabled()&&(t=e.PixelRoundQuad(t));let a=I;0!==this._imageAngle&&(c.setFromRotatedRect(I,-this._imageAngle),a=c),i.CalculateTransformedMesh(e.GetSourceMesh(),t,a),e.SetMeshChanged(!1)}i.Draw(t)}GetCurrentImageInfo(){return this._ownImageInfo||this._objectClass.GetImageInfo()}IsOriginalSizeKnown(){return!0}GetTexture(){return this.GetCurrentImageInfo().GetTexture()}_SetMeshChanged(){this.GetWorldInfo().SetMeshChanged(!0)}_SetImageOffsetX(e){this._imageOffsetX!==e&&(this._imageOffsetX=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageOffsetX(){return this._imageOffsetX}_SetImageOffsetY(e){this._imageOffsetY!==e&&(this._imageOffsetY=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageOffsetY(){return this._imageOffsetY}_SetImageScaleX(e){this._imageScaleX!==e&&(this._imageScaleX=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageScaleX(){return this._imageScaleX}_SetImageScaleY(e){this._imageScaleY!==e&&(this._imageScaleY=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageScaleY(){return this._imageScaleY}_SetImageAngle(e){this._imageAngle!==e&&(this._imageAngle=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageAngle(){return this._imageAngle}_SetTileRandomizationEnabled(e){e=!!e,this._enableTileRandomization!==e&&(this._enableTileRandomization=e,this._runtime.UpdateRender())}_IsTileRandomizationEnabled(){return this._enableTileRandomization}_SetTileXRandom(e){this._tileXRandom!==e&&(this._tileXRandom=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileXRandom(){return this._tileXRandom}_SetTileYRandom(e){this._tileYRandom!==e&&(this._tileYRandom=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileYRandom(){return this._tileYRandom}_SetTileAngleRandom(e){this._tileAngleRandom!==e&&(this._tileAngleRandom=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileAngleRandom(){return this._tileAngleRandom}_SetTileBlendMarginX(e){this._tileBlendMarginX!==e&&(this._tileBlendMarginX=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileBlendMarginX(){return this._tileBlendMarginX}_SetTileBlendMarginY(e){this._tileBlendMarginY!==e&&(this._tileBlendMarginY=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileBlendMarginY(){return this._tileBlendMarginY}SaveToJson(){const e={};return 0!==this._imageOffsetX&&(e["iox"]=this._imageOffsetX),0!==this._imageOffsetY&&(e["ioy"]=this._imageOffsetY),1!==this._imageScaleX&&(e["isx"]=this._imageScaleX),1!==this._imageScaleY&&(e["isy"]=this._imageScaleY),0!==this._imageAngle&&(e["ia"]=this._imageAngle),this._enableTileRandomization&&(e["tr"]=!0),1!==this._tileXRandom&&(e["trx"]=this._tileXRandom),1!==this._tileYRandom&&(e["try"]=this._tileYRandom),1!==this._tileAngleRandom&&(e["tra"]=this._tileAngleRandom),.1!==this._tileBlendMarginX&&(e["trbmx"]=this._tileBlendMarginX),.1!==this._tileBlendMarginY&&(e["trbmy"]=this._tileBlendMarginY),e}LoadFromJson(e){this._imageOffsetX=e["iox"]||0,this._imageOffsetY=e["ioy"]||0,this._imageScaleX=e.hasOwnProperty("isx")?e["isx"]:1,this._imageScaleY=e.hasOwnProperty("isy")?e["isy"]:1,this._imageAngle=e["ia"]||0,this._enableTileRandomization=!!e["tr"],this._tileXRandom=e.hasOwnProperty("trx")?e["trx"]:1,this._tileYRandom=e.hasOwnProperty("try")?e["try"]:1,this._tileAngleRandom=e.hasOwnProperty("tra")?e["tra"]:1,this._tileBlendMarginX=e.hasOwnProperty("trbmx")?e["trbmx"]:.1,this._tileBlendMarginY=e.hasOwnProperty("trbmy")?e["trbmy"]:.1}GetDebuggerProperties(){const e="plugins.tiledbg.properties";return[{title:e+".image-transform.name",properties:[{name:e+".image-offset-x.name",value:this._GetImageOffsetX(),onedit:e=>this._SetImageOffsetX(e)},{name:e+".image-offset-y.name",value:this._GetImageOffsetY(),onedit:e=>this._SetImageOffsetY(e)},{name:e+".image-scale-x.name",value:100*this._GetImageScaleX(),onedit:e=>this._SetImageScaleX(e/100)},{name:e+".image-scale-y.name",value:100*this._GetImageScaleY(),onedit:e=>this._SetImageScaleY(e/100)},{name:e+".image-angle.name",value:i.toDegrees(this._GetImageAngle()),onedit:e=>this._SetImageAngle(i.toRadians(e))}]},{title:e+".tile-randomization.name",properties:[{name:e+".enable-tile-randomization.name",value:this._IsTileRandomizationEnabled(),onedit:e=>this._SetTileRandomizationEnabled(e)},{name:e+".x-random.name",value:100*this._GetTileXRandom(),onedit:e=>this._SetTileXRandom(e/100)},{name:e+".y-random.name",value:100*this._GetTileYRandom(),onedit:e=>this._SetTileYRandom(e/100)},{name:e+".angle-random.name",value:100*this._GetTileAngleRandom(),onedit:e=>this._SetTileAngleRandom(e/100)},{name:e+".blend-margin-x.name",value:100*this._GetTileBlendMarginX(),onedit:e=>this._SetTileBlendMarginX(e/100)},{name:e+".blend-margin-y.name",value:100*this._GetTileBlendMarginY(),onedit:e=>this._SetTileBlendMarginY(e/100)}]}]}GetPropertyValueByIndex(e){switch(e){case s:return this._GetImageOffsetX();case l:return this._GetImageOffsetY();case r:return this._GetImageScaleX();case g:return this._GetImageScaleY();case m:return this._GetImageAngle();case d:return this._IsTileRandomizationEnabled();case h:return this._GetTileXRandom();case o:return this._GetTileYRandom();case _:return this._GetTileAngleRandom();case u:return this._GetTileBlendMarginX();case R:return this._GetTileBlendMarginY()}}SetPropertyValueByIndex(e,t){switch(e){case s:this._SetImageOffsetX(t);break;case l:this._SetImageOffsetY(t);break;case r:this._SetImageScaleX(t);break;case g:this._SetImageScaleY(t);break;case m:this._SetImageAngle(t);break;case d:this._SetTileRandomizationEnabled(!!t);break;case h:this._SetTileXRandom(t);break;case o:this._SetTileYRandom(t);break;case _:this._SetTileAngleRandom(t);break;case u:this._SetTileBlendMarginX(t);break;case R:this._SetTileBlendMarginY(t)}}GetScriptInterfaceClass(){return self.ITiledBackgroundInstance}};const T=new WeakMap;self.ITiledBackgroundInstance=class extends self.IWorldInstance{constructor(){super(),T.set(this,self.IInstance._GetInitInst().GetSdkInstance())}set imageOffsetX(e){a.RequireFiniteNumber(e),T.get(this)._SetImageOffsetX(e)}get imageOffsetX(){return T.get(this)._GetImageOffsetX()}set imageOffsetY(e){a.RequireFiniteNumber(e),T.get(this)._SetImageOffsetY(e)}get imageOffsetY(){return T.get(this)._GetImageOffsetY()}setImageOffset(e,t){a.RequireFiniteNumber(e),a.RequireFiniteNumber(t);const i=T.get(this);i._SetImageOffsetX(e),i._SetImageOffsetY(t)}getImageOffset(){const e=T.get(this);return[e._GetImageOffsetX(),e._GetImageOffsetY()]}set imageScaleX(e){a.RequireFiniteNumber(e),T.get(this)._SetImageScaleX(e)}get imageScaleX(){return T.get(this)._GetImageScaleX()}set imageScaleY(e){a.RequireFiniteNumber(e),T.get(this)._SetImageScaleY(e)}get imageScaleY(){return T.get(this)._GetImageScaleY()}setImageScale(e,t){a.RequireFiniteNumber(e),a.RequireFiniteNumber(t);const i=T.get(this);i._SetImageScaleX(e),i._SetImageScaleY(t)}getImageScale(){const e=T.get(this);return[e._GetImageScaleX(),e._GetImageScaleY()]}set imageAngle(e){a.RequireFiniteNumber(e),T.get(this)._SetImageAngle(e)}get imageAngle(){return T.get(this)._GetImageAngle()}set imageAngleDegrees(e){a.RequireFiniteNumber(e),T.get(this)._SetImageAngle(i.toRadians(e))}get imageAngleDegrees(){return i.toDegrees(T.get(this)._GetImageAngle())}get imageWidth(){return T.get(this).GetCurrentImageInfo().GetWidth()}get imageHeight(){return T.get(this).GetCurrentImageInfo().GetHeight()}getImageSize(){const e=T.get(this).GetCurrentImageInfo();return[e.GetWidth(),e.GetHeight()]}set enableTileRandomization(e){T.get(this)._SetTileRandomizationEnabled(!!e)}get enableTileRandomization(){return T.get(this)._IsTileRandomizationEnabled()}set tileXRandom(e){a.RequireFiniteNumber(e),T.get(this)._SetTileXRandom(e)}get tileXRandom(){return T.get(this)._GetTileXRandom()}set tileYRandom(e){a.RequireFiniteNumber(e),T.get(this)._SetTileYRandom(e)}get tileYRandom(){return T.get(this)._GetTileYRandom()}setTileRandom(e,t){a.RequireFiniteNumber(e),a.RequireFiniteNumber(t);const i=T.get(this);i._SetTileXRandom(e),i._SetTileYRandom(t)}getTileRandom(){const e=T.get(this);return[e._GetTileXRandom(),e._GetTileYRandom()]}set tileAngleRandom(e){a.RequireFiniteNumber(e),T.get(this)._SetTileAngleRandom(e)}get tileAngleRandom(){return T.get(this)._GetTileAngleRandom()}set tileBlendMarginX(e){a.RequireFiniteNumber(e),T.get(this)._SetTileBlendMarginX(e)}get tileBlendMarginX(){return T.get(this)._GetTileBlendMarginX()}set tileBlendMarginY(e){a.RequireFiniteNumber(e),T.get(this)._SetTileBlendMarginY(e)}get tileBlendMarginY(){return T.get(this)._GetTileBlendMarginY()}setTileBlendMargin(e,t){a.RequireFiniteNumber(e),a.RequireFiniteNumber(t);const i=T.get(this);i._SetTileBlendMarginX(e),i._SetTileBlendMarginY(t)}getTileBlendMargin(){const e=T.get(this);return[e._GetTileBlendMarginX(),e._GetTileBlendMarginY()]}async replaceImage(e){a.RequireInstanceOf(e,Blob);const t=T.get(this),n=t.GetRuntime(),s=i.New(i.ImageInfo);s.LoadDynamicBlobAsset(n,e),await s.LoadStaticTexture(n.GetRenderer(),{sampling:n.GetSampling(),wrapX:t.GetSdkType().GetWrapModeX(),wrapY:t.GetSdkType().GetWrapModeY()}),t.WasReleased()?s.Release():(t._ReleaseOwnImage(),t._ownImageInfo=s,n.UpdateRender())}}}self.C3.Plugins.TiledBg.Cnds={OnURLLoaded:()=>!0,OnURLFailed:()=>!0,IsTileRandomizationEnabled(){return this._IsTileRandomizationEnabled()}};{const G=self.C3;G.Plugins.TiledBg.Acts={SetImageOffsetX(e){this._SetImageOffsetX(e)},SetImageOffsetY(e){this._SetImageOffsetY(e)},SetImageScaleX(e){this._SetImageScaleX(e/100)},SetImageScaleY(e){this._SetImageScaleY(e/100)},SetImageAngle(e){this._SetImageAngle(G.toRadians(e))},SetTileRandomizationEnabled(e){this._SetTileRandomizationEnabled(e)},SetTilePosRandom(e,t){this._SetTileXRandom(e/100),this._SetTileYRandom(t/100)},SetTileAngleRandom(e){this._SetTileAngleRandom(e/100)},SetTileBlendMargin(e,t){this._SetTileBlendMarginX(e/100),this._SetTileBlendMarginY(t/100)},SetEffect(e){this.GetWorldInfo().SetBlendMode(e),this._runtime.UpdateRender()},async LoadURL(e,t){if(this._ownImageInfo&&this._ownImageInfo.GetURL()===e)return;const i=this._runtime,a=G.New(G.ImageInfo);try{if(await a.LoadDynamicAsset(i,e,!0),!a.IsLoaded())throw new Error("image failed to load");if(this.WasReleased())return a.Release(),null;if(!await a.LoadStaticTexture(i.GetRenderer(),{sampling:i.GetSampling(),wrapX:this.GetSdkType().GetWrapModeX(),wrapY:this.GetSdkType().GetWrapModeY()}))return}catch(e){return console.error("Load image from URL failed: ",e),void(this.WasReleased()||this.Trigger(G.Plugins.TiledBg.Cnds.OnURLFailed))}this.WasReleased()?a.Release():(this._ReleaseOwnImage(),this._ownImageInfo=a,i.UpdateRender(),await this.TriggerAsync(G.Plugins.TiledBg.Cnds.OnURLLoaded))}}}{const X=self.C3;X.Plugins.TiledBg.Exps={ImageWidth(){return this.GetCurrentImageInfo().GetWidth()},ImageHeight(){return this.GetCurrentImageInfo().GetHeight()},ImageOffsetX(){return this._imageOffsetX},ImageOffsetY(){return this._imageOffsetY},ImageScaleX(){return 100*this._imageScaleX},ImageScaleY(){return 100*this._imageScaleY},ImageAngle(){return X.toDegrees(this._imageAngle)},TileXRandom(){return 100*this._GetTileXRandom()},TileYRandom(){return 100*this._GetTileYRandom()},TileAngleRandom(){return 100*this._GetTileAngleRandom()},TileBlendMarginX(){return 100*this._GetTileBlendMarginX()},TileBlendMarginY(){return 100*this._GetTileBlendMarginY()}}}
}

// scripts/plugins/Spritefont2/c3runtime/runtime.js
{
{const t=self.C3;t.Plugins.Spritefont2=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3;t.Plugins.Spritefont2.Type=class extends t.SDKTypeBase{constructor(e){super(e),this._spriteFont=t.New(self.SpriteFont)}Release(){super.Release()}OnCreate(){this.GetImageInfo().LoadAsset(this._runtime)}LoadTextures(t){return this.GetImageInfo().LoadStaticTexture(t,{sampling:this._runtime.GetSampling()})}ReleaseTextures(){this.GetImageInfo().ReleaseTexture()}GetSpriteFont(){return this._spriteFont}UpdateSettings(t,e,i,r){const s=this.GetImageInfo(),n=this._spriteFont;n.SetWidth(s.GetWidth()),n.SetHeight(s.GetHeight()),n.SetCharacterWidth(t),n.SetCharacterHeight(e),n.SetCharacterSet(i),n.SetSpacingData(r),n.UpdateCharacterMap()}}}{const t=self.C3,e=self.C3X,i=t.New(t.Vector2),r=0,s=1,n=2,a=3,h=4,c=5,o=6,_=7,g=8,p=9,S=10,l=11,d=14,T=["left","center","right"],u=["top","center","bottom"],G=["word","cjk","character"];t.Plugins.Spritefont2.Instance=class extends t.SDKWorldInstanceBase{constructor(e,i){super(e),this._text="",this._enableBBcode=!0,this._characterWidth=16,this._characterHeight=16,this._characterSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,;:?!-_~#\"'&()[]|`\\/@°+=*$£€<>";let r="";if(this._characterScale=1,this._characterSpacing=0,this._lineHeight=0,this._horizontalAlign=0,this._verticalAlign=0,this._wrapMode="word",this._needsTextLayout=!0,this._readAloud=!1,this._screenReaderText=null,this._spriteFontText=null,this._typewriterStartTime=-1,this._typewriterEndTime=-1,this._typewriterLength=0,i){this._text=i[0],this._enableBBcode=i[1],this._characterWidth=i[2],this._characterHeight=i[3],this._characterSet=i[4],r=i[5],this._characterScale=i[6],this._characterSpacing=i[7],this._lineHeight=i[8],this._horizontalAlign=i[9],this._verticalAlign=i[10],this._wrapMode=G[i[11]];this.GetWorldInfo().SetVisible(i[12]),this._readAloud=!!i[d]}this._sdkType.UpdateSettings(this._characterWidth,this._characterHeight,this._characterSet,r),this._spriteFontText=t.New(self.SpriteFontText,this._sdkType.GetSpriteFont());const s=this.GetWorldInfo();this._spriteFontText.SetSize(s.GetWidth(),s.GetHeight()),this._UpdateSettings(),this._UpdateScreenReaderText(),this._inst.SetMustMitigateZFighting()}Release(){this._CancelTypewriter(),this._screenReaderText&&(this._screenReaderText.Release(),this._screenReaderText=null),this._spriteFontText.Release(),this._spriteFontText=null,super.Release()}_UpdateSettings(){const t=this._spriteFontText;t&&(t.SetBBCodeEnabled(this._enableBBcode),t.SetText(this._text),t.SetWordWrapMode(this._wrapMode),t.SetHorizontalAlign(T[this._horizontalAlign]),t.SetVerticalAlign(u[this._verticalAlign]),t.SetSpacing(this._characterSpacing),t.SetLineHeight(this._lineHeight))}_UpdateTextSize(){const t=this.GetWorldInfo();this._spriteFontText.SetSize(t.GetWidth(),t.GetHeight()),this._spriteFontText.SetScale(this._characterScale)}_UpdateScreenReaderText(){if(this._readAloud){let e=this._text;this._enableBBcode&&(e=t.BBString.StripAnyTags(e)),this._screenReaderText?this._screenReaderText.SetText(e):this._screenReaderText=t.New(t.ScreenReaderText,this._runtime,e)}else this._screenReaderText&&(this._screenReaderText.Release(),this._screenReaderText=null)}Draw(t){const e=this._objectClass.GetImageInfo(),i=e.GetTexture();if(!i)return;t.SetTexture(i);const r=this.GetWorldInfo();let s=r.GetBoundingQuad();const n=this._spriteFontText;n.SetScale(this._characterScale),n.SetSceneGraphScale(r.GetSceneGraphScale()),this._runtime.IsPixelRoundingEnabled()&&(s=r.PixelRoundQuad(s)),n.SetSize(r.GetWidth(),r.GetHeight()),n.GetSpriteFont().SetTexRect(e.GetTexRect()),n.SetColor(r.GetUnpremultipliedColor()),n.Draw(t,s.getTlx(),s.getTly(),r.GetAngle()),this._needsTextLayout=!1}SaveToJson(){const t={"t":this._text,"ebbc":this._enableBBcode,"csc":this._characterScale,"csp":this._characterSpacing,"lh":this._lineHeight,"ha":this._horizontalAlign,"va":this._verticalAlign,"w":this._wrapMode,"cw":this._sdkType.GetSpriteFont().GetCharacterWidth(),"ch":this._sdkType.GetSpriteFont().GetCharacterHeight(),"cs":this._sdkType.GetSpriteFont().GetCharacterSet(),"sd":this._sdkType.GetSpriteFont().GetSpacingData()};return-1!==this._typewriterEndTime&&(t["tw"]={"st":this._typewriterStartTime,"en":this._typewriterEndTime,"l":this._typewriterLength}),t}LoadFromJson(t){if(this._CancelTypewriter(),this._text=t["t"],this._enableBBcode=t["ebbc"],this._characterScale=t["csc"],this._characterSpacing=t["csp"],this._lineHeight=t["lh"],this._horizontalAlign=t["ha"],this._verticalAlign=t["va"],t.hasOwnProperty("w")){const e=t["w"];this._wrapMode="boolean"==typeof e?e?"word":"character":e}else this._wrapMode="word";if(t.hasOwnProperty("tw")){const e=t["tw"];this._typewriterStartTime=e["st"],this._typewriterEndTime=e["en"],this._typewriterLength=t["l"]}const e=this._sdkType.GetSpriteFont();e.SetCharacterWidth(t["cw"]),e.SetCharacterHeight(t["ch"]),e.SetCharacterSet(t["cs"]),e.SetSpacingData(t["sd"]),this._UpdateSettings(),this._UpdateScreenReaderText(),-1!==this._typewriterEndTime&&this._StartTicking()}GetPropertyValueByIndex(t){switch(t){case r:return this.GetText();case s:return this._enableBBcode;case n:return this._sdkType.GetSpriteFont().GetCharacterWidth();case a:return this._sdkType.GetSpriteFont().GetCharacterHeight();case h:return this._sdkType.GetSpriteFont().GetCharacterSet();case c:return this._sdkType.GetSpriteFont().GetSpacingData();case o:return this._GetScale();case _:return this._GetCharacterSpacing();case g:return this._GetLineHeight();case p:return this._GetHAlign();case S:return this._GetVAlign();case l:return this._GetWrapMode()}}SetPropertyValueByIndex(t,e){switch(t){case r:this._SetText(e);break;case s:if(this._enableBBcode===!!e)return;this._enableBBcode=!!e,this._UpdateSettings();break;case n:this._sdkType.GetSpriteFont().SetCharacterWidth(e);break;case a:this._sdkType.GetSpriteFont().SetCharacterHeight(e);break;case h:this._sdkType.GetSpriteFont().SetCharacterSet(e);break;case c:this._sdkType.GetSpriteFont().SetSpacingData(e);break;case o:this._SetScale(e);break;case _:this._SetCharacterSpacing(e);break;case g:this._SetLineHeight(e);break;case p:this._SetHAlign(e);break;case S:this._SetVAlign(e);break;case l:this._SetWrapMode(e)}}_SetText(t){this._text!==t&&(this._text=t,this._spriteFontText.SetText(t),this._UpdateScreenReaderText(),this._runtime.UpdateRender())}GetText(){return this._text}_StartTypewriter(e,i){this._SetText(e),this._typewriterStartTime=this._runtime.GetWallTime(),this._typewriterEndTime=this._typewriterStartTime+i/this.GetInstance().GetActiveTimeScale(),this._typewriterLength=t.CountGraphemes(t.BBString.StripAnyTags(e)),this._spriteFontText.SetDrawMaxCharacterCount(0),this._StartTicking()}_CancelTypewriter(){this._typewriterStartTime=-1,this._typewriterEndTime=-1,this._typewriterLength=0,this._spriteFontText.SetDrawMaxCharacterCount(-1),this._StopTicking()}_FinishTypewriter(){-1!==this._typewriterEndTime&&(this._CancelTypewriter(),this.Trigger(t.Plugins.Spritefont2.Cnds.OnTypewriterTextFinished),this._runtime.UpdateRender())}_SetScale(t){this._characterScale!==t&&(this._characterScale=t,this._spriteFontText.SetScale(this._characterScale),this._runtime.UpdateRender())}_GetScale(){return this._characterScale}_SetCharacterSpacing(t){this._characterSpacing!==t&&(this._characterSpacing=t,this._spriteFontText.SetSpacing(this._characterSpacing),this._runtime.UpdateRender())}_GetCharacterSpacing(){return this._characterSpacing}_SetLineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this._spriteFontText.SetLineHeight(this._lineHeight),this._runtime.UpdateRender())}_GetLineHeight(){return this._lineHeight}_SetHAlign(t){this._horizontalAlign!==t&&(this._horizontalAlign=t,this._UpdateSettings(),this._runtime.UpdateRender())}_GetHAlign(){return this._horizontalAlign}_SetVAlign(t){this._verticalAlign!==t&&(this._verticalAlign=t,this._UpdateSettings(),this._runtime.UpdateRender())}_GetVAlign(){return this._verticalAlign}_SetWrapModeByIndex(t){this._SetWrapMode(G[t])}_SetWrapMode(t){this._wrapMode!==t&&(this._wrapMode=t,this._UpdateSettings(),this._runtime.UpdateRender())}_GetWrapMode(){return this._wrapMode}_SetReadAloud(t){this._readAloud=!!t,this._UpdateScreenReaderText()}_IsReadAloud(){return this._readAloud}_GetTextWidth(){return this._UpdateTextSize(),this._spriteFontText.GetTextWidth()}_GetTextHeight(){return this._UpdateTextSize(),this._spriteFontText.GetTextHeight()}_GetTagAtPosition(t,e){this._UpdateTextSize();const r=this.GetWorldInfo();i.set(t-r.GetX(),e-r.GetY()),i.rotate(-r.GetAngle()),i.offset(r.GetWidth()*r.GetOriginX(),r.GetHeight()*r.GetOriginY());const s=this._spriteFontText.HitTestFragment(i.getX(),i.getY());if(s){const t=s.GetStyleTag("tag");if(t)return t.param}return""}_HasTagAtPosition(e,i,r){const s=this._GetTagAtPosition(i,r);return s&&t.equalsNoCase(e,s)}_GetTagPosition(t,e){this._UpdateTextSize(),e=Math.floor(e);const r=this._spriteFontText.FindFragmentWithTag(t,e);if(!r)return null;const s=this.GetWorldInfo();return i.set(r.GetPosX(),r.GetPosY()),i.offset(-s.GetWidth()*s.GetOriginX(),-s.GetHeight()*s.GetOriginY()),i.rotate(s.GetAngle()),i.offset(s.GetX(),s.GetY()),{x:i.getX(),y:i.getY(),width:r.GetWidth(),height:r.GetHeight()}}_GetTagCount(t){return this._UpdateTextSize(),this._spriteFontText.CountFragmentsWithTag(t)}Tick(){const e=this._runtime.GetWallTime();if(e>=this._typewriterEndTime)this._CancelTypewriter(),this.Trigger(t.Plugins.Spritefont2.Cnds.OnTypewriterTextFinished),this._runtime.UpdateRender();else{let i=t.relerp(this._typewriterStartTime,this._typewriterEndTime,e,0,this._typewriterLength);i=Math.floor(i),i!==this._spriteFontText.GetDrawMaxCharacterCount()&&(this._spriteFontText.SetDrawMaxCharacterCount(i),this._runtime.UpdateRender())}}GetDebuggerProperties(){const t="plugins.spritefont2";return[{title:t+".name",properties:[{name:t+".properties.text.name",value:this.GetText(),onedit:t=>this._SetText(t)},{name:t+".properties.scale.name",value:this._GetScale(),onedit:t=>this._SetScale(t)},{name:t+".properties.character-spacing.name",value:this._GetCharacterSpacing(),onedit:t=>this._SetCharacterSpacing(t)},{name:t+".properties.line-height.name",value:this._GetLineHeight(),onedit:t=>this._SetLineHeight(t)}]}]}GetScriptInterfaceClass(){return self.ISpriteFontInstance}};const x=new WeakMap,w=new Map([["left",0],["center",1],["right",2]]),y=new Map([["top",0],["center",1],["bottom",2]]);self.ISpriteFontInstance=class extends self.IWorldInstance{constructor(){super(),x.set(this,self.IInstance._GetInitInst().GetSdkInstance())}get text(){return x.get(this).GetText()}set text(t){e.RequireString(t);const i=x.get(this);i._CancelTypewriter(),i._SetText(t)}typewriterText(t,i){e.RequireString(t),e.RequireFiniteNumber(i);const r=x.get(this);r._CancelTypewriter(),r._StartTypewriter(t,i)}typewriterFinish(){x.get(this)._FinishTypewriter()}set characterScale(t){e.RequireFiniteNumber(t),x.get(this)._SetScale(t)}get characterScale(){return x.get(this)._GetScale()}set characterSpacing(t){e.RequireFiniteNumber(t),x.get(this)._SetCharacterSpacing(t)}get characterSpacing(){return x.get(this)._GetCharacterSpacing()}set lineHeight(t){e.RequireFiniteNumber(t),x.get(this)._SetLineHeight(t)}get lineHeight(){return x.get(this)._GetLineHeight()}set horizontalAlign(t){e.RequireString(t);const i=w.get(t);if(void 0===i)throw new Error("invalid mode");x.get(this)._SetHAlign(i)}get horizontalAlign(){return T[x.get(this)._GetHAlign()]}set verticalAlign(t){e.RequireString(t);const i=y.get(t);if(void 0===i)throw new Error("invalid mode");x.get(this)._SetVAlign(i)}get verticalAlign(){return u[x.get(this)._GetVAlign()]}set wordWrapMode(t){if(!G.includes(t))throw new Error("invalid mode");x.get(this)._SetWrapMode(t)}get wordWrapMode(){return x.get(this)._GetWrapMode()}set readAloud(t){x.get(this)._SetReadAloud(!!t)}get readAloud(){return x.get(this)._IsReadAloud()}get textWidth(){return x.get(this)._GetTextWidth()}get textHeight(){return x.get(this)._GetTextHeight()}getTextSize(){const t=x.get(this);return[t._GetTextWidth(),t._GetTextHeight()]}hasTagAtPosition(t,i,r){return e.RequireString(t),e.RequireFiniteNumber(i),e.RequireFiniteNumber(r),x.get(this)._HasTagAtPosition(t,i,r)}getTagAtPosition(t,i){return e.RequireFiniteNumber(t),e.RequireFiniteNumber(i),x.get(this)._GetTagAtPosition(t,i)}getTagPositionAndSize(t,i=0){return e.RequireString(t),e.RequireFiniteNumber(i),x.get(this)._GetTagPosition(t,i)}getTagCount(t){return e.RequireString(t),x.get(this)._GetTagCount(t)}}}{const t=self.C3;t.Plugins.Spritefont2.Cnds={CompareText(e,i){return i?this._text===e:t.equalsNoCase(this._text,e)},IsRunningTypewriterText(){return-1!==this._typewriterEndTime},OnTypewriterTextFinished:()=>!0,HasTagAtPosition(t,e,i){return this._HasTagAtPosition(t,e,i)}}}self.C3.Plugins.Spritefont2.Acts={SetText(t){this._CancelTypewriter(),"number"==typeof t&&t<1e9&&(t=Math.round(1e10*t)/1e10),this._SetText(t.toString())},AppendText(t){this._CancelTypewriter(),"number"==typeof t&&t<1e9&&(t=Math.round(1e10*t)/1e10),(t=t.toString())&&this._SetText(this._text+t)},TypewriterText(t,e){this._CancelTypewriter(),"number"==typeof t&&t<1e9&&(t=Math.round(1e10*t)/1e10),this._StartTypewriter(t.toString(),e)},TypewriterFinish(){this._FinishTypewriter()},SetScale(t){this._SetScale(t)},SetCharacterSpacing(t){this._SetCharacterSpacing(t)},SetLineHeight(t){this._SetLineHeight(t)},SetCharacterWidth(t,e){let i=!1;const r=this._sdkType.GetSpriteFont();for(const s of t)if(" "===s)r.SetSpaceWidth(e),i=!0;else{const t=r.GetCharacter(s);t&&(t.SetDisplayWidth(e),i=!0)}i&&r.SetCharacterWidthsChanged(),this._runtime.UpdateRender()},SetEffect(t){this.GetWorldInfo().SetBlendMode(t),this._runtime.UpdateRender()},SetHAlign(t){this._SetHAlign(t)},SetVAlign(t){this._SetVAlign(t)},SetWrapping(t){this._SetWrapModeByIndex(t)},SetReadAloud(t){this._SetReadAloud(t)}};{const t=self.C3;t.Plugins.Spritefont2.Exps={CharacterWidth(t){const e=this._sdkType.GetSpriteFont().GetCharacter(t);return e?e.GetDisplayWidth():this._sdkType.GetSpriteFont().GetCharacterWidth()},CharacterHeight(){return this._characterHeight},CharacterScale(){return this._characterScale},CharacterSpacing(){return this._characterSpacing},LineHeight(){return this._lineHeight},Text(){return this._text},PlainText(){return this._enableBBcode?t.BBString.StripAnyTags(this._text):this._text},TextWidth(){return this._GetTextWidth()},TextHeight(){return this._GetTextHeight()},TagAtPosition(t,e){return this._GetTagAtPosition(t,e)},TagCount(t){return this._GetTagCount(t)},TagX(t,e){const i=this._GetTagPosition(t,e);return i?i.x:0},TagY(t,e){const i=this._GetTagPosition(t,e);return i?i.y:0},TagWidth(t,e){const i=this._GetTagPosition(t,e);return i?i.width:0},TagHeight(t,e){const i=this._GetTagPosition(t,e);return i?i.height:0}}}
}

// scripts/plugins/Spritefont2/spritefontCharacter.js
{
const C3=self.C3;self.SpriteFontCharacter=class{constructor(t,e,i,s){let h=t.GetCharacterWidth(),r=t.GetCharacterHeight();this._spriteFont=t,this._char=e,this._pxRect=new C3.Rect(i,s,i+h,s+r),this._texRect=new C3.Rect,this._displayWidth=-1,this._UpdateTexRect()}Release(){this._spriteFont=null,this._pxRect=null,this._texRect=null}_UpdateTexRect(){let t=this._spriteFont.GetWidth(),e=this._spriteFont.GetHeight();this._texRect.copy(this._pxRect),this._texRect.divide(t,e),this._texRect.lerpInto(this._spriteFont.GetTexRect())}GetSpriteFont(){return this._spriteFont}GetChar(){return this._char}GetTexRect(){return this._texRect}SetDisplayWidth(t){this._displayWidth=t}GetDisplayWidth(){return this._displayWidth<0?this._spriteFont.GetCharacterWidth():this._displayWidth}};
}

// scripts/plugins/Spritefont2/spritefontText.js
{
const C3=self.C3,tmpRect=new C3.Rect,tmpQuad=new C3.Quad,tmpColor=new C3.Color,VALID_HORIZ_ALIGNMENTS=new Set(["left","center","right"]),VALID_VERT_ALIGNMENTS=new Set(["top","center","bottom"]),VALID_WORD_WRAP_MODES=new Set(["word","cjk","character"]);function getOffsetParam(t,e){t=t.trim();const a=parseFloat(t);return isFinite(a)?t.endsWith("%")?e*a/100:a:0}let canvasColorCtx=null;function normalizeCssColorString(t){return canvasColorCtx||(canvasColorCtx=C3.CreateCanvas(32,32).getContext("2d")),canvasColorCtx.fillStyle="#FFFFFF",canvasColorCtx.fillStyle=t,canvasColorCtx.fillStyle}self.SpriteFontText=class{constructor(t){this._spriteFont=t,this._cssWidth=0,this._cssHeight=0,this._text="",this._isBBcodeEnabled=!1,this._bbString=null,this._wrappedText=C3.New(C3.WordWrap),this._wrapMode="word",this._wordWrapChanged=!1,this._textLayoutChanged=!1,this._horizontalAlign="left",this._verticalAlign="top",this._scale=1,this._sceneGraphScale=1,this._spacing=0,this._lineHeight=0,this._color=C3.New(C3.Color),this._drawMaxCharCount=-1,this._drawCharCount=0,this._measureTextCallback=t=>this._MeasureText(t),this._spriteFont._AddSpriteFontText(this)}Release(){this._spriteFont._RemoveSpriteFontText(this),this._color=null,this._measureTextCallback=null,this._wrappedText.Clear(),this._wrappedText=null,this._spriteFont=null,this._bbString=null}_MeasureText(t){if(t.IsIcon())return{width:0,height:0};const e=t.GetCharacterArray(),a=t.GetStyleTag("scale"),s=(a?parseFloat(a.param):this._scale)*this._sceneGraphScale,i=t.GetStyleTag("scalex"),r=(i?parseFloat(i.param):1)*s,o=t.GetStyleTag("scaley"),h=(o?parseFloat(o.param):1)*s,n=this._spriteFont.GetCharacterHeight()*h+this._lineHeight,l=this.GetSpriteFont(),c=l.GetCharacterWidth()*r,_=this.GetSpacing();if(l.HasAnyCustomWidths()){let t=0,a=0;for(const s of e){let e=c;const i=l.GetCharacter(s);i?e=i.GetDisplayWidth()*r:" "===s&&(e=l.GetSpaceWidth()*r),a+=e,++t}return{width:a+t*_,height:n}}{const t=e.length;return{width:c*t+Math.max(t,0)*_,height:n}}}_SetTextLayoutChanged(){this._textLayoutChanged=!0}_SetWordWrapChanged(){this._SetTextLayoutChanged(),this._wordWrapChanged=!0,this._wrappedText.Clear()}SetSize(t,e){t<=0||e<=0||this._cssWidth===t&&this._cssHeight===e||(this._cssWidth!==t?this._SetWordWrapChanged():this._SetTextLayoutChanged(),this._cssWidth=t,this._cssHeight=e)}SetDrawMaxCharacterCount(t){this._drawMaxCharCount=Math.floor(t)}GetDrawMaxCharacterCount(){return this._drawMaxCharCount}HitTestFragment(t,e){this._UpdateTextMeasurements();const a=this._wrappedText.GetLines();for(const s of a)if(e>s.GetPosY()&&e<s.GetPosY()+s.GetHeight())for(const e of s.fragments())if(t>=e.GetPosX()&&t<e.GetPosX()+e.GetWidth())return e;return null}*fragmentsWithTag(t){this._UpdateTextMeasurements();const e=this._wrappedText.GetLines();for(const a of e)for(const e of a.fragments()){const a=e.GetStyleTag("tag");a&&C3.equalsNoCase(a.param,t)&&(yield e)}}FindFragmentWithTag(t,e){for(const a of this.fragmentsWithTag(t)){if(0===e)return a;--e}return null}CountFragmentsWithTag(t){let e=0;for(const a of this.fragmentsWithTag(t))++e;return e}_UpdateTextMeasurements(){this._UpdateWordWrap(),this._UpdateTextLayout()}_UpdateWordWrap(){if(!this._wordWrapChanged)return;!this._isBBcodeEnabled||this._bbString&&this._bbString.toString()===this._text||(this._bbString=new C3.BBString(this._text,{noEscape:!0}));const t=-this.GetSpacing();this._wrappedText.WordWrap(this._isBBcodeEnabled?this._bbString.toFragmentList():this._text,this._measureTextCallback,this._cssWidth,this._wrapMode,t),this._wordWrapChanged=!1}_UpdateTextLayout(){this._textLayoutChanged&&(this._LayoutText(),this._textLayoutChanged=!1)}_LayoutText(){let t=0;const e=this._lineHeight,a=C3.cloneArray(this._wrappedText.GetLines());for(const t of a){t.SetPosX(NaN),t.SetPosY(NaN);for(const e of t.fragments())e.SetPosX(NaN),e.SetPosY(NaN)}const s=a.reduce(((t,e)=>t+e.GetHeight()),0)-e;"center"===this._verticalAlign?t=Math.max(Math.floor(this._cssHeight/2-s/2),0):"bottom"===this._verticalAlign&&(t=Math.floor(this._cssHeight-s));for(let s=0,i=a.length;s<i;++s){const i=a[s],r=i.GetHeight();if(s>0&&t>this._cssHeight-(r-e))break;t>=0&&this._LayoutTextLine(i,t),t+=r}}_LayoutTextLine(t,e){let a=0;"center"===this._horizontalAlign?a=Math.max(Math.floor((this._cssWidth-t.GetWidth())/2),0):"right"===this._horizontalAlign&&(a=Math.max(Math.floor(this._cssWidth-t.GetWidth()),0)),t.SetPosX(a),t.SetPosY(e);for(const s of t.fragments())s.IsIcon()||(this._LayoutTextFragment(s,a,e),a+=s.GetWidth())}_LayoutTextFragment(t,e,a){const s=t.GetStyleTag("offsetx");e+=s?getOffsetParam(s.param,t.GetHeight()):0;const i=t.GetStyleTag("offsety");a+=i?getOffsetParam(i.param,t.GetHeight()):0,t.SetPosX(e),t.SetPosY(a)}Draw(t,e,a,s){this._UpdateTextMeasurements(),this._drawCharCount=0;const i=C3.cloneArray(this._wrappedText.GetLines()),r=Math.sin(s),o=Math.cos(s);for(const s of i)this._DrawLine(t,s,e,a,r,o)}_DrawLine(t,e,a,s,i,r){const o=e.GetPosX(),h=e.GetPosY();if(!Number.isFinite(o)||!Number.isFinite(h))return;const n=e.GetHeight();for(const o of e.fragments())this._DrawFragment(t,o,a,s,i,r,n)}_DrawFragment(t,e,a,s,i,r,o){let h=e.GetPosX(),n=e.GetPosY();if(!Number.isFinite(h)||!Number.isFinite(n))return;let l=e.GetCharacterArray(),c=e.GetWidth();if(-1!==this._drawMaxCharCount){if(this._drawCharCount>=this._drawMaxCharCount)return;this._drawCharCount+l.length>this._drawMaxCharCount&&(l=l.slice(0,this._drawMaxCharCount-this._drawCharCount),c=this._MeasureText(e).width),this._drawCharCount+=l.length}const _=e.GetStyleTag("background");if(C3.IsCharArrayAllWhitespace(l)&&!_||e.HasStyleTag("hide"))return;const p=e.GetStyleTag("scale"),d=(p?parseFloat(p.param):this._scale)*this._sceneGraphScale,g=e.GetStyleTag("scalex"),C=(g?parseFloat(g.param):1)*d,u=e.GetStyleTag("scaley"),S=(u?parseFloat(u.param):1)*d,m=this._spriteFont.GetCharacterHeight()*S;n+=o-this._lineHeight-m;let f=1;const x=e.GetStyleTag("opacity");x&&(f=parseFloat(x.param)/100),_&&(t.SetColorFillMode(),tmpColor.parseString(normalizeCssColorString(_.param)),tmpColor.setA(tmpColor.getA()*f*this._color.getA()),tmpColor.premultiply(),t.SetColor(tmpColor),tmpRect.set(h,n,h+c,n+m),tmpRect.getRight()>this._cssWidth&&tmpRect.setRight(this._cssWidth),tmpQuad.setFromRotatedRectPrecalc(tmpRect,i,r),tmpQuad.offset(a,s),t.Quad(tmpQuad),t.SetTextureFillMode());const G=e.GetStyleTag("color");G?(tmpColor.parseString(normalizeCssColorString(G.param)),tmpColor.setA(this._color.getA())):tmpColor.copy(this._color),tmpColor.setA(tmpColor.getA()*f),tmpColor.premultiply(),t.SetColor(tmpColor);const T=this._spriteFont.GetCharacterWidth()*C,W=Math.abs(this.GetSpacing());for(const e of l){const o=this._spriteFont.GetCharacter(e);if(o){const e=o.GetDisplayWidth()*C;if(h+e>this._cssWidth+W+1e-5)return;tmpRect.set(h,n,h+T,n+m),tmpQuad.setFromRotatedRectPrecalc(tmpRect,i,r),tmpQuad.offset(a,s),t.Quad3(tmpQuad,o.GetTexRect()),h+=e+this._spacing}else h+=this._spriteFont.GetSpaceWidth()*C+this._spacing}}GetSpriteFont(){return this._spriteFont}SetBBCodeEnabled(t){t=!!t,this._isBBcodeEnabled!==t&&(this._isBBcodeEnabled=t,this._SetWordWrapChanged())}IsBBCodeEnabled(){return this._isBBcodeEnabled}SetText(t){this._text!==t&&(this._text=t,this._SetWordWrapChanged())}SetWordWrapMode(t){if(!VALID_WORD_WRAP_MODES.has(t))throw new Error("invalid word wrap mode");this._wrapMode!==t&&(this._wrapMode=t,this._SetWordWrapChanged())}SetHorizontalAlign(t){if(!VALID_HORIZ_ALIGNMENTS.has(t))throw new Error("invalid alignment");this._horizontalAlign!==t&&(this._horizontalAlign=t,this._SetTextLayoutChanged())}SetVerticalAlign(t){if(!VALID_VERT_ALIGNMENTS.has(t))throw new Error("invalid alignment");this._verticalAlign!==t&&(this._verticalAlign=t,this._SetTextLayoutChanged())}SetScale(t){this._scale!==t&&(this._scale=t,this._SetWordWrapChanged())}GetScale(){return this._scale}SetSceneGraphScale(t){this._sceneGraphScale!==t&&(this._sceneGraphScale=t,this._SetWordWrapChanged())}GetSceneGraphScale(){return this._sceneGraphScale}SetSpacing(t){this._spacing!==t&&(this._spacing=t,this._SetWordWrapChanged())}GetSpacing(){return this._spacing}SetLineHeight(t){this._lineHeight=t,this._SetWordWrapChanged()}GetLineHeight(){return this._lineHeight}SetOpacity(t){t=C3.clamp(t,0,1),this._color.a=t}SetColor(t){this._color.equals(t)||this._color.copy(t)}GetColor(){return this._color}GetTextWidth(){return this._UpdateTextMeasurements(),this._wrappedText.GetMaxLineWidth()}GetTextHeight(){this._UpdateTextMeasurements();const t=this._spriteFont.GetCharacterHeight()*this._scale,e=this._lineHeight,a=t+e;return this._wrappedText.GetLineCount()*a-e}};
}

// scripts/plugins/Spritefont2/spritefont.js
{
const C3=self.C3,SpriteFontText=self.SpriteFontText,DEFAULT_SPRITEFONT_OPTS={width:256,height:256,characterWidth:16,characterHeight:16,characterSet:""};self.SpriteFont=class{constructor(t){if((t=Object.assign({},DEFAULT_SPRITEFONT_OPTS,t)).width<=0||t.height<=0||t.characterWidth<=0||t.characterHeight<=0)throw new Error("invalid size");this._width=t.width,this._height=t.height,this._characterWidth=t.characterWidth,this._characterHeight=t.characterHeight,this._characterSet=t.characterSet,this._spacingData="",this._spacingParsed=null,this._hasAnyCustomWidths=!1,this._spaceWidth=-1,this._texRect=new C3.Rect(0,0,1,1),this._characterMap=new Map,this._mapChanged=!0,this._allTexts=new Set}Release(){this._texRect=null,this._ReleaseCharacters(),this._characterMap=null,this._allTexts&&this._allTexts.clear(),this._allTexts=null}_ReleaseCharacters(){for(let t of this._characterMap.values())t.Release();this._characterMap.clear()}_AddSpriteFontText(t){this._allTexts.add(t)}_RemoveSpriteFontText(t){this._allTexts.delete(t)}UpdateCharacterMap(){if(!this._mapChanged)return;this._ReleaseCharacters();let t=C3.SplitGraphemes(this._characterSet),h=Math.floor(this._width/this._characterWidth),e=h*Math.floor(this._height/this._characterHeight);for(let a=0,i=t.length;a<i&&!(a>=e);++a){let e=t[a];if(this._characterMap.has(e))continue;let i=a%h,r=Math.floor(a/h);this._characterMap.set(e,C3.New(self.SpriteFontCharacter,this,e,i*this._characterWidth,r*this._characterHeight))}if(this._hasAnyCustomWidths=!1,this._spaceWidth=-1,Array.isArray(this._spacingParsed))for(let t of this._spacingParsed){if(!Array.isArray(t))continue;if(2!==t.length)continue;let h=t[0],e=t[1];if("number"==typeof h&&isFinite(h)&&"string"==typeof e&&h!==this._characterWidth)for(let t of e){let e=this._characterMap.get(t);e?(e.SetDisplayWidth(h),this._hasAnyCustomWidths=!0):" "===t&&(this._spaceWidth=h,this._hasAnyCustomWidths=!0)}}this._mapChanged=!1;for(let t of this._allTexts)t._SetWordWrapChanged()}SetCharacterWidthsChanged(){this._hasAnyCustomWidths=!0;for(const t of this._allTexts)t._SetWordWrapChanged()}GetCharacter(t){return this.UpdateCharacterMap(),this._characterMap.get(t)||null}HasAnyCustomWidths(){return this._hasAnyCustomWidths}SetWidth(t){if((t=Math.floor(t))<=0)throw new Error("invalid size");this._width!==t&&(this._width=t,this._mapChanged=!0)}GetWidth(){return this._width}SetHeight(t){if((t=Math.floor(t))<=0)throw new Error("invalid size");this._height!==t&&(this._height=t,this._mapChanged=!0)}GetHeight(){return this._height}SetTexRect(t){if(!this._texRect.equals(t)){this._texRect.copy(t);for(const t of this._characterMap.values())t._UpdateTexRect()}}GetTexRect(){return this._texRect}SetCharacterWidth(t){if((t=Math.floor(t))<=0)throw new Error("invalid size");this._characterWidth!==t&&(this._characterWidth=t,this._mapChanged=!0)}GetCharacterWidth(){return this._characterWidth}SetCharacterHeight(t){if((t=Math.floor(t))<=0)throw new Error("invalid size");this._characterHeight!==t&&(this._characterHeight=t,this._mapChanged=!0)}GetCharacterHeight(){return this._characterHeight}SetCharacterSet(t){this._characterSet!==t&&(this._characterSet=t,this._mapChanged=!0)}GetCharacterSet(){return this._characterSet}SetSpacingData(t){if(this._spacingData!==t&&(this._spacingData=t,this._mapChanged=!0,this._spacingParsed=null,this._spacingData.length))try{this._spacingParsed=JSON.parse(this._spacingData)}catch(t){this._spacingParsed=null}}GetSpacingData(){return this._spacingData}SetSpaceWidth(t){t<0&&(t=-1),this._spaceWidth!==t&&(this._spaceWidth=t,this._spaceWidth>=0&&(this._hasAnyCustomWidths=!0))}GetSpaceWidth(){return this._spaceWidth<0?this._characterWidth:this._spaceWidth}};
}

// scripts/plugins/Keyboard/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.Keyboard=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const r=self.C3;self.C3X;r.Plugins.Keyboard.Type=class extends r.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}GetScriptInterfaceClass(){return self.IKeyboardObjectType}};let t=null;function GetKeyboardSdkInstance(){return t.GetSingleGlobalInstance().GetSdkInstance()}self.IKeyboardObjectType=class extends self.IObjectType{constructor(e){super(e),t=e,e.GetRuntime()._GetCommonScriptInterfaces().keyboard=this}isKeyDown(e){const r=GetKeyboardSdkInstance();if("string"==typeof e)return r.IsKeyDown(e);if("number"==typeof e)return r.IsKeyCodeDown(e);throw new TypeError("expected string or number")}}}{const s=self.C3,n="keyboard";s.Plugins.Keyboard.Instance=class extends s.SDKInstanceBase{constructor(e,r){super(e,n),this._keysDownByString=new Set,this._keysDownByWhich=new Set,this._triggerWhich=0,this._triggerString="",this._triggerTypedKey="",this._isKeyboardLockSupported=!1;const t=this.GetRuntime().Dispatcher();this._disposables=new s.CompositeDisposable(s.Disposable.From(t,"keydown",(e=>this._OnKeyDown(e.data))),s.Disposable.From(t,"keyup",(e=>this._OnKeyUp(e.data))),s.Disposable.From(t,"window-blur",(()=>this._OnWindowOrKeyboardBlur())),s.Disposable.From(t,"keyboard-blur",(()=>this._OnWindowOrKeyboardBlur()))),this._runtime.AddLoadPromise(this._Init())}Release(){super.Release()}async _Init(){const e=await this.PostToDOMAsync("init");this._isKeyboardLockSupported=e["isKeyboardLockSupported"]}_OnKeyDown(e){const r=e["which"],t=e["code"]||r.toString(),n=e["key"];this._keysDownByString.has(t)||(this._keysDownByString.add(t),this._keysDownByWhich.add(r),this._triggerString=t,this._triggerWhich=r,this._triggerTypedKey=n,this.Trigger(s.Plugins.Keyboard.Cnds.OnAnyKey),this.Trigger(s.Plugins.Keyboard.Cnds.OnKey),this.Trigger(s.Plugins.Keyboard.Cnds.OnLeftRightKeyPressed),this.Trigger(s.Plugins.Keyboard.Cnds.OnKeyCode))}_OnKeyUp(e){const r=e["which"],t=e["code"]||r.toString(),n=e["key"];this._keysDownByString.delete(t),this._keysDownByWhich.delete(r),this._triggerString=t,this._triggerWhich=r,this._triggerTypedKey=n,this.Trigger(s.Plugins.Keyboard.Cnds.OnAnyKeyReleased),this.Trigger(s.Plugins.Keyboard.Cnds.OnKeyReleased),this.Trigger(s.Plugins.Keyboard.Cnds.OnLeftRightKeyReleased),this.Trigger(s.Plugins.Keyboard.Cnds.OnKeyCodeReleased)}_OnWindowOrKeyboardBlur(){for(const e of this._keysDownByWhich)this._keysDownByWhich.delete(e),this._triggerWhich=e,this.Trigger(s.Plugins.Keyboard.Cnds.OnAnyKeyReleased),this.Trigger(s.Plugins.Keyboard.Cnds.OnKeyReleased),this.Trigger(s.Plugins.Keyboard.Cnds.OnKeyCodeReleased);this._keysDownByString.clear()}IsKeyDown(e){return this._keysDownByString.has(e)}IsKeyCodeDown(e){return this._keysDownByWhich.has(e)}SaveToJson(){return{"tk":this._triggerWhich,"tkk":this._triggerTypedKey}}LoadFromJson(e){this._triggerWhich=e["tk"],e.hasOwnProperty("tkk")&&(this._triggerTypedKey=e["tkk"])}GetDebuggerProperties(){const e="plugins.keyboard";return[{title:e+".name",properties:[{name:e+".debugger.last-key-code",value:this._triggerWhich},{name:e+".debugger.last-key-string",value:s.Plugins.Keyboard.Exps.StringFromKeyCode(this._triggerWhich)},{name:e+".debugger.last-typed-key",value:this._triggerTypedKey}]}]}}}{const i=self.C3,a=["ShiftLeft","ShiftRight","ControlLeft","ControlRight","AltLeft","AltRight","MetaLeft","MetaRight"];i.Plugins.Keyboard.Cnds={IsKeyDown(e){return this._keysDownByWhich.has(e)},OnKey(e){return this._triggerWhich===e},OnAnyKey:()=>!0,OnAnyKeyReleased:()=>!0,OnKeyReleased(e){return this._triggerWhich===e},IsKeyCodeDown(e){return e=Math.floor(e),this._keysDownByWhich.has(e)},OnKeyCode(e){return this._triggerWhich===e},OnKeyCodeReleased(e){return this._triggerWhich===e},OnLeftRightKeyPressed(e){const r=a[e];return this._triggerString===r},OnLeftRightKeyReleased(e){const r=a[e];return this._triggerString===r},IsLeftRightKeyDown(e){const r=a[e];return this._keysDownByString.has(r)},IsKeyboardLockSupported(){return this._isKeyboardLockSupported},OnKeyboardLocked:()=>!0,OnKeyboardLockError:()=>!0}}{const o=self.C3;o.Plugins.Keyboard.Acts={async LockKeyboard(e){if(!this._isKeyboardLockSupported)return;let r=[];e&&(r=e.split(","));(await this.PostToDOMAsync("lock-keyboard",{"keysArr":r}))["isOk"]?this.Trigger(o.Plugins.Keyboard.Cnds.OnKeyboardLocked):this.Trigger(o.Plugins.Keyboard.Cnds.OnKeyboardLockError)},UnlockKeyboard(){this._isKeyboardLockSupported&&this.PostToDOMAsync("unlock-keyboard")}}}{function StringFromCharCode(e){switch(e=Math.floor(e)){case 8:return"backspace";case 9:return"tab";case 13:return"enter";case 16:return"shift";case 17:return"control";case 18:return"alt";case 19:return"pause";case 20:return"capslock";case 27:return"esc";case 33:return"pageup";case 34:return"pagedown";case 35:return"end";case 36:return"home";case 37:return"←";case 38:return"↑";case 39:return"→";case 40:return"↓";case 45:return"insert";case 46:return"del";case 91:return"left window key";case 92:return"right window key";case 93:return"select";case 96:return"numpad 0";case 97:return"numpad 1";case 98:return"numpad 2";case 99:return"numpad 3";case 100:return"numpad 4";case 101:return"numpad 5";case 102:return"numpad 6";case 103:return"numpad 7";case 104:return"numpad 8";case 105:return"numpad 9";case 106:return"numpad *";case 107:return"numpad +";case 109:return"numpad -";case 110:return"numpad .";case 111:return"numpad /";case 112:return"F1";case 113:return"F2";case 114:return"F3";case 115:return"F4";case 116:return"F5";case 117:return"F6";case 118:return"F7";case 119:return"F8";case 120:return"F9";case 121:return"F10";case 122:return"F11";case 123:return"F12";case 144:return"numlock";case 145:return"scroll lock";case 186:return";";case 187:return"=";case 188:return",";case 189:return"-";case 190:return".";case 191:return"/";case 192:return"'";case 219:return"[";case 220:return"\\";case 221:return"]";case 222:return"#";case 223:return"`";default:return String.fromCharCode(e)}}self.C3.Plugins.Keyboard.Exps={LastKeyCode(){return this._triggerWhich},StringFromKeyCode:e=>StringFromCharCode(e),TypedKey(){return this._triggerTypedKey}}}
}

// scripts/plugins/Touch/c3runtime/runtime.js
{
{const t=self.C3;t.Plugins.Touch=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}}}{const e=self.C3,s=self.C3X;e.Plugins.Touch.Type=class extends e.SDKTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}GetScriptInterfaceClass(){return self.ITouchObjectType}};let i=null;function GetTouchSdkInstance(){return i.GetSingleGlobalInstance().GetSdkInstance()}self.ITouchObjectType=class extends self.IObjectType{constructor(t){super(t),i=t,t.GetRuntime()._GetCommonScriptInterfaces().touch=this}requestPermission(t){s.RequireString(t);const e=GetTouchSdkInstance();if("orientation"===t)return e._RequestPermission(0);if("motion"===t)return e._RequestPermission(1);throw new Error("invalid type")}}}{const n=self.C3,r="touch";n.Plugins.Touch.Instance=class extends n.SDKInstanceBase{constructor(t,e){super(t,r),this._touches=new Map,this._useMouseInput=!1,this._isMouseDown=!1,this._orientCompassHeading=0,this._orientAlpha=0,this._orientBeta=0,this._orientGamma=0,this._accX=0,this._accY=0,this._accZ=0,this._accWithGX=0,this._accWithGY=0,this._accWithGZ=0,this._triggerIndex=0,this._triggerId=0,this._triggerPermission=0,this._curTouchX=0,this._curTouchY=0,this._getTouchIndex=0,this._triggerType=0,this._permissionPromises=[],e&&(this._useMouseInput=e[0]),this.AddDOMMessageHandler("permission-result",(t=>this._OnPermissionResult(t)));const s=this.GetRuntime().Dispatcher();this._disposables=new n.CompositeDisposable(n.Disposable.From(s,"pointerdown",(t=>this._OnPointerDown(t.data))),n.Disposable.From(s,"pointermove",(t=>this._OnPointerMove(t.data))),n.Disposable.From(s,"pointerup",(t=>this._OnPointerUp(t.data,!1))),n.Disposable.From(s,"pointercancel",(t=>this._OnPointerUp(t.data,!0))),n.Disposable.From(s,"deviceorientation",(t=>this._OnDeviceOrientation(t.data))),n.Disposable.From(s,"deviceorientationabsolute",(t=>this._OnDeviceOrientationAbsolute(t.data))),n.Disposable.From(s,"devicemotion",(t=>this._OnDeviceMotion(t.data))),n.Disposable.From(s,"tick2",(t=>this._OnTick2())))}Release(){this._touches.clear(),super.Release()}_OnPointerDown(t){if("mouse"===t["pointerType"]){if(!this._useMouseInput)return;this._isMouseDown=!0}const e=t["pointerId"];if(this._touches.has(e))return;const s=t["pageX"]-this._runtime.GetCanvasClientX(),i=t["pageY"]-this._runtime.GetCanvasClientY(),r=performance.now(),o=this._touches.size;this._triggerIndex=o,this._triggerId=e;const u=n.New(n.Plugins.Touch.TouchInfo);u.Init(r,s,i,e,o),this._touches.set(e,u),this.Trigger(n.Plugins.Touch.Cnds.OnNthTouchStart),this.Trigger(n.Plugins.Touch.Cnds.OnTouchStart),this._curTouchX=s,this._curTouchY=i,this._triggerType=0,this.Trigger(n.Plugins.Touch.Cnds.OnTouchObject)}_OnPointerMove(t){if("mouse"===t["pointerType"]&&!this._isMouseDown)return;const e=this._touches.get(t["pointerId"]);if(!e)return;const s=performance.now();if(s-e.GetTime()<2)return;const i=t["pageX"]-this._runtime.GetCanvasClientX(),n=t["pageY"]-this._runtime.GetCanvasClientY();e.Update(s,i,n,t["width"],t["height"],t["pressure"])}_OnPointerUp(t,e){if("mouse"===t["pointerType"]){if(!this._isMouseDown)return;this._isMouseDown=!1}const s=performance.now(),i=t["pointerId"],r=this._touches.get(i);if(r){if(this._triggerIndex=r.GetStartIndex(),this._triggerId=r.GetId(),!e){const e=t["pageX"]-this._runtime.GetCanvasClientX(),s=t["pageY"]-this._runtime.GetCanvasClientY();this._curTouchX=e,this._curTouchY=s,this._triggerType=1,this.Trigger(n.Plugins.Touch.Cnds.OnTouchObject)}if(this.Trigger(n.Plugins.Touch.Cnds.OnNthTouchEnd),this.Trigger(n.Plugins.Touch.Cnds.OnTouchEnd),!e){const t=r.ShouldTriggerTap(s);"single-tap"===t?(this.Trigger(n.Plugins.Touch.Cnds.OnTapGesture),this._curTouchX=r.GetX(),this._curTouchY=r.GetY(),this.Trigger(n.Plugins.Touch.Cnds.OnTapGestureObject)):"double-tap"===t&&(this.Trigger(n.Plugins.Touch.Cnds.OnDoubleTapGesture),this._curTouchX=r.GetX(),this._curTouchY=r.GetY(),this.Trigger(n.Plugins.Touch.Cnds.OnDoubleTapGestureObject))}r.Release(),this._touches.delete(i)}}_RequestPermission(t){return this._PostToDOMMaybeSync("request-permission",{"type":t}),new Promise(((e,s)=>{this._permissionPromises.push({type:t,resolve:e,reject:s})}))}_OnPermissionResult(t){const e=t["result"],s=t["type"];this._triggerPermission=s;const i=this._permissionPromises.filter((t=>t.type===s));for(const t of i)t.resolve(e?"granted":"denied");this._permissionPromises=this._permissionPromises.filter((t=>t.type!==s)),e?(this.Trigger(n.Plugins.Touch.Cnds.OnPermissionGranted),0===s?this._runtime.RequestDeviceOrientationEvent():this._runtime.RequestDeviceMotionEvent()):this.Trigger(n.Plugins.Touch.Cnds.OnPermissionDenied)}_OnDeviceOrientation(t){"number"==typeof t["webkitCompassHeading"]?this._orientCompassHeading=t["webkitCompassHeading"]:t["absolute"]&&(this._orientCompassHeading=t["alpha"]),this._orientAlpha=t["alpha"],this._orientBeta=t["beta"],this._orientGamma=t["gamma"]}_OnDeviceOrientationAbsolute(t){this._orientCompassHeading=t["alpha"]}_OnDeviceMotion(t){const e=t["acceleration"];e&&(this._accX=e["x"],this._accY=e["y"],this._accZ=e["z"]);const s=t["accelerationIncludingGravity"];s&&(this._accWithGX=s["x"],this._accWithGY=s["y"],this._accWithGZ=s["z"])}_OnTick2(){const t=performance.now();let e=0;for(const s of this._touches.values())s.GetTime()<=t-50&&s._SetLastTime(t),s.ShouldTriggerHold(t)&&(this._triggerIndex=s.GetStartIndex(),this._triggerId=s.GetId(),this._getTouchIndex=e,this.Trigger(n.Plugins.Touch.Cnds.OnHoldGesture),this._curTouchX=s.GetX(),this._curTouchY=s.GetY(),this.Trigger(n.Plugins.Touch.Cnds.OnHoldGestureObject),this._getTouchIndex=0),++e}_GetTouchByIndex(t){t=Math.floor(t);for(const e of this._touches.values()){if(0===t)return e;--t}return null}_IsClientPosOnCanvas(t,e){return t>=0&&e>=0&&t<this._runtime.GetCanvasCssWidth()&&e<this._runtime.GetCanvasCssHeight()}GetDebuggerProperties(){return[{title:"plugins.touch.debugger.touches",properties:[...this._touches.values()].map((t=>({name:"$"+t.GetId(),value:t.GetX()+", "+t.GetY()})))}]}}}{const o=self.C3;o.Plugins.Touch.Cnds={OnTouchStart:()=>!0,OnTouchEnd:()=>!0,IsInTouch(){return this._touches.size>0},OnTouchObject(t,e){return!!t&&(e===this._triggerType&&(!!this._IsClientPosOnCanvas(this._curTouchX,this._curTouchY)&&this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,[[this._curTouchX,this._curTouchY]],!1)))},IsTouchingObject(t){if(!t)return!1;const e=this._runtime.GetCurrentCondition().IsInverted(),s=[...this._touches.values()].filter((t=>this._IsClientPosOnCanvas(t.GetX(),t.GetY()))).map((t=>[t.GetX(),t.GetY()]));return o.xor(this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,s,e),e)},CompareTouchSpeed(t,e,s){const i=this._GetTouchByIndex(t);return!!i&&o.compare(i.GetSpeed(),e,s)},OrientationSupported:()=>!0,MotionSupported:()=>!0,CompareOrientation(t,e,s){this._runtime.RequestDeviceOrientationEvent();let i=0;return i=0===t?this._orientAlpha:1===t?this._orientBeta:this._orientGamma,o.compare(i,e,s)},CompareAcceleration(t,e,s){this._runtime.RequestDeviceMotionEvent();let i=0;return i=0===t?this._accWithGX:1===t?this._accWithGY:2===t?this._accWithGZ:3===t?this._accX:4===t?this._accY:this._accZ,o.compare(i,e,s)},OnNthTouchStart(t){return(t=Math.floor(t))===this._triggerIndex},OnNthTouchEnd(t){return(t=Math.floor(t))===this._triggerIndex},HasNthTouch(t){return t=Math.floor(t),this._touches.size>=t+1},OnHoldGesture:()=>!0,OnTapGesture:()=>!0,OnDoubleTapGesture:()=>!0,OnHoldGestureObject(t){return!!t&&(!!this._IsClientPosOnCanvas(this._curTouchX,this._curTouchY)&&this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,[[this._curTouchX,this._curTouchY]],!1))},OnTapGestureObject(t){return!!t&&(!!this._IsClientPosOnCanvas(this._curTouchX,this._curTouchY)&&this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,[[this._curTouchX,this._curTouchY]],!1))},OnDoubleTapGestureObject(t){return!!t&&(!!this._IsClientPosOnCanvas(this._curTouchX,this._curTouchY)&&this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,[[this._curTouchX,this._curTouchY]],!1))},OnPermissionGranted(t){return this._triggerPermission===t},OnPermissionDenied(t){return this._triggerPermission===t}}}self.C3.Plugins.Touch.Acts={RequestPermission(t){this._RequestPermission(t)}};{const u=self.C3;u.Plugins.Touch.Exps={TouchCount(){return this._touches.size},X(t){const e=this._GetTouchByIndex(this._getTouchIndex);return e?e.GetPositionForLayer(this._runtime.GetCurrentLayout(),t,!0):0},Y(t){const e=this._GetTouchByIndex(this._getTouchIndex);return e?e.GetPositionForLayer(this._runtime.GetCurrentLayout(),t,!1):0},XAt(t,e){const s=this._GetTouchByIndex(t);return s?s.GetPositionForLayer(this._runtime.GetCurrentLayout(),e,!0):0},YAt(t,e){const s=this._GetTouchByIndex(t);return s?s.GetPositionForLayer(this._runtime.GetCurrentLayout(),e,!1):0},XForID(t,e){const s=this._touches.get(t);return s?s.GetPositionForLayer(this._runtime.GetCurrentLayout(),e,!0):0},YForID(t,e){const s=this._touches.get(t);return s?s.GetPositionForLayer(this._runtime.GetCurrentLayout(),e,!1):0},AbsoluteX(){const t=this._GetTouchByIndex(0);return t?t.GetX():0},AbsoluteY(){const t=this._GetTouchByIndex(0);return t?t.GetY():0},AbsoluteXAt(t){const e=this._GetTouchByIndex(t);return e?e.GetX():0},AbsoluteYAt(t){const e=this._GetTouchByIndex(t);return e?e.GetY():0},AbsoluteXForID(t){const e=this._touches.get(t);return e?e.GetX():0},AbsoluteYForID(t){const e=this._touches.get(t);return e?e.GetY():0},SpeedAt(t){const e=this._GetTouchByIndex(t);return e?e.GetSpeed():0},SpeedForID(t){const e=this._touches.get(t);return e?e.GetSpeed():0},AngleAt(t){const e=this._GetTouchByIndex(t);return e?u.toDegrees(e.GetAngle()):0},AngleForID(t){const e=this._touches.get(t);return e?u.toDegrees(e.GetAngle()):0},CompassHeading(){return this._runtime.RequestDeviceOrientationEvent(),this._orientCompassHeading},Alpha(){return this._runtime.RequestDeviceOrientationEvent(),this._orientAlpha},Beta(){return this._runtime.RequestDeviceOrientationEvent(),this._orientBeta},Gamma(){return this._runtime.RequestDeviceOrientationEvent(),this._orientGamma},AccelerationXWithG(){return this._runtime.RequestDeviceMotionEvent(),this._accWithGX},AccelerationYWithG(){return this._runtime.RequestDeviceMotionEvent(),this._accWithGY},AccelerationZWithG(){return this._runtime.RequestDeviceMotionEvent(),this._accWithGZ},AccelerationX(){return this._runtime.RequestDeviceMotionEvent(),this._accX},AccelerationY(){return this._runtime.RequestDeviceMotionEvent(),this._accY},AccelerationZ(){return this._runtime.RequestDeviceMotionEvent(),this._accZ},TouchIndex(){return this._triggerIndex},TouchID(){return this._triggerId},WidthForID(t){const e=this._touches.get(t);return e?e.GetWidth():0},HeightForID(t){const e=this._touches.get(t);return e?e.GetHeight():0},PressureForID(t){const e=this._touches.get(t);return e?e.GetPressure():0}}}
}

// scripts/plugins/Touch/c3runtime/touchInfo.js
{
const C3=self.C3,GESTURE_HOLD_THRESHOLD=15,GESTURE_HOLD_TIMEOUT=500,GESTURE_TAP_TIMEOUT=333,GESTURE_DOUBLETAP_THRESHOLD=25;let lastTapX=-1e3,lastTapY=-1e3,lastTapTime=-1e4;C3.Plugins.Touch.TouchInfo=class extends C3.DefendedBase{constructor(){super(),this._pointerId=0,this._startIndex=0,this._startTime=0,this._time=0,this._lastTime=0,this._startX=0,this._startY=0,this._x=0,this._y=0,this._lastX=0,this._lastY=0,this._width=0,this._height=0,this._pressure=0,this._hasTriggeredHold=!1,this._isTooFarForHold=!1}Release(){}Init(t,s,i,e,h){this._pointerId=e,this._startIndex=h,this._time=t,this._lastTime=t,this._startTime=t,this._startX=s,this._startY=i,this._x=s,this._y=i,this._lastX=s,this._lastY=i}Update(t,s,i,e,h,_){this._lastTime=this._time,this._time=t,this._lastX=this._x,this._lastY=this._y,this._x=s,this._y=i,this._width=e,this._height=h,this._pressure=_,!this._isTooFarForHold&&C3.distanceTo(this._startX,this._startY,this._x,this._y)>=15&&(this._isTooFarForHold=!0)}GetId(){return this._pointerId}GetStartIndex(){return this._startIndex}GetTime(){return this._time}_SetLastTime(t){this._lastTime=t}GetX(){return this._x}GetY(){return this._y}GetSpeed(){const t=C3.distanceTo(this._x,this._y,this._lastX,this._lastY),s=(this._time-this._lastTime)/1e3;return s>0?t/s:0}GetAngle(){return C3.angleTo(this._lastX,this._lastY,this._x,this._y)}GetWidth(){return this._width}GetHeight(){return this._height}GetPressure(){return this._pressure}ShouldTriggerHold(t){return!this._hasTriggeredHold&&(t-this._startTime>=500&&!this._isTooFarForHold&&C3.distanceTo(this._startX,this._startY,this._x,this._y)<15&&(this._hasTriggeredHold=!0,!0))}ShouldTriggerTap(t){return this._hasTriggeredHold?"":t-this._startTime<=333&&!this._isTooFarForHold&&C3.distanceTo(this._startX,this._startY,this._x,this._y)<15?t-lastTapTime<=666&&C3.distanceTo(lastTapX,lastTapY,this._x,this._y)<25?(lastTapX=-1e3,lastTapY=-1e3,lastTapTime=-1e4,"double-tap"):(lastTapX=this._x,lastTapY=this._y,lastTapTime=t,"single-tap"):""}GetPositionForLayer(t,s,i){if(void 0===s){return t.GetLayerByIndex(0).CanvasCssToLayer_DefaultTransform(this._x,this._y)[i?0:1]}{const e=t.GetLayer(s);return e?e.CanvasCssToLayer(this._x,this._y)[i?0:1]:0}}};
}

// scripts/plugins/LocalStorage/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.LocalStorage=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const t=self.C3;t.Plugins.LocalStorage.Type=class extends t.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const s=self.C3,r="localstorage";s.Plugins.LocalStorage.Instance=class extends s.SDKInstanceBase{constructor(e,t){super(e,r),this._currentKey="",this._lastValue="",this._keyNamesList=[],this._errorMessage="",this._isPersistent=!1,this._pendingGets=0,this._pendingSets=0,this._isInMemoryOnly=!1,t&&(this._isInMemoryOnly=t[0]);const s=this._runtime._GetProjectStorage();this._storage=null,this._isInMemoryOnly?this._storage=s.createInstance({forceInMemoryFallback:!0}):this._storage=s,this._debugCache=new Map,this._isLoadingDebugCache=!1,this._runtime.AddLoadPromise(this._Init())}async _Init(){const e=await Promise.race([this.PostToDOMAsync("init"),s.Wait(3e3)]);e&&(this._isPersistent=e["isPersistent"])}Release(){super.Release()}async _TriggerStorageError(e){this._errorMessage=this._GetErrorString(e),await this.TriggerAsync(s.Plugins.LocalStorage.Cnds.OnError)}_GetErrorString(e){return e?"string"==typeof e?e:"string"==typeof e.message?e.message:"string"==typeof e.name?e.name:"string"==typeof e.data?e.data:"unknown error":"unknown error"}GetDebuggerProperties(){return this._isLoadingDebugCache||this._DebugCacheStorage(),[{title:"plugins.localstorage.name",properties:[...this._debugCache.entries()].map((e=>({name:"$"+e[0],value:e[1],onedit:t=>this._storage.setItem(e[0],t)})))}]}async _DebugCacheStorage(){this._isLoadingDebugCache=!0;try{const e=await this._storage.keys();e.sort(((e,t)=>{const s=e.toLowerCase(),r=t.toLowerCase();return s<r?-1:r<s?1:0}));const t=await Promise.all(e.map((e=>this._storage.getItem(e))));this._debugCache.clear();for(let s=0,r=e.length;s<r;++s)this._debugCache.set(e[s],t[s])}catch(e){console.warn("[C3 debugger] Error displaying local storage: ",e)}finally{this._isLoadingDebugCache=!1}}}}{const i=self.C3;i.Plugins.LocalStorage.Cnds={OnItemSet(e){return this._currentKey===e},OnAnyItemSet:()=>!0,OnItemGet(e){return this._currentKey===e},OnAnyItemGet:()=>!0,OnItemRemoved(e){return this._currentKey===e},OnAnyItemRemoved:()=>!0,OnCleared:()=>!0,OnAllKeyNamesLoaded:()=>!0,OnError:()=>!0,OnItemExists(e){return this._currentKey===e},OnItemMissing(e){return this._currentKey===e},CompareKey(e,t){return i.compare(this._currentKey,e,t)},CompareValue(e,t){return i.compare(this._lastValue,e,t)},IsProcessingSets(){return this._pendingSets>0},IsProcessingGets(){return this._pendingGets>0},OnAllSetsComplete:()=>!0,OnAllGetsComplete:()=>!0,IsPersistent(){return this._isPersistent}}}{const a=self.C3;function IsExpressionType(e){return"string"==typeof e||"number"==typeof e}a.Plugins.LocalStorage.Acts={async SetItem(e,t){this._pendingSets++;try{const s=await this._storage.setItem(e,t);await this.ScheduleTriggers((async()=>{this._currentKey=e,this._lastValue=s,await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemSet),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemSet)}))}catch(e){await this._TriggerStorageError(e)}finally{this._pendingSets--,0===this._pendingSets&&await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllSetsComplete)}},async SetBinaryItem(e,t){if(!t)return;const s=t.GetFirstPicked(this._inst);if(!s)return;const r=s.GetSdkInstance();if(!r)return;const i=r.GetArrayBufferReadOnly();this._pendingSets++;try{await this._storage.setItem(e,i),await this.ScheduleTriggers((async()=>{this._currentKey=e,this._lastValue="",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemSet),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemSet)}))}catch(e){await this._TriggerStorageError(e)}finally{this._pendingSets--,0===this._pendingSets&&await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllSetsComplete)}},async GetItem(e){this._pendingGets++;try{const t=await this._storage.getItem(e);await this.ScheduleTriggers((async()=>{this._currentKey=e,this._lastValue=IsExpressionType(t)?t:"",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemGet),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemGet)}))}catch(e){await this._TriggerStorageError(e)}finally{this._pendingGets--,0===this._pendingGets&&await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllGetsComplete)}},async GetBinaryItem(e,t){if(!t)return;const s=t.GetFirstPicked(this._inst);if(!s)return;const r=s.GetSdkInstance();this._pendingGets++;try{let t=await this._storage.getItem(e);t=t instanceof ArrayBuffer?t:new ArrayBuffer(0),await this.ScheduleTriggers((async()=>{this._lastValue="",this._currentKey=e,r.SetArrayBufferTransfer(t),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemGet),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemGet)}))}catch(e){await this._TriggerStorageError(e)}finally{this._pendingGets--,0===this._pendingGets&&await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllGetsComplete)}},async CheckItemExists(e){try{const t=await this._storage.getItem(e);await this.ScheduleTriggers((async()=>{this._currentKey=e,null==t?(this._lastValue="",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemMissing)):(this._lastValue=IsExpressionType(t)?t:"",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemExists))}))}catch(e){await this._TriggerStorageError(e)}},async RemoveItem(e){try{await this._storage.removeItem(e),await this.ScheduleTriggers((async()=>{this._currentKey=e,this._lastValue="",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemRemoved),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemRemoved)}))}catch(e){await this._TriggerStorageError(e)}},async ClearStorage(){try{await this._storage.clear(),await this.ScheduleTriggers((async()=>{this._currentKey="",this._lastValue="",a.clearArray(this._keyNamesList),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnCleared)}))}catch(e){await this._TriggerStorageError(e)}},async GetAllKeyNames(){try{const e=await this._storage.keys();await this.ScheduleTriggers((async()=>{this._keyNamesList=e,await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllKeyNamesLoaded)}))}catch(e){await this._TriggerStorageError(e)}},async RequestPersistent(){const e=await this.PostToDOMAsync("request-persistent");e["isOk"]&&(this._isPersistent=e["isPersistent"])},LoadMemoryFromJSON(e){if(!this._isInMemoryOnly)return;let t;try{t=JSON.parse(e)}catch(e){return void console.error("[Local Storage] Failed to parse memory storage JSON: ",e)}t&&t["is-c3-storage"]&&Array.isArray(t["items"])||console.error("[Local Storage] Failed to load memory storage JSON: invalid data"),this._storage.SetMemoryStorage(new Map(t["items"]))}}}self.C3.Plugins.LocalStorage.Exps={ItemValue(){return this._lastValue},Key(){return this._currentKey},KeyCount(){return this._keyNamesList.length},KeyAt(e){return(e=Math.floor(e))<0||e>=this._keyNamesList.length?"":this._keyNamesList[e]},ErrorMessage(){return this._errorMessage},MemoryStorageAsJSON(){return this._isInMemoryOnly?JSON.stringify({"is-c3-storage":!0,"items":[...this._storage.GetMemoryStorage()]}):""}};
}

// scripts/plugins/Audio/c3runtime/runtime.js
{
{const t=self.C3,e=[];t.Plugins.Audio=class extends t.SDKPluginBase{constructor(t){super(t)}_AddActionPromise(t){e.push(t)}static async WaitForAllActionPromises(){await Promise.all(e),t.clearArray(e)}Release(){super.Release()}}}{const s=self.C3,i=self.C3X;s.Plugins.Audio.Type=class extends s.SDKTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}GetScriptInterfaceClass(){return self.IAudioObjectType}};let a=null;function GetAudioSdkInstance(){return a.GetSingleGlobalInstance().GetSdkInstance()}function GetAudioDOMInterface(){if(self["C3Audio_DOMInterface"])return self["C3Audio_DOMInterface"];throw new Error("audio scripting API cannot be used here - make sure the project is using DOM mode, not worker mode")}self.IAudioObjectType=class extends self.IObjectType{constructor(t){super(t),a=t}get audioContext(){return GetAudioDOMInterface()["GetAudioContextExtern"]()}get destinationNode(){return GetAudioDOMInterface()["GetDestinationNodeExtern"]()}get isSilent(){return GetAudioSdkInstance()._IsSilent()}set isSilent(t){GetAudioSdkInstance()._SetSilent(t)}get masterVolume(){return GetAudioSdkInstance()._GetMasterVolume()}set masterVolume(t){i.RequireFiniteNumber(t),GetAudioSdkInstance()._SetMasterVolume(t)}stopAll(){GetAudioSdkInstance()._StopAll()}}}{const n=self.C3,r="audio",o=["interactive","balanced","playback"];n.Plugins.Audio.Instance=class extends n.SDKInstanceBase{constructor(t,e){super(t,r),this._nextPlayTime=0,this._nextPlayOffset=0,this._triggerTags=[],this._enableMultiTags=!0,this._timeScaleMode=0,this._saveLoadMode=0,this._playInBackground=!1,this._panningModel=1,this._distanceModel=1,this._listenerPos=[this._runtime.GetViewportWidth()/2,this._runtime.GetViewportHeight()/2,600],this._listenerForwardVec=[0,0,-1],this._listenerUpVec=[0,1,0],this._referenceDistance=600,this._maxDistance=1e4,this._rolloffFactor=1,this._listenerInst=null,this._loadListenerUid=-1,this._masterVolume=1,this._isSilent=!1,this._sampleRate=0,this._audioContextState="suspended",this._outputLatency=0,this._effectCount=new Map,this._preloadTotal=0,this._preloadCount=0,this._bufferMetadata=new Map,this._remoteUrls=new Map;let s="interactive";e&&(this._timeScaleMode=e[0],this._saveLoadMode=e[1],this._playInBackground=e[2],s=o[e[3]],this._enableMultiTags=e[4],this._panningModel=e[5],this._distanceModel=e[6],this._listenerPos[2]=e[7],this._referenceDistance=e[8],this._maxDistance=e[9],this._rolloffFactor=e[10]),this._lastAIState=[],this._lastFxState=[],this._lastAnalysersData=[],this.AddDOMMessageHandlers([["state",t=>this._OnUpdateState(t)],["audiocontext-state",t=>this._OnAudioContextStateChanged(t)],["fxstate",t=>this._OnUpdateFxState(t)],["trigger",t=>this._OnTrigger(t)],["buffer-metadata",t=>this._OnBufferMetadata(t)]]);const i=this.GetRuntime().Dispatcher();this._disposables=new n.CompositeDisposable(n.Disposable.From(i,"instancedestroy",(t=>this._OnInstanceDestroyed(t.instance))),n.Disposable.From(i,"afterload",(()=>this._OnAfterLoad())),n.Disposable.From(i,"suspend",(()=>this._OnSuspend())),n.Disposable.From(i,"resume",(()=>this._OnResume())));const a=this._runtime.GetExportType(),l="Safari"===n.Platform.Browser,h=this._runtime.IsiOSWebView()||"macos-wkwebview"===a,u=this._runtime.GetAssetManager().IsFileProtocol(),c="playable-ad-single-file"===this._runtime.GetExportType(),d=l||h||u||c;this._runtime.AddLoadPromise(this.PostToDOMAsync("create-audio-context",{"preloadList":this._runtime.GetAssetManager().GetAudioToPreload().map((t=>({"originalUrl":t.originalUrl,"url":t.url,"type":t.type,"fileSize":t.fileSize}))),"timeScaleMode":this._timeScaleMode,"latencyHint":s,"panningModel":this._panningModel,"distanceModel":this._distanceModel,"refDistance":this._referenceDistance,"maxDistance":this._maxDistance,"rolloffFactor":this._rolloffFactor,"listenerPos":this._listenerPos,"usePlayMusicAsSoundWorkaround":d}).then((t=>{this._sampleRate=t["sampleRate"],this._audioContextState=t["audioContextState"],this._outputLatency=t["outputLatency"]}))),this._StartTicking()}Release(){this._listenerInst=null,super.Release()}_SplitTags(t){return this._enableMultiTags?t.split(" ").filter((t=>!!t)):t?[t]:[]}_MatchTagLists(t,e){for(const s of e){let e=!1;for(const i of t)if(n.equalsNoCase(i,s)){e=!0;break}if(!e)return!1}return!0}_MatchTagListToStr(t,e){return this._MatchTagLists(t,this._SplitTags(e))}_AddActionPromise(t){this.GetPlugin()._AddActionPromise(t)}_OnInstanceDestroyed(t){this._listenerInst===t&&(this._listenerInst=null)}DbToLinearNoCap(t){return Math.pow(10,t/20)}DbToLinear(t){const e=this.DbToLinearNoCap(t);return isFinite(e)?Math.max(Math.min(e,1),0):0}LinearToDbNoCap(t){return Math.log(t)/Math.log(10)*20}LinearToDb(t){return this.LinearToDbNoCap(Math.max(Math.min(t,1),0))}_GetScheduledPlayInfo(){let t=0;const e=!!self["C3_GetAudioContextCurrentTime"];return t=e?this._nextPlayTime:this._nextPlayOffset,this._nextPlayTime=0,this._nextPlayOffset=0,{playOffset:t,isTrueClock:e}}_OnSuspend(){this._playInBackground||this.PostToDOM("set-suspended",{"isSuspended":!0})}_OnResume(){this._playInBackground||this.PostToDOM("set-suspended",{"isSuspended":!1})}_OnUpdateState(t){const e=t["tickCount"];this._outputLatency=t["outputLatency"];const s=this._lastAIState.filter((t=>t.hasOwnProperty("placeholder")&&(t["placeholder"]>e||-1===t["placeholder"])));this._lastAIState=t["audioInstances"],this._lastAnalysersData=t["analysers"],s.length>0&&n.appendArray(this._lastAIState,s)}_OnBufferMetadata(t){this._bufferMetadata.set(t["originalUrl"],{duration:t["duration"]})}_OnAudioContextStateChanged(t){this._audioContextState=t["audioContextState"]}GetAudioContextState(){return this._runtime.IsExportToVideo()?"running":this._audioContextState}_OnUpdateFxState(t){this._lastFxState=t["fxstate"]}_GetFirstAudioStateByTags(t){const e=this._SplitTags(t);for(const t of this._lastAIState)if(this._MatchTagLists(t["tags"],e))return t;return null}_IsTagPlaying(t){const e=this._SplitTags(t);return this._lastAIState.some((t=>this._MatchTagLists(t["tags"],e)&&t["isPlaying"]))}_MaybeMarkAsPlaying(t,e,s,i,a){if(this._IsTagPlaying(e))return null;const n=this._bufferMetadata.get(t),r={"tags":this._SplitTags(e),"duration":n?n.duration:0,"volume":a,"isPlaying":!0,"playbackTime":0,"playbackRate":1,"uid":-1,"bufferOriginalUrl":t,"bufferUrl":"","bufferType":"","isMusic":s,"isLooping":i,"isMuted":!1,"resumePosition":0,"pan":null,"placeholder":-1};return this._lastAIState.push(r),r}_MaybeMarkAsStopped(t){const e=this._SplitTags(t);for(const t of this._lastAIState)this._MatchTagLists(t["tags"],e)&&(t["isPlaying"]=!1)}async _OnTrigger(t){const e=t["type"];this._triggerTags=t["tags"];const s=t["aiid"];if("ended"===e){for(const t of this._lastAIState)if(t["aiid"]===s){t["isPlaying"]=!1;break}await this.TriggerAsync(n.Plugins.Audio.Cnds.OnEnded)}else"fade-ended"===e&&await this.TriggerAsync(n.Plugins.Audio.Cnds.OnFadeEnded)}_MatchTriggerTag(t){return this._MatchTagListToStr(this._triggerTags,t)}Tick(){const t={"timeScale":this._runtime.GetTimeScale(),"gameTime":this._runtime.GetGameTimeRaw(),"instPans":this.GetInstancePans(),"tickCount":this._runtime.GetTickCountNoSave()};if(this._listenerInst){const e=this._listenerInst.GetWorldInfo();this._listenerPos[0]=e.GetX(),this._listenerPos[1]=e.GetY(),t["listenerPos"]=this._listenerPos,t["listenerOrientation"]=[...this._listenerForwardVec,...this._listenerUpVec]}this.PostToDOM("tick",t)}rotatePtAround(t,e,s,i,a){if(0===s)return[t,e];const n=Math.sin(s),r=Math.cos(s),o=(t-=i)*n;return t=t*r-(e-=a)*n,e=e*r+o,[t+=i,e+=a]}GetInstancePans(){return this._lastAIState.filter((t=>-1!==t["uid"])).map((t=>this._runtime.GetInstanceByUID(t["uid"]))).filter((t=>t)).map((t=>{const e=t.GetWorldInfo(),s=e.GetLayer().GetAngle(),[i,a]=this.rotatePtAround(e.GetX(),e.GetY(),-s,this._listenerPos[0],this._listenerPos[1]);return{"uid":t.GetUID(),"x":i,"y":a,"z":e.GetTotalZElevation(),"angle":e.GetAngle()-s}}))}GetAnalyserData(t,e){for(const s of this._lastAnalysersData)if(s.index===e&&n.equalsNoCase(s["tag"],t))return s;return null}_IncrementEffectCount(t){for(const e of this._SplitTags(t)){const t=e.toLowerCase();this._effectCount.set(t,(this._effectCount.get(t)||0)+1)}}_IsSilent(){return this._isSilent}_SetSilent(t){t=!!t,this._isSilent!==t&&(this._isSilent=t,this.PostToDOM("set-silent",{"isSilent":t}))}_GetMasterVolume(){return this._masterVolume}_SetMasterVolume(t){this._masterVolume!==t&&(this._masterVolume=t,this.PostToDOM("set-master-volume",{"vol":t}))}_StopAll(){this.PostToDOM("stop-all");for(const t of this._lastAIState)t["isPlaying"]=!1}_ShouldSave(t){return!t.hasOwnProperty("placeholder")&&(3!==this._saveLoadMode&&((!t["isMusic"]||1!==this._saveLoadMode)&&!(!t["isMusic"]&&2===this._saveLoadMode)))}SaveToJson(){return{"isSilent":this._isSilent,"masterVolume":this._masterVolume,"listenerZ":this._listenerPos[2],"listenerForwardVec":this._listenerForwardVec,"listenerUpVec":this._listenerUpVec,"listenerUid":this._listenerInst?this._listenerInst.GetUID():-1,"remoteUrls":[...this._remoteUrls.entries()],"playing":this._lastAIState.filter((t=>this._ShouldSave(t))),"effects":this._lastFxState,"analysers":this._lastAnalysersData}}LoadFromJson(t){if(this._isSilent=t["isSilent"],this._masterVolume=t["masterVolume"],this._listenerPos[2]=t["listenerZ"],this._listenerInst=null,this._loadListenerUid=t["listenerUid"],t.hasOwnProperty("listenerForwardVec")?this._listenerForwardVec=t["listenerForwardVec"]:this._listenerForwardVec=[0,0,-1],t.hasOwnProperty("listenerUpVec")?this._listenerUpVec=t["listenerUpVec"]:this._listenerUpVec=[0,1,0],this._remoteUrls.clear(),t["remoteUrls"])for(const[e,s]of t["remoteUrls"])this._remoteUrls.set(e,s);this._lastAIState=t["playing"];for(const t of this._lastAIState)t.hasOwnProperty("tag")&&!t.hasOwnProperty("tags")&&(t["tags"]=[t["tag"]].filter((t=>!!t)));this._lastFxState=t["effects"],this._lastAnalysersData=t["analysers"]}_OnAfterLoad(){if(-1!==this._loadListenerUid&&(this._listenerInst=this._runtime.GetInstanceByUID(this._loadListenerUid),this._loadListenerUid=-1,this._listenerInst)){const t=this._listenerInst.GetWorldInfo();this._listenerPos[0]=t.GetX(),this._listenerPos[1]=t.GetY()}for(const t of this._lastAIState){const e=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t["bufferOriginalUrl"]);e?(t["bufferUrl"]=e.url,t["bufferType"]=e.type):t["bufferUrl"]=null}for(const t of Object.values(this._lastFxState))for(const e of t)if(e.hasOwnProperty("bufferOriginalUrl")){const t=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e["bufferOriginalUrl"]);t&&(e["bufferUrl"]=t.url,e["bufferType"]=t.type)}this.PostToDOM("load-state",{"saveLoadMode":this._saveLoadMode,"timeScale":this._runtime.GetTimeScale(),"gameTime":this._runtime.GetGameTimeRaw(),"listenerPos":this._listenerPos,"listenerOrientation":[...this._listenerForwardVec,...this._listenerUpVec],"isSilent":this._isSilent,"masterVolume":this._masterVolume,"playing":this._lastAIState.filter((t=>null!==t["bufferUrl"])),"effects":this._lastFxState})}GetDebuggerProperties(){const t=[];for(const[e,s]of Object.entries(this._lastFxState))t.push({name:"$"+e,value:s.map((t=>t["type"])).join(", ")});const e="plugins.audio.debugger";return[{title:e+".tag-effects",properties:t},{title:e+".currently-playing",properties:[{name:e+".currently-playing-count",value:this._lastAIState.length},...this._lastAIState.map(((t,e)=>({name:"$#"+e,value:`${t["bufferOriginalUrl"]} ("${t["tags"]}") ${Math.round(10*t["playbackTime"])/10} / ${Math.round(10*t["duration"])/10}`})))]}]}}}self.C3.Plugins.Audio.Cnds={OnEnded(t){return this._MatchTriggerTag(t)},OnFadeEnded(t){return this._MatchTriggerTag(t)},PreloadsComplete(){return this._preloadCount===this._preloadTotal},AdvancedAudioSupported:()=>!0,IsSilent(){return this._IsSilent()},IsAnyPlaying(){for(const t of this._lastAIState)if(t["isPlaying"])return!0;return!1},IsTagPlaying(t){return this._IsTagPlaying(t)}};{const l=self.C3,h=["lowpass","highpass","bandpass","lowshelf","highshelf","peaking","notch","allpass"];l.Plugins.Audio.Acts={Play(t,e,s,i,a){const n=l.Plugins.Audio.Acts._DoPlay.call(this,t,e,s,i,a);return this._AddActionPromise(n),n},PlayFromTimeline(t,e,s,i){l.Plugins.Audio.Acts._DoPlay.call(this,t,0,e,0,s,i)},async _DoPlay(t,e,s,i,a,n){if(this._isSilent)return;const r=t[1],o=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);if(!o)return;const{playOffset:h,isTrueClock:u}=this._GetScheduledPlayInfo(),c=this._MaybeMarkAsPlaying(t[0],a,r,0!==e,this.DbToLinear(s));try{await this.PostToDOMAsync("play",{"originalUrl":t[0],"url":o.url,"type":o.type,"isMusic":r,"tags":this._SplitTags(a),"isLooping":0!==e,"vol":this.DbToLinear(s),"stereoPan":l.clamp(i/100,-1,1),"pos":n||0,"off":h,"trueClock":u})}finally{c&&(c["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayAtPosition(t,e,s,i,a,n,r,o,h,u,c){if(this._isSilent)return;const d=t[1],_=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);if(!_)return;const{playOffset:f,isTrueClock:p}=this._GetScheduledPlayInfo(),g=this._MaybeMarkAsPlaying(t[0],c,d,0!==e,this.DbToLinear(s));try{await this.PostToDOMAsync("play",{"originalUrl":t[0],"url":_.url,"type":_.type,"isMusic":d,"tags":this._SplitTags(c),"isLooping":0!==e,"vol":this.DbToLinear(s),"pos":0,"off":f,"trueClock":p,"panning":{"x":i,"y":a,"z":n,"angle":l.toRadians(r),"innerAngle":l.toRadians(o),"outerAngle":l.toRadians(h),"outerGain":this.DbToLinear(u)}})}finally{g&&(g["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayAtObject(t,e,s,i,a,n,r,o){if(this._isSilent)return;if(!i)return;const h=i.GetFirstPicked();if(!h||!h.GetWorldInfo())return;const u=h.GetWorldInfo(),c=u.GetLayer().GetAngle(),[d,_]=this.rotatePtAround(u.GetX(),u.GetY(),-c,this._listenerPos[0],this._listenerPos[1]),f=t[1],p=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);if(!p)return;const{playOffset:g,isTrueClock:y}=this._GetScheduledPlayInfo(),m=this._MaybeMarkAsPlaying(t[0],o,f,0!==e,this.DbToLinear(s));try{await this.PostToDOMAsync("play",{"originalUrl":t[0],"url":p.url,"type":p.type,"isMusic":f,"tags":this._SplitTags(o),"isLooping":0!==e,"vol":this.DbToLinear(s),"pos":0,"off":g,"trueClock":y,"panning":{"x":d,"y":_,"z":u.GetTotalZElevation(),"angle":u.GetAngle()-c,"innerAngle":l.toRadians(a),"outerAngle":l.toRadians(n),"outerGain":this.DbToLinear(r),"uid":h.GetUID()}})}finally{m&&(m["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayByName(t,e,s,i,a,n){if(this._isSilent)return;const r=1===t,o=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());if(!o)return;const{playOffset:h,isTrueClock:u}=this._GetScheduledPlayInfo(),c=this._MaybeMarkAsPlaying(e,n,r,0!==s,this.DbToLinear(i));try{await this.PostToDOMAsync("play",{"originalUrl":e,"url":o.url,"type":o.type,"isMusic":r,"tags":this._SplitTags(n),"isLooping":0!==s,"vol":this.DbToLinear(i),"stereoPan":l.clamp(a/100,-1,1),"pos":0,"off":h,"trueClock":u})}finally{c&&(c["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayAtPositionByName(t,e,s,i,a,n,r,o,h,u,c,d){if(this._isSilent)return;const _=1===t,f=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());if(!f)return;const{playOffset:p,isTrueClock:g}=this._GetScheduledPlayInfo(),y=this._MaybeMarkAsPlaying(e,d,_,0!==s,this.DbToLinear(i));try{await this.PostToDOMAsync("play",{"originalUrl":e,"url":f.url,"type":f.type,"isMusic":_,"tags":this._SplitTags(d),"isLooping":0!==s,"vol":this.DbToLinear(i),"pos":0,"off":p,"trueClock":g,"panning":{"x":a,"y":n,"z":r,"angle":l.toRadians(o),"innerAngle":l.toRadians(h),"outerAngle":l.toRadians(u),"outerGain":this.DbToLinear(c)}})}finally{y&&(y["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayAtObjectByName(t,e,s,i,a,n,r,o,h){if(this._isSilent)return;if(this._isSilent)return;if(!a)return;const u=a.GetFirstPicked();if(!u||!u.GetWorldInfo())return;const c=u.GetWorldInfo(),d=c.GetLayer().GetAngle(),[_,f]=this.rotatePtAround(c.GetX(),c.GetY(),-d,this._listenerPos[0],this._listenerPos[1]),p=1===t,g=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());if(!g)return;const{playOffset:y,isTrueClock:m}=this._GetScheduledPlayInfo(),T=this._MaybeMarkAsPlaying(e,h,p,0!==s,this.DbToLinear(i));try{await this.PostToDOMAsync("play",{"originalUrl":e,"url":g.url,"type":g.type,"isMusic":p,"tags":this._SplitTags(h),"isLooping":0!==s,"vol":this.DbToLinear(i),"pos":0,"off":y,"trueClock":m,"panning":{"x":_,"y":f,"z":c.GetTotalZElevation(),"angle":c.GetAngle()-d,"innerAngle":l.toRadians(n),"outerAngle":l.toRadians(r),"outerGain":this.DbToLinear(o),"uid":u.GetUID()}})}finally{T&&(T["placeholder"]=this._runtime.GetTickCountNoSave())}},SetLooping(t,e){this.PostToDOM("set-looping",{"tags":this._SplitTags(t),"isLooping":0===e})},SetMuted(t,e){this.PostToDOM("set-muted",{"tags":this._SplitTags(t),"isMuted":0===e})},SetVolume(t,e){this.PostToDOM("set-volume",{"tags":this._SplitTags(t),"vol":this.DbToLinear(e)})},FadeVolume(t,e,s,i){this.PostToDOM("fade-volume",{"tags":this._SplitTags(t),"vol":this.DbToLinear(e),"duration":s,"stopOnEnd":0===i})},SetStereoPan(t,e){this.PostToDOM("set-stereo-pan",{"tags":this._SplitTags(t),"p":l.clamp(e/100,-1,1)})},async Preload(t){const e=t[1],s=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);s&&(this._preloadTotal++,await this.PostToDOMAsync("preload",{"originalUrl":t[0],"url":s.url,"type":s.type,"isMusic":e}),this._preloadCount++)},async PreloadByName(t,e){const s=1===t,i=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());i&&(this._preloadTotal++,await this.PostToDOMAsync("preload",{"originalUrl":e,"url":i.url,"type":i.type,"isMusic":s}),this._preloadCount++)},SetPlaybackRate(t,e){this.PostToDOM("set-playback-rate",{"tags":this._SplitTags(t),"rate":Math.max(e,0)})},Stop(t){this._MaybeMarkAsStopped(t),this.PostToDOM("stop",{"tags":this._SplitTags(t)})},StopAll(){this._StopAll()},SetPaused(t,e){this.PostToDOM("set-paused",{"tags":this._SplitTags(t),"paused":0===e})},Seek(t,e){this.PostToDOM("seek",{"tags":this._SplitTags(t),"pos":e})},SetSilent(t){2===t&&(t=this._IsSilent()?1:0),this._SetSilent(0===t)},SetMasterVolume(t){const e=this.DbToLinear(t);this._SetMasterVolume(e)},AddFilterEffect(t,e,s,i,a,n,r){const o=h[e];this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"filter","tags":this._SplitTags(t),"params":[o,s,i,a,n,l.clamp(r/100,0,1)]})},AddDelayEffect(t,e,s,i){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"delay","tags":this._SplitTags(t),"params":[e,this.DbToLinear(s),l.clamp(i/100,0,1)]})},AddFlangerEffect(t,e,s,i,a,n){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"flanger","tags":this._SplitTags(t),"params":[e/1e3,s/1e3,i,a/100,l.clamp(n/100,0,1)]})},AddPhaserEffect(t,e,s,i,a,n,r){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"phaser","tags":this._SplitTags(t),"params":[e,s,i,a,n,l.clamp(r/100,0,1)]})},AddConvolutionEffect(t,e,s,i){const a=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e[0]);a&&(this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"convolution","tags":this._SplitTags(t),"bufferOriginalUrl":e[0],"bufferUrl":a.url,"bufferType":a.type,"params":[0===s,l.clamp(i/100,0,1)]}))},AddGainEffect(t,e){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"gain","tags":this._SplitTags(t),"params":[this.DbToLinear(e)]})},AddStereoPanEffect(t,e){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"stereopan","tags":this._SplitTags(t),"params":[l.clamp(e/100,-1,1)]})},AddMuteEffect(t){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"gain","tags":this._SplitTags(t),"params":[0]})},AddTremoloEffect(t,e,s){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"tremolo","tags":this._SplitTags(t),"params":[e,l.clamp(s/100,0,1)]})},AddRingModEffect(t,e,s){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"ringmod","tags":this._SplitTags(t),"params":[e,l.clamp(s/100,0,1)]})},AddDistortionEffect(t,e,s,i,a,n){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"distortion","tags":this._SplitTags(t),"params":[this.DbToLinearNoCap(e),this.DbToLinearNoCap(s),i,this.DbToLinearNoCap(a),l.clamp(n/100,0,1)]})},AddCompressorEffect(t,e,s,i,a,n){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"compressor","tags":this._SplitTags(t),"params":[e,s,i,a/1e3,n/1e3]})},AddAnalyserEffect(t,e,s){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"analyser","tags":this._SplitTags(t),"params":[e,s]})},RemoveEffects(t){const e=this._SplitTags(t);for(const t of e)this._effectCount.set(t.toLowerCase(),0);this.PostToDOM("remove-effects",{"tags":e}),this._lastFxState={}},SetEffectParameter(t,e,s,i,a,n){this.PostToDOM("set-effect-param",{"tags":this._SplitTags(t),"index":Math.floor(e),"param":s,"value":i,"ramp":a,"time":n})},SetListenerObject(t){if(!t)return;const e=t.GetFirstPicked();e&&e.GetWorldInfo()&&(this._listenerInst=e)},SetListenerZ(t){this._listenerPos[2]=t},SetListenerOrientation(t,e,s,i,a,n){this._listenerForwardVec[0]=t,this._listenerForwardVec[1]=e,this._listenerForwardVec[2]=-s,this._listenerUpVec[0]=i,this._listenerUpVec[1]=a,this._listenerUpVec[2]=-n},ScheduleNextPlay(t){this._nextPlayTime=Math.max(t,0),this._nextPlayOffset=Math.max(t-performance.now()/1e3,0)},UnloadAudio(t){const e=t[1],s=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);s&&this.PostToDOM("unload",{"url":s.url,"type":s.type,"isMusic":e})},UnloadAudioByName(t,e){const s=1===t,i=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());i&&this.PostToDOM("unload",{"url":i.url,"type":i.type,"isMusic":s})},UnloadAll(){this.PostToDOM("unload-all")},AddRemoteURL(t,e,s){this._remoteUrls.set(s.toLowerCase(),{url:t,type:e})}}}{const u=self.C3;u.Plugins.Audio.Exps={Duration(t){const e=this._GetFirstAudioStateByTags(t);return e?e["duration"]:0},PlaybackTime(t){const e=this._GetFirstAudioStateByTags(t);return e?e["playbackTime"]:0},PlaybackRate(t){const e=this._GetFirstAudioStateByTags(t);return e?e["playbackRate"]:0},Volume(t){const e=this._GetFirstAudioStateByTags(t);return e?this.LinearToDb(e["volume"]):0},MasterVolume(){return this.LinearToDb(this._GetMasterVolume())},EffectCount(t){return this._effectCount.get(t.toLowerCase())||0},AnalyserFreqBinCount(t,e){const s=this.GetAnalyserData(t,Math.floor(e));return s?s["binCount"]:0},AnalyserFreqBinAt(t,e,s){const i=this.GetAnalyserData(t,Math.floor(e));return i?(s=Math.floor(s))<0||s>=i["binCount"]?0:i["freqBins"][s]:0},AnalyserPeakLevel(t,e){const s=this.GetAnalyserData(t,Math.floor(e));return s?s["peak"]:0},AnalyserRMSLevel(t,e){const s=this.GetAnalyserData(t,Math.floor(e));return s?s["rms"]:0},SampleRate(){return this._sampleRate},CurrentTime:()=>self["C3_GetAudioContextCurrentTime"]?self["C3_GetAudioContextCurrentTime"]():performance.now()/1e3,OutputLatency(){return this._outputLatency},NormalizedVolume(t,e){return 0===(t=u.clamp(+t,0,100)/100)?-1/0:t<.1?this.LinearToDb(u.lerp(0,this.DbToLinear(e),10*t)):u.lerp(e,0,(t-.1)/.9)}}}
}

// scripts/behaviors/scrollto/c3runtime/runtime.js
{
{const e=self.C3;e.Behaviors.scrollto=class extends e.SDKBehaviorBase{constructor(e){super(e),this._shakeMag=0,this._shakeStart=0,this._shakeEnd=0,this._shakeMode=0}Release(){super.Release()}SetShakeMagnitude(e){this._shakeMag=e}GetShakeMagnitude(){return this._shakeMag}SetShakeStart(e){this._shakeStart=e}GetShakeStart(){return this._shakeStart}SetShakeEnd(e){this._shakeEnd=e}GetShakeEnd(){return this._shakeEnd}SetShakeMode(e){this._shakeMode=e}GetShakeMode(){return this._shakeMode}}}{const e=self.C3;e.Behaviors.scrollto.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=0;e.Behaviors.scrollto.Instance=class extends e.SDKBehaviorInstanceBase{constructor(e,s){super(e),this._isEnabled=!0,s&&(this._isEnabled=s[t]),this._isEnabled&&this._StartTicking2()}Release(){super.Release()}SaveToJson(){const e=this.GetBehavior();return{"e":this._isEnabled,"smg":e.GetShakeMagnitude(),"ss":e.GetShakeStart(),"se":e.GetShakeEnd(),"smd":e.GetShakeMode()}}LoadFromJson(e){const t=this.GetBehavior();t.SetShakeMagnitude(e["smg"]),t.SetShakeStart(e["ss"]),t.SetShakeEnd(e["se"]),t.SetShakeMode(e["smd"]),this._isEnabled=e["e"],this._isEnabled?this._StartTicking2():this._StopTicking2()}_SetEnabled(e){this._isEnabled=!!e,this._isEnabled?this._StartTicking2():this._StopTicking2()}IsEnabled(){return this._isEnabled}Tick2(){if(!this.IsEnabled())return;this._runtime.GetDt(this._inst);const t=this.GetBehavior(),s=t.GetInstances();let a=0,i=0,h=0;for(const t of s){const s=t.GetBehaviorInstanceFromCtor(e.Behaviors.scrollto);if(!s||!s.GetSdkInstance().IsEnabled())continue;const n=t.GetWorldInfo();a+=n.GetX(),i+=n.GetY(),++h}const n=this._inst.GetWorldInfo().GetLayout(),r=this._runtime.GetGameTime();let o=0,S=0;if(r>=t.GetShakeStart()&&r<t.GetShakeEnd()){let e=t.GetShakeMagnitude()*Math.min(this._runtime.GetTimeScale(),1);0===t.GetShakeMode()&&(e*=1-(r-t.GetShakeStart())/(t.GetShakeEnd()-t.GetShakeStart()));const s=this._runtime.Random()*Math.PI*2,a=this._runtime.Random()*e;o=Math.cos(s)*a,S=Math.sin(s)*a}n.SetScrollX(a/h+o),n.SetScrollY(i/h+S)}GetPropertyValueByIndex(e){if(e===t)return this._isEnabled}SetPropertyValueByIndex(e,s){if(e===t)this._isEnabled=!!s,this._isEnabled?this._StartTicking2():this._StopTicking2()}GetDebuggerProperties(){return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:"behaviors.scrollto.properties.enabled.name",value:this.IsEnabled(),onedit:e=>this._SetEnabled(e)}]}]}}}self.C3.Behaviors.scrollto.Cnds={IsEnabled(){return this.IsEnabled()}};self.C3.Behaviors.scrollto.Acts={Shake(e,t,s){const a=this.GetBehavior();a.SetShakeMagnitude(e),a.SetShakeStart(this._runtime.GetGameTime()),a.SetShakeEnd(this._runtime.GetGameTime()+t),a.SetShakeMode(s)},SetEnabled(e){this._SetEnabled(0!==e)}};self.C3.Behaviors.scrollto.Exps={};
}

// scripts/behaviors/bound/c3runtime/runtime.js
{
{const e=self.C3;e.Behaviors.bound=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.bound.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=0;e.Behaviors.bound.Instance=class extends e.SDKBehaviorInstanceBase{constructor(e,s){super(e),this._mode=0,s&&(this._mode=s[t]),this._StartTicking2()}Release(){super.Release()}SaveToJson(){return{"m":this._mode}}LoadFromJson(e){this._mode=e["m"]}Tick2(){const e=this._inst.GetWorldInfo(),t=e.GetBoundingBox(),s=e.GetLayout();let o=!1;0===this._mode?(e.GetX()<0&&(e.SetX(0),o=!0),e.GetY()<0&&(e.SetY(0),o=!0),e.GetX()>s.GetWidth()&&(e.SetX(s.GetWidth()),o=!0),e.GetY()>s.GetHeight()&&(e.SetY(s.GetHeight()),o=!0)):(t.getLeft()<0&&(e.OffsetX(-t.getLeft()),o=!0),t.getTop()<0&&(e.OffsetY(-t.getTop()),o=!0),t.getRight()>s.GetWidth()&&(e.OffsetX(-(t.getRight()-s.GetWidth())),o=!0),t.getBottom()>s.GetHeight()&&(e.OffsetY(-(t.getBottom()-s.GetHeight())),o=!0)),o&&e.SetBboxChanged()}GetPropertyValueByIndex(e){if(e===t)return this._mode}SetPropertyValueByIndex(e,s){if(e===t)this._mode=s}}}self.C3.Behaviors.bound.Cnds={};self.C3.Behaviors.bound.Acts={};self.C3.Behaviors.bound.Exps={};
}

// scripts/behaviors/Physics/c3runtime/runtime.js
{
{const t=self.C3,e=self.C3X;let i=null,s=null,n=[],o=null,r=null;const a="Physics_DisabledCollisions";function SetObjectTypeCollisionsEnabled(t,e,i){const s=t.GetSavedDataMap(),n=e.GetSavedDataMap();if(i){const i=s.get(a);i&&i.delete(e.GetSID());const o=n.get(a);o&&o.delete(t.GetSID())}else{let i=s.get(a);i||(i=new Set,s.set(a,i));let o=n.get(a);o||(o=new Set,n.set(a,o)),i.add(e.GetSID()),o.add(t.GetSID())}}t.Behaviors.Physics=class extends t.SDKBehaviorBase{constructor(t){super(t),r=this,this._world=null,this._worldG=10,this._worldScale=.02,this._worldManifold=null,this._lastUpdateTick=-1,this._steppingMode=1,this._velocityIterations=8,this._positionIterations=3,this._allCollisionsEnabled=!0,this._runtime.AddLoadPromise(this._LoadBox2DWasm())}GetScriptInterfaceClass(){return self.IPhysicsBehavior}async _LoadBox2DWasm(){const t=await this._runtime.GetAssetManager().GetProjectFileUrl("box2d.wasm");await new Promise((e=>{self["Box2DWasmModule"]({"wasmBinaryFile":t}).then((t=>{o=t,this._InitBox2DWorld(),e()}))}))}_InitBox2DWorld(){const e=this._runtime.GetCollisionEngine();i=t.Behaviors.Physics.GetVec2(0,0),s=t.Behaviors.Physics.GetVec2(0,0),this._world=new o["b2World"](t.Behaviors.Physics.GetTempVec2A(0,this._worldG),!0);const n=new o["JSContactListener"];n["BeginContact"]=i=>{const s=o["wrapPointer"](i,o["b2Contact"]),n=t.Behaviors.Physics.Instance.LookupBehInstFromBody(s["GetFixtureA"]()["GetBody"]()),r=t.Behaviors.Physics.Instance.LookupBehInstFromBody(s["GetFixtureB"]()["GetBody"]());e.RegisterCollision(n.GetObjectInstance(),r.GetObjectInstance())},n["EndContact"]=()=>{},n["PreSolve"]=()=>{},n["PostSolve"]=()=>{},this._world["SetContactListener"](n);const r=new o["JSContactFilter"];r["ShouldCollide"]=(e,i)=>{if(this._allCollisionsEnabled)return!0;const s=o["wrapPointer"](e,o["b2Fixture"]),n=o["wrapPointer"](i,o["b2Fixture"]),r=t.Behaviors.Physics.Instance.LookupBehInstFromBody(s["GetBody"]()),l=t.Behaviors.Physics.Instance.LookupBehInstFromBody(n["GetBody"]()),h=r.GetObjectInstance().GetObjectClass(),_=l.GetObjectInstance().GetObjectClass(),c=h.GetSID(),d=_.GetSID(),u=h.GetSavedDataMap().get(a);if(u&&u.has(d))return!1;const y=_.GetSavedDataMap().get(a);return!y||!y.has(c)},this._world["SetContactFilter"](r),this._worldManifold=new o["b2WorldManifold"]}Release(){super.Release()}GetBox2D(){return o}GetWorld(){return this._world}GetWorldScale(){return this._worldScale}GetSteppingMode(){return this._steppingMode}SetSteppingMode(t){this._steppingMode=t}SetLastUpdateTick(t){this._lastUpdateTick=t}GetLastUpdateTick(){return this._lastUpdateTick}SetVelocityIterations(t){this._velocityIterations=Math.max(t,1)}GetVelocityIterations(){return this._velocityIterations}SetPositionIterations(t){this._positionIterations=Math.max(t,1)}GetPositionIterations(){return this._positionIterations}SetIterations(t,e){this.SetVelocityIterations(t),this.SetPositionIterations(e)}GetGravity(){return this._worldG}SetGravity(e){e!==this._worldG&&(this._world["SetGravity"](t.Behaviors.Physics.GetTempVec2A(0,e)),this._worldG=e,this._WakeUpAllPhysicsBodies())}_WakeUpAllPhysicsBodies(){for(const e of this.GetInstances()){const i=t.Behaviors.Physics.Instance.LookupBehInstFromInst(e);if(!i)continue;const s=i.GetBody();s&&s["SetAwake"](!0)}}DisableShouldCollideFastPath(){this._allCollisionsEnabled=!1}SetCollisionsEnabled(t,e,i){if(i=!!i,t&&e){if(e.IsFamily())for(const s of e.GetFamilyMembers())SetObjectTypeCollisionsEnabled(t,s,i);else SetObjectTypeCollisionsEnabled(t,e,i);this.DisableShouldCollideFastPath()}}GetWorldManifold(){return this._worldManifold}static GetPhysicsCollisionKey(){return a}static GetVec2(t,e){if(n.length){const i=n.pop();return i["set_x"](t),i["set_y"](e),i}return new(0,o["b2Vec2"])(t,e)}static FreeVec2(t){n.push(t)}static GetTempVec2A(t,e){return i["set_x"](t),i["set_y"](e),i}static GetTempVec2B(t,e){return s["set_x"](t),s["set_y"](e),s}static CreatePolygonShape(t){const e=new(0,o["b2PolygonShape"]),i=o["_malloc"](8*t.length);let s=0;for(let e=0;e<t.length;++e)o["HEAPF32"][i+s>>2]=t[e]["get_x"](),o["HEAPF32"][i+(s+4)>>2]=t[e]["get_y"](),s+=8;const n=o["wrapPointer"](i,o["b2Vec2"]);return e["Set"](n,t.length),o["_free"](i),e}};const l=["fixed","variable"];self.IPhysicsBehavior=class extends self.IBehavior{constructor(){super()}set worldGravity(t){e.RequireFiniteNumber(t),r.SetGravity(t)}get worldGravity(){return r.GetGravity()}set steppingMode(t){const e=l.indexOf(t);if(e<0)throw new Error("invalid stepping mode");r.SetSteppingMode(l[e])}get steppingMode(){return l[r.GetSteppingMode()]}set velocityIterations(t){e.RequireFiniteNumber(t),r.SetVelocityIterations(t)}get velocityIterations(){return r.GetVelocityIterations()}set positionIterations(t){e.RequireFiniteNumber(t),r.SetPositionIterations(t)}get positionIterations(){return r.GetPositionIterations()}setCollisionsEnabled(t,e,i){const s=r.GetRuntime(),n=s._UnwrapIObjectClass(t),o=s._UnwrapIObjectClass(e);i=!!i,r.SetCollisionsEnabled(n,o,i)}}}{const h=self.C3;h.Behaviors.Physics.Type=class extends h.SDKBehaviorTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const _=self.C3,c=self.C3X,d=self.IBehaviorInstance,u=(self.assert,0),y=1,p=2,g=3,m=4,b=5,G=6,I=7,S=8,f=9,C=new WeakMap,A=new WeakMap,D=new WeakMap,v=-2147483648,B=1073741824,w=536870912,F=3758096384,P=_.Behaviors.Physics.GetTempVec2A,M=_.Behaviors.Physics.GetTempVec2B,R=_.New(_.Rect),E=_.New(_.Quad);_.Behaviors.Physics.Instance=class extends _.SDKBehaviorInstanceBase{constructor(t,e){super(t);const i=this.GetBehavior(),s=this.GetWorldInfo();this._box2d=i.GetBox2D(),this._world=i.GetWorld(),this._worldScale=i.GetWorldScale(),this._isImmovable=!1,this._collisionMask=0,this._actualCollisionMask=0,this._preventRotation=!1,this._density=1,this._friction=.5,this._restitution=.2,this._linearDamping=0,this._angularDamping=.01,this._isBullet=!1,this._isEnabled=!0,this._body=null,this._fixtures=[],this._myJoints=[],this._myCreatedJoints=[],this._joiningMe=new Set,this._lastKnownX=s.GetX(),this._lastKnownY=s.GetY(),this._lastKnownAngle=s.GetAngle(),this._lastWidth=0,this._lastHeight=0,this._lastTickOverride=!1,e&&(this._isImmovable=!!e[u],this._collisionMask=e[y],this._preventRotation=!!e[p],this._density=e[g],this._friction=e[m],this._restitution=e[b],this._linearDamping=e[G],this._angularDamping=e[I],this._isBullet=!!e[S],this._isEnabled=!!e[f]);const n=this._runtime.Dispatcher();this._disposables=new _.CompositeDisposable(_.Disposable.From(n,"instancedestroy",(t=>this._OnInstanceDestroyed(t.instance))),_.Disposable.From(n,"beforeload",(()=>this._OnBeforeLoad())),_.Disposable.From(n,"afterload",(()=>this._OnAfterLoad()))),A.set(this._inst,this),this._isEnabled&&this._StartTicking()}PostCreate(){this._CreateBody()}Release(){this._DestroyMyJoints(),_.clearArray(this._myCreatedJoints),this._joiningMe.clear(),this._body&&(this._DestroyFixtures(),this._world["DestroyBody"](this._body),this._body=null),super.Release()}_CreateFixture(t){if(!this._body)return;const e=this._body["CreateFixture"](t);return this._fixtures.push(e),e}_DestroyFixtures(){if(this._body){for(const t of this._fixtures)this._body["DestroyFixture"](t);_.clearArray(this._fixtures)}}_GetBoundingQuadExcludingMesh(){const t=this.GetWorldInfo();return t.HasMesh()?(t.CalculateBbox(R,E,!1),E):t.GetBoundingQuad()}_Destroy(t){this._box2d["destroy"](t)}_CreateBody(){if(!this._isEnabled)return;const t=this._box2d["b2FixtureDef"],e=this._box2d["b2BodyDef"],i=this.GetWorldInfo(),s=i.HasOwnCollisionPoly();if(this._actualCollisionMask=this._collisionMask,s||this._inst.HasTilemap()||0!==this._actualCollisionMask||(this._actualCollisionMask=1),!this._body){const t=new e;t["set_type"](this._isImmovable?0:2);let s=i.GetX()*this._worldScale,n=i.GetY()*this._worldScale;if(2===this._actualCollisionMask){const t=this._GetBoundingQuadExcludingMesh();s=t.midX()*this._worldScale,n=t.midY()*this._worldScale}t["set_position"](M(s,n)),t["set_angle"](i.GetAngle()),t["set_fixedRotation"](this._preventRotation),t["set_linearDamping"](this._linearDamping),t["set_angularDamping"](this._angularDamping),t["set_bullet"](this._isBullet),this._body=this._world["CreateBody"](t),this._Destroy(t),C.set(this._body,this)}this._DestroyFixtures();const n=new t;n["set_density"](this._density),n["set_friction"](this._friction),n["set_restitution"](this._restitution);const o=Math.max(Math.abs(i.GetWidth()),1),r=Math.max(Math.abs(i.GetHeight()),1);0===this._actualCollisionMask?this._inst.HasTilemap()?this._CreateTilemapFixtures(n):this._CreatePolygonFixture(n,o,r):1===this._actualCollisionMask?this._CreateBoundingBoxFixture(n,i,o,r):this._CreateCircleFixture(n,o,r),this._lastWidth=i.GetWidth(),this._lastHeight=i.GetHeight(),i.SetPhysicsBodyChanged(!1),this._Destroy(n)}_CreateBoundingBoxFixture(t,e,i,s){const n=new(0,this._box2d["b2PolygonShape"]),o=i*this._worldScale,r=s*this._worldScale;let a=e.GetOriginX(),l=e.GetOriginY();e.GetWidth()<0&&(a=1-a),e.GetHeight()<0&&(l=1-l);const h=(.5-a)*o,c=(.5-l)*r,d=_.Behaviors.Physics.GetVec2(h,c);n["SetAsBox"](o/2,r/2,d,0),t["set_shape"](n),this._CreateFixture(t),this._Destroy(n),_.Behaviors.Physics.FreeVec2(d)}_CreateCircleFixture(t,e,i){const s=new(0,this._box2d["b2CircleShape"]);s["set_m_radius"](Math.min(e,i)*this._worldScale*.5),t["set_shape"](s),this._CreateFixture(t),this._Destroy(s)}_CreatePolygonFixture(t,e,i){const s=this.GetWorldInfo(),n=s.GetWidth()<0,o=s.GetHeight()<0,r=this._worldScale,a=s.GetCustomTransformedCollisionPoly(n?-e:e,o?-i:i,0).pointsArr(),l=a.length/2,h=[];for(let t=0;t<l;++t)h.push(_.Behaviors.Physics.GetVec2(a[2*t],a[2*t+1]));n!==o&&h.reverse();const c=_.Behaviors.Physics.Separator.Separate(h,e*i);for(const t of h)_.Behaviors.Physics.FreeVec2(t);if(c.length)for(const e of c){for(const t of e)t["set_x"](t["get_x"]()*r),t["set_y"](t["get_y"]()*r);const i=_.Behaviors.Physics.CreatePolygonShape(e);t["set_shape"](i),this._CreateFixture(t),this._Destroy(i);for(const t of e)_.Behaviors.Physics.FreeVec2(t)}else this._CreateBoundingBoxFixture(t,s,e,i)}_CreateTilemapFixtures(t){const e=this._worldScale,i=_.Behaviors.Physics.GetVec2,s=_.Behaviors.Physics.FreeVec2,n=[];this._inst.GetSdkInstance().GetAllCollisionRects(n);const o=[];for(let r=0,a=n.length;r<a;++r){const a=n[r],l=a.GetRect(),h=a.GetPoly();if(h){let n=D.get(h);if(!n){const t=h.pointsArr(),e=h.pointCount();for(let s=0;s<e;++s)o.push(i(t[2*s],t[2*s+1]));const r=a.GetTileId()&F;(r===v||r===B||r===w||r&v&&r&B&&r&w)&&o.reverse(),n=_.Behaviors.Physics.Separator.Separate(o,l.width()*l.height()),D.set(h,n);for(const t of o)s(t);_.clearArray(o)}for(let r=0,a=n.length;r<a;++r){const a=n[r];for(let t=0,s=a.length;t<s;++t)o.push(i((l.getLeft()+a[t]["get_x"]())*e,(l.getTop()+a[t]["get_y"]())*e));const h=_.Behaviors.Physics.CreatePolygonShape(o);t["set_shape"](h),this._CreateFixture(t),this._Destroy(h);for(const t of o)s(t);_.clearArray(o)}}else{o.push(i(l.getLeft()*e,l.getTop()*e)),o.push(i(l.getRight()*e,l.getTop()*e)),o.push(i(l.getRight()*e,l.getBottom()*e)),o.push(i(l.getLeft()*e,l.getBottom()*e));const s=_.Behaviors.Physics.CreatePolygonShape(o);t["set_shape"](s),this._CreateFixture(t),this._Destroy(s)}for(const t of o)s(t);_.clearArray(o)}}_DestroyBody(){this._body&&(this._DestroyMyJoints(),C.delete(this._body),this._DestroyFixtures(),this._world["DestroyBody"](this._body),this._body=null)}_DestroyMyJoints(){for(const t of this._myJoints)this._world["DestroyJoint"](t);_.clearArray(this._myJoints)}_RecreateMyJoints(){for(const t of this._myCreatedJoints)switch(t.type){case 0:this._DoCreateDistanceJoint(...t.params);break;case 1:this._DoCreateRevoluteJoint(...t.params);break;case 2:this._DoCreateLimitedRevoluteJoint(...t.params);break;case 3:this._DoCreatePrismaticJoint(...t.params)}}_GetInstImagePoint(t){const e=this.GetWorldInfo();if(-1===t)return[e.GetX(),e.GetY()];if(0===t&&this._body){const t=this._body["GetWorldCenter"]();return[t["get_x"]()/this._worldScale,t["get_y"]()/this._worldScale]}return this._inst.GetImagePoint(t)}_CreateDistanceJoint(t,e,i,s,n){if(!this._isEnabled||!e||e===this._inst)return;const o=_.Behaviors.Physics.Instance.LookupBehInstFromInst(e);o&&o._IsEnabled()&&(this._myCreatedJoints.push({type:0,params:[t,e.GetUID(),i,s,n]}),this._DoCreateDistanceJoint(t,e.GetUID(),i,s,n))}_DoCreateDistanceJoint(t,e,i,s,n){if(!this._isEnabled)return;const o=this._runtime.GetInstanceByUID(e);if(!o||o===this._inst)return;const r=_.Behaviors.Physics.Instance.LookupBehInstFromInst(o);if(!r||!r._IsEnabled())return;r._joiningMe.add(this._inst),this._UpdateBodyToMatchInstance(!1),r._UpdateBodyToMatchInstance(!1);const[a,l]=this._GetInstImagePoint(t),[h,c]=o.GetImagePoint(i),d=a-h,u=l-c,y=this._box2d["b2DistanceJointDef"],p=this._worldScale,g=new y;g["Initialize"](this._body,r.GetBody(),P(a*p,l*p),M(h*p,c*p)),g["set_length"](Math.hypot(d,u)*p),g["set_dampingRatio"](s),g["set_frequencyHz"](n),this._myJoints.push(this._world["CreateJoint"](g)),this._Destroy(g)}_CreateRevoluteJoint(t,e){if(!this._isEnabled||!e||e===this._inst)return;const i=_.Behaviors.Physics.Instance.LookupBehInstFromInst(e);i&&i._IsEnabled()&&(this._myCreatedJoints.push({type:1,params:[t,e.GetUID()]}),this._DoCreateRevoluteJoint(t,e.GetUID()))}_DoCreateRevoluteJoint(t,e){if(!this._isEnabled)return;const i=this._runtime.GetInstanceByUID(e);if(!i||i===this._inst)return;const s=_.Behaviors.Physics.Instance.LookupBehInstFromInst(i);if(!s||!s._IsEnabled())return;s._joiningMe.add(this._inst),this._UpdateBodyToMatchInstance(!1),s._UpdateBodyToMatchInstance(!1);const[n,o]=this._GetInstImagePoint(t),r=this._box2d["b2RevoluteJointDef"],a=this._worldScale,l=new r;l["Initialize"](this._body,s.GetBody(),P(n*a,o*a)),this._myJoints.push(this._world["CreateJoint"](l)),this._Destroy(l)}_CreateLimitedRevoluteJoint(t,e,i,s){if(!this._isEnabled||!e||e===this._inst)return;const n=_.Behaviors.Physics.Instance.LookupBehInstFromInst(e);n&&n._IsEnabled()&&(i=_.toDegrees(i),s=_.toDegrees(s),this._myCreatedJoints.push({type:2,params:[t,e.GetUID(),i,s]}),this._DoCreateLimitedRevoluteJoint(t,e.GetUID(),i,s))}_DoCreateLimitedRevoluteJoint(t,e,i,s){if(!this._isEnabled)return;const n=this._runtime.GetInstanceByUID(e);if(!n||n===this._inst)return;const o=_.Behaviors.Physics.Instance.LookupBehInstFromInst(n);if(!o||!o._IsEnabled())return;o._joiningMe.add(this._inst),this._UpdateBodyToMatchInstance(!1),o._UpdateBodyToMatchInstance(!1);const[r,a]=this._GetInstImagePoint(t),l=this._box2d["b2RevoluteJointDef"],h=this._worldScale,c=new l;c["Initialize"](this._body,o.GetBody(),P(r*h,a*h)),c["set_enableLimit"](!0),c["set_lowerAngle"](_.toRadians(i)),c["set_upperAngle"](_.toRadians(s)),this._myJoints.push(this._world["CreateJoint"](c)),this._Destroy(c)}_CreatePrismaticJoint(t,e,i,s,n,o,r,a,l){if(!this._isEnabled||!e||e===this._inst)return;const h=_.Behaviors.Physics.Instance.LookupBehInstFromInst(e);h&&h._IsEnabled()&&(i=_.toDegrees(i),a=_.toDegrees(a),this._myCreatedJoints.push({type:3,params:[t,e.GetUID(),i,s,n,o,r,a,l]}),this._DoCreatePrismaticJoint(t,e.GetUID(),i,s,n,o,r,a,l))}_DoCreatePrismaticJoint(t,e,i,s,n,o,r,a,l){if(!this._isEnabled)return;const h=this._runtime.GetInstanceByUID(e);if(!h||h===this._inst)return;const c=_.Behaviors.Physics.Instance.LookupBehInstFromInst(h);if(!c||!c._IsEnabled())return;c._joiningMe.add(this._inst),this._UpdateBodyToMatchInstance(!1),c._UpdateBodyToMatchInstance(!1);const[d,u]=this._GetInstImagePoint(t);i=_.toRadians(i);const y=Math.cos(i),p=Math.sin(i),g=this._box2d["b2PrismaticJointDef"],m=this._worldScale,b=new g;b["Initialize"](this._body,c.GetBody(),P(d*m,u*m),M(y,p)),b["set_enableLimit"](!!s),b["set_lowerTranslation"](n*m),b["set_upperTranslation"](o*m),b["set_enableMotor"](!!r),b["set_motorSpeed"](_.toRadians(a)),b["set_maxMotorForce"](l),this._myJoints.push(this._world["CreateJoint"](b)),this._Destroy(b)}_RemoveJoints(){this._isEnabled&&(this._DestroyMyJoints(),_.clearArray(this._myCreatedJoints),this._joiningMe.clear())}_RemoveOtherInstanceJointsToMe(){for(const t of this._joiningMe){const e=_.Behaviors.Physics.Instance.LookupBehInstFromInst(t);if(!e||!e._IsEnabled())return;e._DestroyJointsForInstance(this._inst)}this._joiningMe.clear()}_OnInstanceDestroyed(t){this._DestroyJointsForInstance(t)}_DestroyJointsForInstance(t){const e=t.GetUID();let i=0;for(let t=0,s=this._myCreatedJoints.length;t<s;++t)this._myCreatedJoints[i]=this._myCreatedJoints[t],i<this._myJoints.length&&(this._myJoints[i]=this._myJoints[t]),this._myCreatedJoints[t].params[1]===e?t<this._myJoints.length&&this._world["DestroyJoint"](this._myJoints[t]):++i;_.truncateArray(this._myCreatedJoints,i),i<this._myJoints.length&&_.truncateArray(this._myJoints,i),this._joiningMe.delete(t)}GetBody(){return this._body}static LookupBehInstFromBody(t){return C.get(t)||null}static LookupBehInstFromInst(t){return A.get(t)||null}SaveToJson(){const t={"e":this._isEnabled,"im":this._isImmovable,"pr":this._preventRotation,"d":this._density,"fr":this._friction,"re":this._restitution,"ld":this._linearDamping,"ad":this._angularDamping,"b":this._isBullet,"mcj":this._myCreatedJoints};if(this._isEnabled){const e=this._body["GetLinearVelocity"]();t["vx"]=e["get_x"](),t["vy"]=e["get_y"](),t["om"]=this._body["GetAngularVelocity"]()}return t}_OnBeforeLoad(){this._DestroyMyJoints(),_.clearArray(this._myCreatedJoints),this._joiningMe.clear()}LoadFromJson(t){this._DestroyBody(),this._isEnabled=t["e"],t.hasOwnProperty("im")&&(this._isImmovable=!!t["im"]),this._preventRotation=t["pr"],this._density=t["d"],this._friction=t["fr"],this._restitution=t["re"],this._linearDamping=t["ld"],this._angularDamping=t["ad"],this._isBullet=t["b"],this._myCreatedJoints=t["mcj"];const e=this.GetWorldInfo();this._lastKnownX=e.GetX(),this._lastKnownY=e.GetY(),this._lastKnownAngle=e.GetAngle(),this._lastWidth=e.GetWidth(),this._lastHeight=e.GetHeight(),this._isEnabled&&(this._CreateBody(),this._body["SetLinearVelocity"](P(t["vx"],t["vy"])),this._body["SetAngularVelocity"](t["om"]),0===t["vx"]&&0===t["vy"]&&0===t["om"]||this._body["SetAwake"](!0),this._myCreatedJoints=t["mcj"]),this._isEnabled?this._StartTicking():this._StopTicking()}_OnAfterLoad(){this._isEnabled&&this._RecreateMyJoints()}Tick(){if(!this._isEnabled)return;const t=this._runtime,e=this.GetBehavior();let i=0;0===e.GetSteppingMode()?i=t.GetTimeScale()/60:(i=t.GetDt(this._inst),i>1/30&&(i=1/30));const s=t.GetTickCountNoSave();s>e.GetLastUpdateTick()&&t.GetTimeScale()>0&&(0!==i&&this._world["Step"](i,e.GetVelocityIterations(),e.GetPositionIterations()),this._world["ClearForces"](),e.SetLastUpdateTick(s)),this._UpdateBodyToMatchInstance(!0)}_UpdateBodyToMatchInstance(t){const e=this._inst.GetWorldInfo(),i=this._worldScale;(e.GetWidth()!==this._lastWidth||e.GetHeight()!==this._lastHeight||e.IsPhysicsBodyChanged())&&this._CreateBody();const s=this._body,n=e.GetX(),o=e.GetY(),r=n-this._lastKnownX,a=o-this._lastKnownY,l=Math.abs(r)>.001||Math.abs(a)>.001,h=e.GetAngle()!==this._lastKnownAngle;let _=n,c=o;if(2===this._actualCollisionMask){const t=this._GetBoundingQuadExcludingMesh();_=t.midX(),c=t.midY()}l?(h?s["SetTransform"](P(_*i,c*i),e.GetAngle()):s["SetTransform"](P(_*i,c*i),s["GetAngle"]()),t&&(s["SetLinearVelocity"](P(r,a)),this._lastTickOverride=!0),s["SetAwake"](!0)):t&&this._lastTickOverride&&(this._lastTickOverride=!1,s["SetLinearVelocity"](P(0,0)),s["SetTransform"](P(_*i,c*i),s["GetAngle"]())),!l&&h&&(s["SetTransform"](s["GetPosition"](),e.GetAngle()),s["SetAwake"](!0));const d=s["GetPosition"](),u=d["get_x"]()/i,y=d["get_y"]()/i,p=s["GetAngle"]();if((u!==e.GetX()||y!==e.GetY()||p!==e.GetAngle())&&(e.SetXY(u,y),e.SetAngle(p),e.SetBboxChanged(),2===this._actualCollisionMask)){const t=this._GetBoundingQuadExcludingMesh(),i=t.midX()-e.GetX(),s=t.midY()-e.GetY();0===i&&0===s||(e.OffsetXY(-i,-s),e.SetBboxChanged())}this._lastKnownX=e.GetX(),this._lastKnownY=e.GetY(),this._lastKnownAngle=e.GetAngle()}GetPropertyValueByIndex(t){switch(t){case p:return this._IsPreventRotate();case g:return this._GetDensity();case m:return this._GetFriction();case b:return this._GetElasticity();case G:return this._GetLinearDamping();case I:return this._GetAngularDamping();case S:return this._IsBullet();case f:return this._IsEnabled()}}SetPropertyValueByIndex(t,e){switch(t){case p:this._SetPreventRotate(e);break;case g:this._SetDensity(e);break;case m:this._SetFriction(e);break;case b:this._SetElasticity(e);break;case G:this._SetLinearDamping(e);break;case I:this._SetAngularDamping(e);break;case S:this._SetBullet(e);break;case f:this._SetEnabled(e)}}_SetEnabled(t){t=!!t,this._isEnabled&&!t?(this._RemoveOtherInstanceJointsToMe(),this._DestroyBody(),this._isEnabled=!1,this._StopTicking()):!this._isEnabled&&t&&(this._isEnabled=!0,this._CreateBody(),this._StartTicking())}_IsEnabled(){return this._isEnabled}GetDebuggerProperties(){const t="behaviors.physics",e=[{name:t+".properties.enabled.name",value:this._IsEnabled(),onedit:t=>this._SetEnabled(t)},{name:t+".properties.immovable.name",value:this._IsImmovable(),onedit:t=>this._SetImmovable(t)},{name:t+".properties.density.name",value:this._GetDensity(),onedit:t=>this._SetDensity(t)},{name:t+".properties.friction.name",value:this._GetFriction(),onedit:t=>this._SetFriction(t)},{name:t+".properties.elasticity.name",value:this._GetElasticity(),onedit:t=>this._SetElasticity(t)},{name:t+".properties.linear-damping.name",value:this._GetLinearDamping(),onedit:t=>this._SetLinearDamping(t)},{name:t+".properties.angular-damping.name",value:this._GetAngularDamping(),onedit:t=>this._SetAngularDamping(t)}];return this._isEnabled&&(e.push({name:t+".debugger.is-sleeping",value:!this._IsAwake()}),e.push({name:t+".debugger.velocity-x",value:this._GetVelocityX(),onedit:t=>this._SetVelocity(t,this._GetVelocityY())}),e.push({name:t+".debugger.velocity-y",value:this._GetVelocityY(),onedit:t=>this._SetVelocity(this._GetVelocityX(),t)}),e.push({name:t+".debugger.angular-velocity",value:_.toDegrees(this._GetAngularVelocity()),onedit:t=>this._SetAngularVelocity(_.toRadians(t))}),e.push({name:t+".debugger.mass",value:this._GetMass()})),[{title:"$"+this.GetBehaviorType().GetName(),properties:e}]}_ApplyForce(t,e,i){const[s,n]=this._GetInstImagePoint(i);this._DoApplyForce(t,e,s,n)}_ApplyForceToward(t,e,i,s){const[n,o]=this._GetInstImagePoint(s),r=_.angleTo(n,o,e,i);this._DoApplyForce(Math.cos(r)*t,Math.sin(r)*t,n,o)}_ApplyForceAtAngle(t,e,i){const[s,n]=this._GetInstImagePoint(i);this._DoApplyForce(Math.cos(e)*t,Math.sin(e)*t,s,n)}_DoApplyForce(t,e,i,s){if(!this._isEnabled)return;const n=this._worldScale;this._body["ApplyForce"](P(t,e),M(i*n,s*n),!0)}_ApplyImpulse(t,e,i){const[s,n]=this._GetInstImagePoint(i);this._DoApplyImpulse(t,e,s,n)}_ApplyImpulseToward(t,e,i,s){const[n,o]=this._GetInstImagePoint(s),r=_.angleTo(n,o,e,i);this._DoApplyImpulse(Math.cos(r)*t,Math.sin(r)*t,n,o)}_ApplyImpulseAtAngle(t,e,i){const[s,n]=this._GetInstImagePoint(i);this._DoApplyImpulse(Math.cos(e)*t,Math.sin(e)*t,s,n)}_DoApplyImpulse(t,e,i,s){if(!this._isEnabled)return;const n=this._worldScale;this._body["ApplyLinearImpulse"](P(t,e),M(i*n,s*n),!0);const o=this.GetWorldInfo();this._lastKnownX=o.GetX(),this._lastKnownY=o.GetY(),this._lastTickOverride=!1}_ApplyTorque(t){this._isEnabled&&this._body["ApplyTorque"](t,!0)}_ApplyTorqueToAngle(t,e){const i=_.angleClockwise(this.GetWorldInfo().GetAngle(),e)?-1:1;this._ApplyTorque(t*i)}_ApplyTorqueToPosition(t,e,i){const s=this.GetWorldInfo(),n=_.angleTo(s.GetX(),s.GetY(),e,i),o=_.angleClockwise(s.GetAngle(),n)?-1:1;this._ApplyTorque(t*o)}_SetAngularVelocity(t){this._isEnabled&&(this._body["SetAngularVelocity"](t),this._body["SetAwake"](!0))}_GetAngularVelocity(){return this._isEnabled?this._body["GetAngularVelocity"]():0}_SetVelocity(t,e){if(!this._isEnabled)return;const i=this._worldScale;this._body["SetLinearVelocity"](P(t*i,e*i)),this._body["SetAwake"](!0);const s=this.GetWorldInfo();this._lastKnownX=s.GetX(),this._lastKnownY=s.GetY(),this._lastTickOverride=!1}_GetVelocity(){if(!this._isEnabled)return[0,0];const t=this._worldScale,e=this._body["GetLinearVelocity"]();return[e["get_x"]()/t,e["get_y"]()/t]}_GetVelocityX(){return this._isEnabled?this._body["GetLinearVelocity"]()["get_x"]()/this._worldScale:0}_GetVelocityY(){return this._isEnabled?this._body["GetLinearVelocity"]()["get_y"]()/this._worldScale:0}_Teleport(t,e){if(!this._isEnabled)return;const i=this._worldScale;this._body["SetTransform"](P(t*i,e*i),this._body["GetAngle"]());const s=this.GetWorldInfo();s.SetXY(t,e),s.SetBboxChanged(),this._lastKnownX=s.GetX(),this._lastKnownY=s.GetY()}_SetDensity(t){if(this._isEnabled&&this._density!==t){this._density=t;for(const e of this._fixtures)e["SetDensity"](t);this._body["ResetMassData"]()}}_GetDensity(){return this._isEnabled?this._density:0}_SetFriction(t){if(this._isEnabled&&this._friction!==t){this._friction=t;for(const e of this._fixtures)e["SetFriction"](t);if(this._body)for(let t=this._body["GetContactList"]();this._box2d["getPointer"](t);t=t["get_next"]()){const e=t["get_contact"]();e&&e["ResetFriction"]()}}}_GetFriction(){return this._isEnabled?this._friction:0}_SetElasticity(t){if(this._isEnabled&&this._restitution!==t){this._restitution=t;for(const e of this._fixtures)e["SetRestitution"](t)}}_GetElasticity(){return this._isEnabled?this._restitution:0}_SetLinearDamping(t){this._isEnabled&&this._linearDamping!==t&&(this._linearDamping=t,this._body["SetLinearDamping"](t))}_GetLinearDamping(){return this._isEnabled?this._linearDamping:0}_SetAngularDamping(t){this._isEnabled&&this._angularDamping!==t&&(this._angularDamping=t,this._body["SetAngularDamping"](t))}_GetAngularDamping(){return this._isEnabled?this._angularDamping:0}_SetImmovable(t){this._isEnabled&&(t=!!t,this._isImmovable!==t&&(this._isImmovable=t,this._body["SetType"](this._isImmovable?0:2),this._body["SetAwake"](!0)))}_IsImmovable(){return this._isImmovable}_SetPreventRotate(t){this._isEnabled&&(t=!!t,this._preventRotation!==t&&(this._preventRotation=t,this._body["SetFixedRotation"](this._preventRotation),this._body["SetAngularVelocity"](0),this._body["SetAwake"](!0)))}_IsPreventRotate(){return this._preventRotation}_SetBullet(t){this._isEnabled&&(t=!!t,this._isBullet!==t&&(this._isBullet=t,this._body["SetBullet"](this._isBullet),this._body["SetAwake"](!0)))}_IsBullet(){return this._isBullet}_SetAwake(t){this._isEnabled&&this._body["SetAwake"](!!t)}_IsAwake(){return!!this._isEnabled&&this._body["IsAwake"]()}_GetMass(){return this._isEnabled?this._body["GetMass"]()/this._worldScale:0}_GetCenterOfMassX(){return this._isEnabled?this._body["GetWorldCenter"]()["get_x"]()/this._worldScale:0}_GetCenterOfMassY(){return this._isEnabled?this._body["GetWorldCenter"]()["get_y"]()/this._worldScale:0}_GetCenterOfMass(){if(!this._isEnabled)return[0,0];const t=this._body["GetWorldCenter"](),e=this._worldScale;return[t["get_x"]()/e,t["get_y"]()/e]}_GetContactCount(){if(!this._isEnabled)return 0;let t=0;for(let e=this._body["GetContactList"]();this._box2d["getPointer"](e);e=e["get_next"]()){const i=e["get_contact"]();if(!i)continue;t+=i["GetManifold"]()["get_pointCount"]()}return t}_GetContactPositionAt(t){if(t=Math.floor(t),!this._isEnabled)return[0,0];let e=0;for(let i=this._body["GetContactList"]();this._box2d["getPointer"](i);i=i["get_next"]()){const s=i["get_contact"]();if(!s)continue;const n=s["GetManifold"]()["get_pointCount"]();if(t>=e&&t<e+n){const i=t-e,n=this.GetBehavior().GetWorldManifold();s["GetWorldManifold"](n);const o=n["get_points"](i);return[o["get_x"]()/this._worldScale,o["get_y"]()/this._worldScale]}e+=n}return[0,0]}GetScriptInterfaceClass(){return self.IPhysicsBehaviorInstance}};const T=new WeakMap;function UnwrapIWorldInstance(t,e){return T.get(t).GetRuntime()._UnwrapIWorldInstance(e)}self.IPhysicsBehaviorInstance=class extends d{constructor(){super(),T.set(this,d._GetInitInst().GetSdkInstance())}get isEnabled(){return T.get(this)._IsEnabled()}set isEnabled(t){T.get(this)._SetEnabled(t)}applyForce(t,e,i=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),T.get(this)._ApplyForce(t,e,i)}applyForceTowardPosition(t,e,i,s=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),c.RequireFiniteNumber(i),T.get(this)._ApplyForceToward(t,e,i,s)}applyForceAtAngle(t,e,i=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),T.get(this)._ApplyForceAtAngle(t,e,i)}applyImpulse(t,e,i=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),T.get(this)._ApplyImpulse(t,e,i)}applyImpulseTowardPosition(t,e,i,s=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),c.RequireFiniteNumber(i),T.get(this)._ApplyImpulseToward(t,e,i,s)}applyImpulseAtAngle(t,e,i=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),T.get(this)._ApplyImpulseAtAngle(t,e,i)}applyTorque(t){c.RequireFiniteNumber(t),T.get(this)._ApplyTorque(t)}applyTorqueToAngle(t,e){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),T.get(this)._ApplyTorqueToAngle(t,e)}applyTorqueToPosition(t,e,i){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),c.RequireFiniteNumber(i),T.get(this)._ApplyTorqueToPosition(t,e,i)}set angularVelocity(t){c.RequireFiniteNumber(t),T.get(this)._SetAngularVelocity(t)}get angularVelocity(){return T.get(this)._GetAngularVelocity()}setVelocity(t,e){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),T.get(this)._SetVelocity(t,e)}getVelocityX(){return T.get(this)._GetVelocityX()}getVelocityY(){return T.get(this)._GetVelocityY()}getVelocity(){return T.get(this)._GetVelocity()}teleport(t,e){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),T.get(this)._Teleport(t,e)}set density(t){c.RequireFiniteNumber(t),T.get(this)._SetDensity(t)}get density(){return T.get(this)._GetDensity()}set friction(t){c.RequireFiniteNumber(t),T.get(this)._SetFriction(t)}get friction(){return T.get(this)._GetFriction()}set elasticity(t){c.RequireFiniteNumber(t),T.get(this)._SetElasticity(t)}get elasticity(){return T.get(this)._GetElasticity()}set linearDamping(t){c.RequireFiniteNumber(t),T.get(this)._SetLinearDamping(t)}get linearDamping(){return T.get(this)._GetLinearDamping()}set angularDamping(t){c.RequireFiniteNumber(t),T.get(this)._SetAngularDamping(t)}get angularDamping(){return T.get(this)._GetAngularDamping()}set isImmovable(t){T.get(this)._SetImmovable(t)}get isImmovable(){return T.get(this)._IsImmovable()}set isPreventRotation(t){T.get(this)._SetPreventRotate(t)}get isPreventRotation(){return T.get(this)._IsPreventRotate()}set isBullet(t){T.get(this)._SetBullet(t)}get isBullet(){return T.get(this)._IsBullet()}get mass(){return T.get(this)._GetMass()}getCenterOfMassX(){return T.get(this)._GetCenterOfMassX()}getCenterOfMassY(){return T.get(this)._GetCenterOfMassY()}getCenterOfMass(){return T.get(this)._GetCenterOfMass()}getContactCount(){return T.get(this)._GetContactCount()}getContactX(t){return c.RequireFiniteNumber(t),T.get(this)._GetContactPositionAt(t)[0]}getContactY(t){return c.RequireFiniteNumber(t),T.get(this)._GetContactPositionAt(t)[1]}getContact(t){return c.RequireFiniteNumber(t),T.get(this)._GetContactPositionAt(t)}set isAwake(t){T.get(this)._SetAwake(!!t)}get isAwake(){return T.get(this)._IsAwake()}get isSleeping(){return!T.get(this)._IsAwake()}createDistanceJoint(t,e,i,s,n){c.RequireFiniteNumber(s),c.RequireFiniteNumber(n);const o=UnwrapIWorldInstance(this,e);T.get(this)._CreateDistanceJoint(t,o,i,s,n)}createRevoluteJoint(t,e){const i=UnwrapIWorldInstance(this,e);T.get(this)._CreateRevoluteJoint(t,i)}createLimitedRevoluteJoint(t,e,i,s){c.RequireFiniteNumber(i),c.RequireFiniteNumber(s);const n=UnwrapIWorldInstance(this,e);T.get(this)._CreateLimitedRevoluteJoint(t,n,i,s)}createPrismaticJoint(t,e,i,s,n,o,r,a,l){const h=UnwrapIWorldInstance(this,e);T.get(this)._CreatePrismaticJoint(t,h,i,s,n,o,r,a,l)}removeAllJoints(){T.get(this)._RemoveJoints()}}}{const x=self.C3;x.Behaviors.Physics.Cnds={IsSleeping(){return!this._IsAwake()},IsImmovable(){return this._IsImmovable()},CompareVelocity(t,e,i){if(!this._isEnabled)return!1;let s=0;if(0===t)s=this._GetVelocityX();else if(1===t)s=this._GetVelocityY();else{const[t,e]=this._GetVelocity();s=Math.hypot(t,e)}return x.compare(s,e,i)},CompareAngularVelocity(t,e){if(!this._isEnabled)return!1;const i=x.toDegrees(this._GetAngularVelocity());return x.compare(i,t,e)},CompareMass(t,e){if(!this._isEnabled)return!1;const i=this._GetMass();return x.compare(i,t,e)},IsEnabled(){return this._IsEnabled()}}}{const k=self.C3;k.Behaviors.Physics.Acts={ApplyForce(t,e,i){this._ApplyForce(t,e,i)},ApplyForceToward(t,e,i,s){this._ApplyForceToward(t,e,i,s)},ApplyForceAtAngle(t,e,i){this._ApplyForceAtAngle(t,k.toRadians(e),i)},ApplyImpulse(t,e,i){this._ApplyImpulse(t,e,i)},ApplyImpulseToward(t,e,i,s){this._ApplyImpulseToward(t,e,i,s)},ApplyImpulseAtAngle(t,e,i){this._ApplyImpulseAtAngle(t,k.toRadians(e),i)},ApplyTorque(t){this._ApplyTorque(k.toRadians(t))},ApplyTorqueToAngle(t,e){this._ApplyTorqueToAngle(k.toRadians(t),k.toRadians(e))},ApplyTorqueToPosition(t,e,i){this._ApplyTorqueToPosition(k.toRadians(t),e,i)},SetAngularVelocity(t){this._SetAngularVelocity(k.toRadians(t))},CreateDistanceJoint(t,e,i,s,n){if(!e)return;const o=e.GetFirstPicked(this._inst);this._CreateDistanceJoint(t,o,i,s,n)},CreateRevoluteJoint(t,e){if(!e)return;const i=e.GetFirstPicked(this._inst);this._CreateRevoluteJoint(t,i)},CreateLimitedRevoluteJoint(t,e,i,s){if(!e)return;const n=e.GetFirstPicked(this._inst);this._CreateLimitedRevoluteJoint(t,n,k.toRadians(i),k.toRadians(s))},CreatePrismaticJoint(t,e,i,s,n,o,r,a,l){if(!e)return;const h=e.GetFirstPicked(this._inst);this._CreatePrismaticJoint(t,h,k.toRadians(i),s,n,o,r,k.toRadians(a),l)},RemoveJoints(){this._RemoveJoints()},SetWorldGravity(t){this.GetBehavior().SetGravity(t)},SetSteppingMode(t){this.GetBehavior().SetSteppingMode(t)},SetIterations(t,e){this.GetBehavior().SetIterations(t,e)},SetVelocity(t,e){this._SetVelocity(t,e)},Teleport(t,e){this._Teleport(t,e)},SetDensity(t){this._SetDensity(t)},SetFriction(t){this._SetFriction(t)},SetElasticity(t){this._SetElasticity(t)},SetLinearDamping(t){this._SetLinearDamping(t)},SetAngularDamping(t){this._SetAngularDamping(t)},SetImmovable(t){this._SetImmovable(t)},EnableCollisions(t,e){this.GetBehavior().SetCollisionsEnabled(this.GetObjectClass(),t,0!==e)},SetPreventRotate(t){this._SetPreventRotate(0!==t)},SetBullet(t){this._SetBullet(0!==t)},SetAwake(t){this._SetAwake(!!t)},SetEnabled(t){this._SetEnabled(0!==t)}}}{const J=self.C3;J.Behaviors.Physics.Exps={VelocityX(){return this._GetVelocityX()},VelocityY(){return this._GetVelocityY()},AngularVelocity(){return J.toDegrees(this._GetAngularVelocity())},Mass(){return this._GetMass()},CenterOfMassX(){return this._GetCenterOfMassX()},CenterOfMassY(){return this._GetCenterOfMassY()},Density(){return this._GetDensity()},Friction(){return this._GetFriction()},Elasticity(){return this._GetElasticity()},LinearDamping(){return this._GetLinearDamping()},AngularDamping(){return this._GetAngularDamping()},ContactCount(){return this._GetContactCount()},ContactXAt(t){return this._GetContactPositionAt(t)[0]},ContactYAt(t){return this._GetContactPositionAt(t)[1]}}}
}

// scripts/behaviors/Physics/c3runtime/separator.js
{
const C3=self.C3,b2Separator={};C3.Behaviors.Physics.Separator=b2Separator;const GetVec2=C3.Behaviors.Physics.GetVec2,FreeVec2=C3.Behaviors.Physics.FreeVec2;function CloneVec2(e){return GetVec2(e["get_x"](),e["get_y"]())}function SplitConvexPolysOver8Points(e){const t=[];for(const r of e)r.length<=8?t.push(r):t.push.apply(t,SplitConvexPoly(r));return t}function SplitConvexPoly(e){const t=[];t.push(e.splice(0,8));const r=t[0][0];let n=t[0][7];for(;e.length;){const a=e.splice(0,Math.min(e.length,6));let o=a.at(-1);a.push(CloneVec2(r)),a.push(CloneVec2(n)),t.push(a),n=o}return t}b2Separator.det=function(e,t,r,n,a,o){return e*n+r*o+a*t-t*r-n*a-o*e},b2Separator.hitRay=function(e,t,r,n,a,o,s,g){const p=r-e,i=n-t,c=s-a,h=g-o,_=(c*(o-t)-h*(a-e))/(i*c-p*h),u=e+_*p,l=t+_*i,y=b2Separator.isOnSegment(r,n,e,t,u,l),f=b2Separator.isOnSegment(u,l,a,o,s,g);return y&&f?GetVec2(u,l):null},b2Separator.isOnSegment=function(e,t,r,n,a,o){return(r+.1>=e&&e>=a-.1||r-.1<=e&&e<=a+.1)&&(n+.1>=t&&t>=o-.1||n-.1<=t&&t<=o+.1)&&b2Separator.isOnLine(e,t,r,n,a,o)},b2Separator.isOnLine=function(e,t,r,n,a,o){if(Math.abs(a-r)>.1){const s=(o-n)/(a-r)*(e-r)+n;return Math.abs(s-t)<.1}return Math.abs(e-r)<.1},b2Separator.pointsMatch=function(e,t,r,n){return Math.abs(r-e)<.1&&Math.abs(n-t)<.1},b2Separator.Separate=function(e,t){if(3===e.length)return[e.map((e=>GetVec2(e["get_x"](),e["get_y"]())))];const r=b2Separator.calcShapes(e);let n=[];for(let e=0,a=r.length;e<a;++e){const a=r[e],o=[];let s=0;for(let e=0,t=a.length;e<t;++e){const r=a[e],n=a[(e+1)%t];s+=r["get_x"]()*n["get_y"]()-r["get_y"]()*n["get_x"](),o.push(GetVec2(r["get_x"](),r["get_y"]()))}if(s=Math.abs(s/2),s>=.001*t)n.push(o);else for(let e=0,t=o.length;e<t;e++)FreeVec2(o[e])}return n=SplitConvexPolysOver8Points(n),n},b2Separator.calcShapes=function(e){let t,r,n,a,o,s,g,p=[],i=0,c=0,h=0,_=0,u=0,l=0,y=0,f=0,S=0,b=0,x=0,V=0,C=0,v=0,M=0,O=[],P=[],m=!1,G=[],F=[],k=!1;for(F.push(e);F.length;){for(p=F[0],c=p.length,m=!0,i=0;i<c;i++)if(S=i,b=i<c-1?i+1:i+1-c,x=i<c-2?i+2:i+2-c,t=p[S],r=p[b],n=p[x],_=b2Separator.det(t["get_x"](),t["get_y"](),r["get_x"](),r["get_y"](),n["get_x"](),n["get_y"]()),_<0){for(m=!1,f=1e9,h=0;h<c;h++)h!==S&&h!==b&&(V=h,C=h<c-1?h+1:0,a=p[V],o=p[C],s=b2Separator.hitRay(t["get_x"](),t["get_y"](),r["get_x"](),r["get_y"](),a["get_x"](),a["get_y"](),o["get_x"](),o["get_y"]()),s&&(l=r["get_x"]()-s["get_x"](),y=r["get_y"]()-s["get_y"](),u=l*l+y*y,u<f?(M=V,v=C,g=s,f=u):FreeVec2(s)));if(1e9===f)return[];for(O=[],P=[],V=M,C=v,a=p[V],o=p[C],k=!1,b2Separator.pointsMatch(g["get_x"](),g["get_y"](),o["get_x"](),o["get_y"]())||(O.push(g),k=!0),b2Separator.pointsMatch(g["get_x"](),g["get_y"](),a["get_x"](),a["get_y"]())||(P.push(g),k=!0),k||FreeVec2(g),M=-1,v=S;;){if(v===C){if(M<0||M>=c)return[];b2Separator.isOnSegment(o["get_x"](),o["get_y"](),p[M]["get_x"](),p[M]["get_y"](),t["get_x"](),t["get_y"]())||O.push(p[v]);break}O.push(p[v]),M=v,v-1<0?v=c-1:v--}for(O.reverse(),M=-1,v=b;;){if(v===V){if(M<0||M>=c)return[];v!==V||b2Separator.isOnSegment(a["get_x"](),a["get_y"](),p[M]["get_x"](),p[M]["get_y"](),r["get_x"](),r["get_y"]())||P.push(p[v]);break}P.push(p[v]),M=v,v+1>c-1?v=0:v++}F.push(O,P),F.shift();break}m&&G.push(F.shift())}return G};
}

// scripts/behaviors/Platform/c3runtime/runtime.js
{
{const t=self.C3;t.Behaviors.Platform=class extends t.SDKBehaviorBase{constructor(t){super(t)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.Platform.Type=class extends e.SDKBehaviorTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const i=self.C3,s=self.C3X,n=self.IBehaviorInstance,h=0,r=1,o=2,l=3,a=4,_=5,u=6,d=7,m=8,p=9,g=.05;function accelerate(t,e,s,n,h){const r=e*h,o=s*h;return i.clamp(t*h+.5*n*h*h,r,o)}i.Behaviors.Platform.Instance=class extends i.SDKBehaviorInstanceBase{constructor(t,e){super(t),this._keyboardDisposables=null,this._leftKey=!1,this._rightKey=!1,this._jumpKey=!1,this._jumped=!1,this._doubleJumped=!1,this._canDoubleJump=!1,this._ignoreInput=!1,this._simLeft=!1,this._simRight=!1,this._simJump=!1,this._lastFloorObject=null,this._loadFloorUid=-1,this._lastFloorX=0,this._lastFloorY=0,this._floorIsJumpthru=!1,this._wasOnFloor=!1,this._wasOverJumpthru=this._runtime.GetCollisionEngine().TestOverlapJumpthru(this._inst),this._loadJumpthruUid=-1,this._animMode="stopped",this._fallThroughTime=-1,this._isFirstTick=!0,this._dx=0,this._dy=0,this._downX=0,this._downY=0,this._rightX=0,this._rightY=0,this._g=1500,this._g1=1500,this._ga=i.toRadians(90),this._maxSpeed=330,this._acc=1500,this._dec=1500,this._jumpStrength=650,this._maxFall=1e3,this._enableDoubleJump=!1,this._jumpSustain=0,this._sustainTime=0,this._defaultControls=!0,this._ceilingCollisionMode=0,this._isEnabled=!0,e&&(this._maxSpeed=e[h],this._acc=e[r],this._dec=e[o],this._jumpStrength=e[l],this._g=e[a],this._maxFall=e[_],this._enableDoubleJump=!!e[u],this._jumpSustain=e[d]/1e3,this._defaultControls=!!e[m],this._isEnabled=!!e[p]);const s=this._runtime.Dispatcher();this._disposables=new i.CompositeDisposable(i.Disposable.From(s,"instancedestroy",(t=>this._OnInstanceDestroyed(t.instance))),i.Disposable.From(s,"afterload",(t=>this._OnAfterLoad()))),this._defaultControls&&this._BindEvents(),this._isEnabled&&this._StartPostTicking(),this._UpdateGravity()}Release(){this._keyboardDisposables&&(this._keyboardDisposables.Release(),this._keyboardDisposables=null),this._lastFloorObject=null,this._wasOverJumpthru=null,super.Release()}_BindEvents(){if(this._keyboardDisposables)return;const t=this._runtime.Dispatcher();this._keyboardDisposables=new i.CompositeDisposable(i.Disposable.From(t,"keydown",(t=>this._OnKeyDown(t.data))),i.Disposable.From(t,"keyup",(t=>this._OnKeyUp(t.data))),i.Disposable.From(t,"window-blur",(()=>this._OnWindowOrKeyboardBlur())),i.Disposable.From(t,"keyboard-blur",(()=>this._OnWindowOrKeyboardBlur())))}_UnBindEvents(){this._keyboardDisposables&&(this._keyboardDisposables.Release(),this._keyboardDisposables=null)}_OnInstanceDestroyed(t){this._lastFloorObject===t&&(this._lastFloorObject=null),this._wasOverJumpthru===t&&(this._wasOverJumpthru=null)}_OnKeyDown(t){switch(t["key"]){case"ArrowLeft":this._leftKey=!0;break;case"ArrowRight":this._rightKey=!0;break;case"ArrowUp":this._jumpKey=!0}}_OnKeyUp(t){switch(t["key"]){case"ArrowLeft":this._leftKey=!1;break;case"ArrowRight":this._rightKey=!1;break;case"ArrowUp":this._jumpKey=!1,this._jumped=!1}}_OnWindowOrKeyboardBlur(){this._leftKey=!1,this._rightKey=!1,this._jumpKey=!1,this._jumped=!1}SaveToJson(){return{"ii":this._ignoreInput,"lfx":this._lastFloorX,"lfy":this._lastFloorY,"lfo":this._lastFloorObject?this._lastFloorObject.GetUID():-1,"am":this._animMode,"en":this._isEnabled,"fallt":this._fallThroughTime,"ft":this._isFirstTick,"dx":this._dx,"dy":this._dy,"ms":this._maxSpeed,"acc":this._acc,"dec":this._dec,"js":this._jumpStrength,"g":this._g,"g1":this._g1,"mf":this._maxFall,"wof":this._wasOnFloor,"woj":this._wasOverJumpthru?this._wasOverJumpthru.GetUID():-1,"ga":this._ga,"edj":this._enableDoubleJump,"cdj":this._canDoubleJump,"dj":this._doubleJumped,"sus":this._jumpSustain,"dc":this._defaultControls,"cc":this._ceilingCollisionMode}}LoadFromJson(t){this._ignoreInput=t["ii"],this._lastFloorX=t["lfx"],this._lastFloorY=t["lfy"],this._loadFloorUid=t["lfo"],this._animMode=t["am"];const e=t["en"];this._fallThroughTime=t["fallt"]||-1,this._isFirstTick=t["ft"],this._dx=t["dx"],this._dy=t["dy"],this._maxSpeed=t["ms"],this._acc=t["acc"],this._dec=t["dec"],this._jumpStrength=t["js"],this._g=t["g"],this._g1=t["g1"],this._maxFall=t["mf"],this._wasOnFloor=t["wof"],this._loadJumpthruUid=t["woj"],this._ga=t["ga"],this._enableDoubleJump=t["edj"],this._canDoubleJump=t["cdj"],this._doubleJumped=t["dj"],this._jumpSustain=t["sus"],this._defaultControls=t["dc"],this._ceilingCollisionMode=t["cc"]||0,this._leftKey=!1,this._rightKey=!1,this._jumpKey=!1,this._jumped=!1,this._simLeft=!1,this._simRight=!1,this._simJump=!1,this._sustainTime=0,this._defaultControls?this._BindEvents():this._UnBindEvents(),this._SetEnabled(e),this._UpdateGravity()}_OnAfterLoad(){-1===this._loadFloorUid?this._lastFloorObject=null:this._lastFloorObject=this._runtime.GetInstanceByUID(this._loadFloorUid),-1===this._loadJumpthruUid?this._wasOverJumpthru=null:this._wasOverJumpthru=this._runtime.GetInstanceByUID(this._loadJumpthruUid)}_SetLastFloorObject(t){if(this._lastFloorObject=t,t){const e=t.GetWorldInfo();this._lastFloorX=e.GetX(),this._lastFloorY=e.GetY()}}_IsFallThroughEnabled(){return this._runtime.GetGameTime()>this._fallThroughTime+g}_UpdateGravity(){this._downX=Math.cos(this._ga),this._downY=Math.sin(this._ga),this._rightX=Math.cos(this._ga-Math.PI/2),this._rightY=Math.sin(this._ga-Math.PI/2),this._downX=i.roundToDp(this._downX,6),this._downY=i.roundToDp(this._downY,6),this._rightX=i.roundToDp(this._rightX,6),this._rightY=i.roundToDp(this._rightY,6),this._g1=this._g,this._g<0&&(this._downX*=-1,this._downY*=-1,this._g=Math.abs(this._g))}_GetGDir(){return this._g<0?-1:1}_IsOnFloor(){const t=this._inst.GetWorldInfo(),e=this._runtime.GetCollisionEngine(),i=this._inst,s=this._lastFloorObject,n=t.GetX(),h=t.GetY();if(t.OffsetXY(this._downX,this._downY),t.SetBboxChanged(),!s||!e.TestOverlap(i,s)||s.GetObjectClass().HasSolidBehavior()&&!e.IsSolidCollisionAllowed(s,i)||s.GetObjectClass().HasJumpthruBehavior()&&!s._IsJumpthruEnabled()){let s=e.TestOverlapSolid(i),r=null;if(!s&&this._IsFallThroughEnabled()&&(r=e.TestOverlapJumpthru(i,!0)),t.SetXY(n,h),t.SetBboxChanged(),s)return e.TestOverlap(i,s)?null:(this._floorIsJumpthru=!1,s);if(r&&r.length){let t=0;for(let s=0,n=r.length;s<n;++s)r[t]=r[s],e.TestOverlap(i,r[s])||++t;if(t>=1)return this._floorIsJumpthru=!0,r[0]}return null}return t.SetXY(n,h),t.SetBboxChanged(),s}PostTick(){if(!this._isEnabled)return;const t=this._runtime.GetDt(this._inst);this._jumpKey||this._simJump||(this._jumped=!1);let e=this._leftKey||this._simLeft,i=this._rightKey||this._simRight,s=this._jumpKey||this._simJump,n=s&&!this._jumped;this._simLeft=!1,this._simRight=!1,this._simJump=!1,this._ignoreInput&&(e=!1,i=!1,s=!1,n=!1),s||(this._sustainTime=0),this._HandleFirstTick();const[h,r,o]=this._TrackMovingPlatform();let l=this._IsOnFloor();const a=l&&!this._wasOnFloor;let _=!1;if([_,l]=this._MaybePushOutSolid(l),_)return;this._TrackFloor(l,o,h,s),n=this._HandleJump(l,n,s),l||this._HandleAirTime(n,s,t),this._wasOnFloor=!!l;const u=this._CalculateHorizontalAcceleration(e,i);let d=!1,m=0;if(0!==this._dx&&([d,l]=this._HandleHorizontalMovement(t,u,l,n)),0!==this._dy){const[e,i]=this._HandleVerticalMovement(t,l);d=d||e,m=i}!d&&a&&this._dy<0&&m>0&&(this._dy=0,d=!0),this._ApplyHorizontalAcceleration(e,i,u,t),l&&!n||d||(this._dy=Math.min(this._dy+this._g*t,this._maxFall)),this._HandleAnimationTriggers(l,d,n),this._wasOverJumpthru=this._runtime.GetCollisionEngine().TestOverlapJumpthru(this._inst)}_HandleFirstTick(){if(!this._isFirstTick)return;const t=this._inst,e=this._runtime.GetCollisionEngine();(e.TestOverlapSolid(t)||e.TestOverlapJumpthru(t))&&e.PushOutSolid(t,-this._downX,-this._downY,4,!0),this._isFirstTick=!1}_TrackMovingPlatform(){const t=this._lastFloorObject,e=t?t.GetWorldInfo():null;let s=0,n=0,h=!1;if(t&&0===this._dy&&(e.GetY()!==this._lastFloorY||e.GetX()!==this._lastFloorX)){const t=this._inst,r=t.GetWorldInfo(),o=this._runtime.GetCollisionEngine(),l=e.GetX(),a=e.GetY();s=l-this._lastFloorX,n=a-this._lastFloorY,r.OffsetXY(s,n),r.SetBboxChanged(),this._lastFloorX=l,this._lastFloorY=a,h=!0;const _=o.TestOverlapSolid(t);_&&(o.RegisterCollision(t,_),o.PushOutSolid(t,-s,-n,2.5*i.hypot2DFast(s,n)))}return[s,n,h]}_MaybePushOutSolid(t){let e=!1;const i=this._inst,s=i.GetWorldInfo(),n=this._runtime.GetCollisionEngine(),h=n.TestOverlapSolid(i);if(!h)return[!1,t];const r=Math.abs(s.GetWidth()),o=Math.abs(s.GetHeight());return n.PushOutSolid(i,-this._downX,-this._downY,o/8)?(n.RegisterCollision(i,h),t=h,this._SetLastFloorObject(h),this._floorIsJumpthru=!1,this._dy=0):n.PushOutSolidAxis(i,this._rightX,this._rightY,r/2)||n.PushOutSolidAxis(i,this._downX,this._downY,o/2)||n.PushOutSolidNearest(i,Math.max(r,o)/2)?n.RegisterCollision(i,h):e=!0,[e,t]}_TrackFloor(t,e,i,s){const n=this._inst,h=this._runtime.GetCollisionEngine();if(t){const s=this._downX,r=this._downY,o=this._rightX,l=this._rightY;if(this._doubleJumped=!1,this._canDoubleJump=!1,this._dy>0&&(this._wasOnFloor||(h.PushInFractional(n,-s,-r,t,16),this._wasOnFloor=!0),this._dy=0),this._lastFloorObject!==t)this._SetLastFloorObject(t),h.RegisterCollision(n,t);else if(e){const t=h.TestOverlapSolid(n);t&&(h.RegisterCollision(n,t),0!==i&&(i>0?h.PushOutSolid(n,-o,-l):h.PushOutSolid(n,o,l)),h.PushOutSolid(n,-s,-r))}}else s||(this._canDoubleJump=!0)}_HandleJump(t,e,s){if(t&&e||!t&&this._enableDoubleJump&&s&&this._canDoubleJump&&!this._doubleJumped){const s=this._inst,n=s.GetWorldInfo(),h=this._runtime.GetCollisionEngine(),r=n.GetX(),o=n.GetY();n.OffsetXY(-this._downX,-this._downY),n.SetBboxChanged(),h.TestOverlapSolid(s)?e=!1:(this._sustainTime=this._jumpSustain,this.Trigger(i.Behaviors.Platform.Cnds.OnJump),this._animMode="jumping",this._dy=-this._jumpStrength,e=!0,t?this._jumped=!0:this._doubleJumped=!0),n.SetXY(r,o),n.SetBboxChanged()}return e}_HandleAirTime(t,e,i){e&&this._sustainTime>0?(this._dy=-this._jumpStrength,this._sustainTime-=i):this._lastFloorObject=null,t&&(this._jumped=!0)}_CalculateHorizontalAcceleration(t,e){let i=0;const s=this._acc,n=this._dec;return t&&!e&&(i=this._dx>0?-(s+n):-s),e&&!t&&(i=this._dx<0?s+n:s),i}_ApplyHorizontalAcceleration(t,e,s,n){const h=this._dec;t===e&&(this._dx<0?this._dx=Math.min(this._dx+h*n,0):this._dx>0&&(this._dx=Math.max(this._dx-h*n,0))),this._dx=i.clamp(this._dx+s*n,-this._maxSpeed,this._maxSpeed);const r=this._runtime.GetCollisionEngine(),o=this._dx<0?this._GetWallObstacle(0,1,1):null;if(o)this._dx=0,r.RegisterCollision(this._inst,o);else{const t=this._dx>0?this._GetWallObstacle(1,1,1):null;t&&(this._dx=0,r.RegisterCollision(this._inst,t))}}_HandleHorizontalMovement(t,e,i,s){const n=this._inst,h=n.GetWorldInfo(),r=this._runtime.GetCollisionEngine(),o=this._downX,l=this._downY,a=this._rightX,_=this._rightY,u=this._maxSpeed;let d=!1;const m=new Set(r.TestOverlapJumpthru(n,!0));let p=h.GetX(),g=h.GetY();const c=accelerate(this._dx,-u,u,e,t)*a,S=accelerate(this._dx,-u,u,e,t)*_;h.OffsetXY(a*(this._dx>1?1:-1)-o,_*(this._dx>1?1:-1)-l),h.SetBboxChanged();let b=!1;const f=r.TestOverlapSolid(n);h.SetXY(p+c,g+S),h.SetBboxChanged();let G=r.TestOverlapSolid(n);if(!G&&i&&this._floorIsJumpthru&&(G=r.TestOverlapJumpthru(n),m.has(G)?G=null:b=!0),G){let e=Math.abs(this._dx*t)+2;f||!r.PushOutSolid(n,-o,-l,e,b,G)?(r.RegisterCollision(n,G),e=Math.max(Math.abs(this._dx*t*2.5),Math.floor(h.GetWidth())),r.PushOutSolid(n,a*(this._dx<0?1:-1),_*(this._dx<0?1:-1),e,!1)?!i||b||this._floorIsJumpthru||(p=h.GetX(),g=h.GetY(),h.OffsetXY(o,l),r.TestOverlapSolid(n)&&r.PushOutSolid(n,-o,-l,3,!1)||(h.SetXY(p,g),h.SetBboxChanged())):(h.SetXY(p,g),h.SetBboxChanged()),b||(this._dx=0)):!f&&!s&&Math.abs(this._dy)<Math.abs(this._jumpStrength/4)&&(this._dy=0,i||(d=!0))}else{const e=this._IsOnFloor();if(i&&!e){const e=Math.ceil(Math.abs(this._dx*t))+2;p=h.GetX(),g=h.GetY(),h.OffsetXY(o*e,l*e),h.SetBboxChanged();const s=r.TestOverlapJumpthru(n);let a=!1;s&&!m.has(s)&&r.PushOutSolid(n,-o,-l,e+2,!0,s)&&(i=s,this._SetLastFloorObject(s),this._floorIsJumpthru=!0,a=!0),a||(r.TestOverlapSolid(n)?r.PushOutSolid(n,-o,-l,e+2,!1):(h.SetXY(p,g),h.SetBboxChanged()))}else e&&(!i&&this._floorIsJumpthru&&(this._SetLastFloorObject(e),this._dy=0,d=!0),0===this._dy&&r.PushInFractional(n,-o,-l,e,16))}return[d,i]}_HandleVerticalMovement(t,e){const s=this._inst,n=s.GetWorldInfo(),h=this._runtime.GetCollisionEngine(),r=this._downX,o=this._downY;let l=!1,a=n.GetX(),_=n.GetY();const u=accelerate(this._dy,-1/0,this._maxFall,this._g,t);n.OffsetXY(u*r,u*o);const d=n.GetX(),m=n.GetY();n.SetBboxChanged();let p=h.TestOverlapSolid(s),g=!1;if(!p&&this._dy>0&&!e){const t=this._IsFallThroughEnabled()?h.TestOverlapJumpthru(s,!0):null;if(t&&t.length){if(this._wasOverJumpthru){n.SetXY(a,_),n.SetBboxChanged();let e=0;for(let i=0,n=t.length;i<n;++i)t[e]=t[i],h.TestOverlap(s,t[i])||++e;i.truncateArray(t,e),n.SetXY(d,m),n.SetBboxChanged()}t.length>=1&&(p=t[0])}g=!!p}if(p){h.RegisterCollision(s,p),this._sustainTime=0;let e=1.1;g&&!this._wasOverJumpthru&&(e=2);const i=Math.max(Math.abs(this._dy*t*e),2);h.PushOutSolid(s,r*(this._dy<0?1:-1),o*(this._dy<0?1:-1),i,g,p)?(this._SetLastFloorObject(p),this._floorIsJumpthru=g,this._dy>0&&(l=!0),(this._dy>0||0===this._ceilingCollisionMode)&&(this._dy=0),this._dy<0&&1===this._ceilingCollisionMode&&h.PushInFractional(s,r,o,p,32)):(n.SetXY(a,_),n.SetBboxChanged(),this._wasOnFloor=!0,g||(this._dy=0))}return[l,u]}_HandleAnimationTriggers(t,e,s){"falling"!==this._animMode&&this._dy>0&&!t&&(this.Trigger(i.Behaviors.Platform.Cnds.OnFall),this._animMode="falling"),(t||e)&&this._dy>=0&&("falling"===this._animMode||e||s&&0===this._dy?(this.Trigger(i.Behaviors.Platform.Cnds.OnLand),0===this._dx&&0===this._dy?this._animMode="stopped":this._animMode="moving"):("stopped"!==this._animMode&&0===this._dx&&0===this._dy&&(this.Trigger(i.Behaviors.Platform.Cnds.OnStop),this._animMode="stopped"),"moving"===this._animMode||0===this._dx&&0===this._dy||s||(this.Trigger(i.Behaviors.Platform.Cnds.OnMove),this._animMode="moving")))}_IsMoving(){return 0!==this._GetVectorX()||0!==this._GetVectorY()}_CheckIfStandingOnFloor(){if(0!==this._dy)return!1;const t=this._inst,e=this.GetWorldInfo(),i=this._runtime.GetCollisionEngine(),s=e.GetX(),n=e.GetY();e.OffsetXY(this._downX,this._downY),e.SetBboxChanged();const h=i.TestOverlapSolid(t);let r=null;if(!h&&this._IsFallThroughEnabled()&&(r=i.TestOverlapJumpthru(t,!0)),e.SetXY(s,n),e.SetBboxChanged(),h)return!i.TestOverlap(t,h);if(r&&r.length){let e=0;for(let s=0,n=r.length;s<n;++s)r[e]=r[s],i.TestOverlap(t,r[s])||e++;if(e>=1)return!0}return!1}_IsByWall(t,e=2,i=3){return!!this._GetWallObstacle(t,e,i)}_GetWallObstacle(t,e=2,i=3){const s=this._inst,n=this.GetWorldInfo(),h=this._runtime.GetCollisionEngine(),r=n.GetX(),o=n.GetY();if(0===t?n.OffsetXY(-this._rightX*e,-this._rightY*e):n.OffsetXY(this._rightX*e,this._rightY*e),n.SetBboxChanged(),!h.TestOverlapSolid(s))return n.SetXY(r,o),n.SetBboxChanged(),null;n.OffsetXY(-this._downX*i,-this._downY*i),n.SetBboxChanged();const l=h.TestOverlapSolid(s);return n.SetXY(r,o),n.SetBboxChanged(),l}_FallThroughJumpThru(){const t=this.GetWorldInfo(),e=t.GetX(),i=t.GetY();t.OffsetXY(this._downX,this._downY),t.SetBboxChanged();const s=this._runtime.GetCollisionEngine().TestOverlapJumpthru(this._inst,!1);t.SetXY(e,i),t.SetBboxChanged(),s&&(this._fallThroughTime=this._runtime.GetGameTime(),this._lastFloorObject=null)}_ResetDoubleJump(t){this._doubleJumped=!t}_GetSpeed(){return Math.hypot(this._dx,this._dy)}_GetMovingAngle(){return Math.atan2(this._dy,this._dx)}_IsJumping(){return this._dy<0}_IsFalling(){return this._dy>0}_SetMaxSpeed(t){this._maxSpeed=Math.max(t,0)}_GetMaxSpeed(){return this._maxSpeed}_SetAcceleration(t){this._acc=Math.max(t,0)}_GetAcceleration(){return this._acc}_SetDeceleration(t){this._dec=Math.max(t,0)}_GetDeceleration(){return this._dec}_SetJumpStrength(t){this._jumpStrength=Math.max(t,0)}_GetJumpStrength(){return this._jumpStrength}_SetMaxFallSpeed(t){this._maxFall=Math.max(t,0)}_GetMaxFallSpeed(){return this._maxFall}_SetGravity(t){if(this._g1===t)return;this._g=t,this._UpdateGravity();const e=this._runtime.GetCollisionEngine(),i=this.GetWorldInfo();e.TestOverlapSolid(this._inst)&&(e.PushOutSolid(this._inst,this._downX,this._downY,10),i.OffsetXY(2*this._downX,2*this._downY),i.SetBboxChanged()),this._lastFloorObject=null}_GetGravity(){return this._g}_SetGravityAngle(t){t=i.clampAngle(t),this._ga!==t&&(this._ga=t,this._UpdateGravity(),this._lastFloorObject=null)}_GetGravityAngle(){return this._ga}_SetDoubleJumpEnabled(t){this._enableDoubleJump=!!t}_IsDoubleJumpEnabled(){return this._enableDoubleJump}_SetJumpSustain(t){this._jumpSustain=t}_GetJumpSustain(){return this._jumpSustain}_SetCeilingCollisionMode(t){this._ceilingCollisionMode=t}_GetCeilingCollisionMode(){return this._ceilingCollisionMode}_SetVectorX(t){this._dx=t}_GetVectorX(){return this._dx}_SetVectorY(t){this._dy=t}_GetVectorY(){return this._dy}_SimulateControl(t){if(this._isEnabled)switch(t){case 0:this._simLeft=!0;break;case 1:this._simRight=!0;break;case 2:this._simJump=!0}}_SetDefaultControls(t){t=!!t,this._defaultControls!==t&&(this._defaultControls=t,this._defaultControls?this._BindEvents():(this._UnBindEvents(),this._OnWindowOrKeyboardBlur()))}_IsDefaultControls(){return this._defaultControls}_SetIgnoreInput(t){this._ignoreInput=!!t}_IsIgnoreInput(){return this._ignoreInput}_SetEnabled(t){t=!!t,this._isEnabled!==t&&(this._isEnabled=t,this._isEnabled?this._StartPostTicking():(this._StopPostTicking(),this._lastFloorObject=null,this._simLeft=!1,this._simRight=!1,this._simJump=!1))}_IsEnabled(){return this._isEnabled}GetPropertyValueByIndex(t){switch(t){case h:return this._GetMaxSpeed();case r:return this._GetAcceleration();case o:return this._GetDeceleration();case l:return this._GetJumpStrength();case a:return this._GetGravity();case _:return this._GetMaxFallSpeed();case u:return this._IsDoubleJumpEnabled();case d:return 1e3*this._GetJumpSustain();case m:return this._IsDefaultControls();case p:return this._IsEnabled()}}SetPropertyValueByIndex(t,e){switch(t){case h:this._SetMaxSpeed(e);break;case r:this._SetAcceleration(e);break;case o:this._SetDeceleration(e);break;case l:this._SetJumpStrength(e);break;case a:this._SetGravity(e);break;case _:this._SetMaxFallSpeed(e);break;case u:this._SetDoubleJumpEnabled(!!e);break;case d:this._SetJumpSustain(e/1e3);break;case m:this._SetDefaultControls(!!e);break;case p:this._SetEnabled(!!e)}}GetDebuggerProperties(){const t="behaviors.platform";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:t+".debugger.vector-x",value:this._GetVectorX(),onedit:t=>this._SetVectorX(t)},{name:t+".debugger.vector-y",value:this._GetVectorY(),onedit:t=>this._SetVectorY(t)},{name:t+".properties.max-speed.name",value:this._GetMaxSpeed(),onedit:t=>this._SetMaxSpeed(t)},{name:t+".properties.acceleration.name",value:this._GetAcceleration(),onedit:t=>this._SetAcceleration(t)},{name:t+".properties.deceleration.name",value:this._GetDeceleration(),onedit:t=>this._SetDeceleration(t)},{name:t+".properties.jump-strength.name",value:this._GetJumpStrength(),onedit:t=>this._SetJumpStrength(t)},{name:t+".properties.gravity.name",value:this._GetGravity(),onedit:t=>this._SetGravity(t)},{name:t+".debugger.gravity-angle",value:i.toDegrees(this._GetGravityAngle()),onedit:t=>this._SetGravityAngle(i.toRadians(t))},{name:t+".properties.max-fall-speed.name",value:this._GetMaxFallSpeed(),onedit:t=>this._SetMaxFallSpeed(t)},{name:t+".properties.double-jump.name",value:this._IsDoubleJumpEnabled(),onedit:t=>this._SetDoubleJumpEnabled(t)},{name:t+".properties.jump-sustain.name",value:1e3*this._GetJumpSustain(),onedit:t=>this._SetJumpSustain(t/1e3)},{name:t+".debugger.animation-mode",value:[t+".debugger.anim-"+this._animMode]},{name:t+".properties.enabled.name",value:this._IsEnabled(),onedit:t=>this._SetEnabled(t)}]}]}GetScriptInterfaceClass(){return self.IPlatformBehaviorInstance}};const c=new WeakMap,S=new Map([["left",0],["right",1],["jump",2]]);self.IPlatformBehaviorInstance=class extends n{constructor(){super(),c.set(this,n._GetInitInst().GetSdkInstance())}fallThrough(){c.get(this)._FallThroughJumpThru()}resetDoubleJump(t){c.get(this)._ResetDoubleJump(!!t)}simulateControl(t){s.RequireString(t);const e=S.get(t);if("number"!=typeof e)throw new Error("invalid control");c.get(this)._SimulateControl(e)}get speed(){return c.get(this)._GetSpeed()}get maxSpeed(){return c.get(this)._GetMaxSpeed()}set maxSpeed(t){s.RequireFiniteNumber(t),c.get(this)._SetMaxSpeed(t)}get acceleration(){return c.get(this)._GetAcceleration()}set acceleration(t){s.RequireFiniteNumber(t),c.get(this)._SetAcceleration(t)}get deceleration(){return c.get(this)._GetDeceleration()}set deceleration(t){s.RequireFiniteNumber(t),c.get(this)._SetDeceleration(t)}get jumpStrength(){return c.get(this)._GetJumpStrength()}set jumpStrength(t){s.RequireFiniteNumber(t),c.get(this)._SetJumpStrength(t)}get maxFallSpeed(){return c.get(this)._GetMaxFallSpeed()}set maxFallSpeed(t){s.RequireFiniteNumber(t),c.get(this)._SetMaxFallSpeed(t)}get gravity(){return c.get(this)._GetGravity()}set gravity(t){s.RequireFiniteNumber(t),c.get(this)._SetGravity(t)}get gravityAngle(){return c.get(this)._GetGravityAngle()}set gravityAngle(t){s.RequireFiniteNumber(t),c.get(this)._SetGravityAngle(t)}get isDoubleJumpEnabled(){return c.get(this)._IsDoubleJumpEnabled()}set isDoubleJumpEnabled(t){c.get(this)._SetDoubleJumpEnabled(!!t)}get jumpSustain(){return c.get(this)._GetJumpSustain()}set jumpSustain(t){s.RequireFiniteNumber(t),c.get(this)._SetJumpSustain(t)}get ceilingCollisionMode(){return 0===c.get(this)._GetCeilingCollisionMode()?"stop":"preserve-momentum"}set ceilingCollisionMode(t){s.RequireString(t);const e=c.get(this);if("stop"===t)e._SetCeilingCollisionMode(0);else{if("preserve-momentum"!==t)throw new Error("invalid mode");e._SetCeilingCollisionMode(1)}}get isOnFloor(){return c.get(this)._CheckIfStandingOnFloor()}isByWall(t){s.RequireString(t);const e=c.get(this);if("left"===t)return e._IsByWall(0);if("right"===t)return e._IsByWall(1);throw new Error("invalid side")}get isMoving(){return c.get(this)._IsMoving()}get isJumping(){return c.get(this)._IsJumping()}get isFalling(){return c.get(this)._IsFalling()}get vectorX(){return c.get(this)._GetVectorX()}set vectorX(t){s.RequireFiniteNumber(t),c.get(this)._SetVectorX(t)}get vectorY(){return c.get(this)._GetVectorY()}set vectorY(t){s.RequireFiniteNumber(t),c.get(this)._SetVectorY(t)}setVector(t,e){s.RequireFiniteNumber(t),s.RequireFiniteNumber(e);const i=c.get(this);i._SetVectorX(t),i._SetVectorY(e)}getVector(){const t=c.get(this);return[t._GetVectorX(),t._GetVectorY()]}get isDefaultControls(){return c.get(this)._IsDefaultControls()}set isDefaultControls(t){c.get(this)._SetDefaultControls(!!t)}get isIgnoringInput(){return c.get(this)._IsIgnoreInput()}set isIgnoringInput(t){c.get(this)._SetIgnoreInput(!!t)}get isEnabled(){return c.get(this)._IsEnabled()}set isEnabled(t){c.get(this)._SetEnabled(!!t)}}}{const b=self.C3;b.Behaviors.Platform.Cnds={IsMoving(){return this._IsMoving()},CompareSpeed(t,e){return b.compare(this._GetSpeed(),t,e)},IsOnFloor(){return this._CheckIfStandingOnFloor()},IsByWall(t){return this._IsByWall(t)},IsJumping(){return this._IsJumping()},IsFalling(){return this._IsFalling()},IsDoubleJumpEnabled(){return this._IsDoubleJumpEnabled()},OnJump:()=>!0,OnFall:()=>!0,OnStop:()=>!0,OnMove:()=>!0,OnLand:()=>!0,IsEnabled(){return this._IsEnabled()}}}{const f=self.C3;f.Behaviors.Platform.Acts={SetMaxSpeed(t){this._SetMaxSpeed(t)},SetAcceleration(t){this._SetAcceleration(t)},SetDeceleration(t){this._SetDeceleration(t)},SetJumpStrength(t){this._SetJumpStrength(t)},SetMaxFallSpeed(t){this._SetMaxFallSpeed(t)},SetGravity(t){this._SetGravity(t)},SimulateControl(t){this._SimulateControl(t)},SetIgnoreInput(t){this._SetIgnoreInput(!!t)},SetVectorX(t){this._SetVectorX(t)},SetVectorY(t){this._SetVectorY(t)},SetGravityAngle(t){this._SetGravityAngle(f.toRadians(t))},SetEnabled(t){this._SetEnabled(0!==t)},FallThrough(){this._FallThroughJumpThru()},SetDoubleJumpEnabled(t){this._SetDoubleJumpEnabled(0!==t)},SetJumpSustain(t){this._SetJumpSustain(t/1e3)},SetCeilingCollision(t){this._SetCeilingCollisionMode(t)},SetDefaultControls(t){this._SetDefaultControls(t)},ResetDoubleJump(t){this._ResetDoubleJump(t)}}}{const G=self.C3;G.Behaviors.Platform.Exps={Speed(){return this._GetSpeed()},MaxSpeed(){return this._GetMaxSpeed()},Acceleration(){return this._GetAcceleration()},Deceleration(){return this._GetDeceleration()},JumpStrength(){return this._GetJumpStrength()},Gravity(){return this._GetGravity()},GravityAngle(){return G.toDegrees(this._GetGravityAngle())},MaxFallSpeed(){return this._GetMaxFallSpeed()},MovingAngle(){return G.toDegrees(this._GetMovingAngle())},VectorX(){return this._GetVectorX()},VectorY(){return this._GetVectorY()},JumpSustain(){return 1e3*this._GetJumpSustain()}}}
}

// scripts/behaviors/Bullet/c3runtime/runtime.js
{
{const t=self.C3;t.Behaviors.Bullet=class extends t.SDKBehaviorBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3;t.Behaviors.Bullet.Type=class extends t.SDKBehaviorTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const t=self.C3,e=self.C3X,s=self.IBehaviorInstance,i=0,n=1,h=2,a=3,_=4,l=5,o=6;t.Behaviors.Bullet.Instance=class extends t.SDKBehaviorInstanceBase{constructor(t,e){super(t);const s=this.GetWorldInfo();this._speed=0,this._acc=0,this._g=0,this._bounceOffSolid=!1,this._setAngle=!1,this._isStepping=!1,this._isEnabled=!0,this._dx=0,this._dy=0,this._lastX=s.GetX(),this._lastY=s.GetY(),this._lastKnownAngle=s.GetAngle(),this._travelled=0,this._stepSize=Math.min(Math.abs(s.GetWidth()),Math.abs(s.GetHeight())/2),this._stopStepping=!1,e&&(this._speed=e[i],this._acc=e[n],this._g=e[h],this._bounceOffSolid=!!e[a],this._setAngle=!!e[_],this._isStepping=!!e[l],this._isEnabled=!!e[o]);const r=s.GetAngle();this._dx=Math.cos(r)*this._speed,this._dy=Math.sin(r)*this._speed,this._isEnabled&&(this._StartTicking(),this._bounceOffSolid&&this._StartPostTicking())}Release(){super.Release()}SaveToJson(){const t={"dx":this._dx,"dy":this._dy,"lx":this._lastX,"ly":this._lastY,"lka":this._lastKnownAngle,"t":this._travelled};return 0!==this._acc&&(t["acc"]=this._acc),0!==this._g&&(t["g"]=this._g),this._isStepping&&(t["st"]=this._isStepping),this._isEnabled||(t["e"]=this._isEnabled),this._bounceOffSolid&&(t["bos"]=this._bounceOffSolid),this._setAngle&&(t["sa"]=this._setAngle),t}LoadFromJson(t){this._dx=t["dx"],this._dy=t["dy"],this._lastX=t["lx"],this._lastY=t["ly"],this._lastKnownAngle=t["lka"],this._travelled=t["t"],this._acc=t.hasOwnProperty("acc")?t["acc"]:0,this._g=t.hasOwnProperty("g")?t["g"]:0,this._isStepping=!!t.hasOwnProperty("st")&&t["st"],this._bounceOffSolid=!!t.hasOwnProperty("bos")&&t["bos"],this._setAngle=!!t.hasOwnProperty("sa")&&t["sa"],this._SetEnabled(!t.hasOwnProperty("e")||t["e"])}Tick(){if(!this._isEnabled)return;const e=this._runtime.GetDt(this._inst),s=this._inst.GetWorldInfo();if(s.GetAngle()!==this._lastKnownAngle){const e=s.GetAngle();if(this._setAngle){const s=t.distanceTo(0,0,this._dx,this._dy);this._dx=Math.cos(e)*s,this._dy=Math.sin(e)*s}this._lastKnownAngle=e}let i=0,n=0;if(0!==this._acc){let h=t.distanceTo(0,0,this._dx,this._dy),a=0;a=0===this._dx&&0===this._dy?s.GetAngle():t.angleTo(0,0,this._dx,this._dy),h+=this._acc*e,i=Math.cos(a)*this._acc,n=Math.sin(a)*this._acc,h<0&&(h=0,i=0,n=0),this._dx=Math.cos(a)*h,this._dy=Math.sin(a)*h}if(0!==this._g&&(this._dy+=this._g*e,n+=this._g),this._lastX=s.GetX(),this._lastY=s.GetY(),0!==this._dx||0!==this._dy){const h=this._dx*e+.5*i*e*e,a=this._dy*e+.5*n*e*e,_=t.distanceTo(0,0,h,a);if(this._MoveBy(h,a,_),this._travelled+=_,this._setAngle&&(0!==h||0!==a)){const e=t.angleTo(0,0,h,a);s.SetAngle(e),this._lastKnownAngle=s.GetAngle()}s.SetBboxChanged()}}_MoveBy(e,s,i){const n=this.GetWorldInfo();if(!this._isStepping||i<=this._stepSize)return n.OffsetXY(e,s),n.SetBboxChanged(),void(this._isStepping&&this.Trigger(t.Behaviors.Bullet.Cnds.OnStep));this._stopStepping=!1;const h=n.GetX(),a=n.GetY(),_=h+e,l=a+s,o=t.angleTo(0,0,e,s),r=Math.cos(o)*this._stepSize,d=Math.sin(o)*this._stepSize,c=Math.floor(i/this._stepSize);for(let e=1;e<=c;++e)if(n.SetXY(h+r*e,a+d*e),n.SetBboxChanged(),this.Trigger(t.Behaviors.Bullet.Cnds.OnStep),this._inst.IsDestroyed()||this._stopStepping)return;n.SetXY(_,l),n.SetBboxChanged(),this.Trigger(t.Behaviors.Bullet.Cnds.OnStep)}PostTick(){if(!this._isEnabled||!this._bounceOffSolid||0===this._dx&&0===this._dy)return;const e=this._runtime.GetDt(this._inst),s=this._inst.GetWorldInfo(),i=this._runtime.GetCollisionEngine(),n=i.TestOverlapSolid(this._inst);if(n){i.RegisterCollision(this._inst,n);const h=t.distanceTo(0,0,this._dx,this._dy),a=i.CalculateBounceAngle(this._inst,this._lastX,this._lastY);this._dx=Math.cos(a)*h,this._dy=Math.sin(a)*h,s.OffsetXY(this._dx*e,this._dy*e),s.SetBboxChanged(),this._setAngle&&(s.SetAngle(a),this._lastKnownAngle=s.GetAngle(),s.SetBboxChanged()),i.PushOutSolid(this._inst,this._dx/h,this._dy/h,Math.max(2.5*h*e,30))||i.PushOutSolidNearest(this._inst,100)}}GetPropertyValueByIndex(t){switch(t){case i:return this._GetSpeed();case n:return this._GetAcceleration();case h:return this._GetGravity();case _:return this._setAngle;case l:return this._isStepping;case o:return this._IsEnabled()}}SetPropertyValueByIndex(t,e){switch(t){case i:this._SetSpeed(e);break;case n:this._acc=e;break;case h:this._g=e;break;case _:this._setAngle=!!e;break;case l:this._isStepping=!!e;break;case o:this._SetEnabled(!!e)}}_SetSpeed(e){const s=t.angleTo(0,0,this._dx,this._dy);this._dx=Math.cos(s)*e,this._dy=Math.sin(s)*e}_GetSpeed(){return t.roundToDp(t.distanceTo(0,0,this._dx,this._dy),6)}_SetAcceleration(t){this._acc=t}_GetAcceleration(){return this._acc}_SetGravity(t){this._g=t}_GetGravity(){return this._g}_SetAngleOfMotion(e){const s=t.distanceTo(0,0,this._dx,this._dy);this._dx=Math.cos(e)*s,this._dy=Math.sin(e)*s}_GetAngleOfMotion(){return t.angleTo(0,0,this._dx,this._dy)}_SetBounceOffSolids(t){t=!!t,this._bounceOffSolid!==t&&(this._bounceOffSolid=t,this._isEnabled&&(this._bounceOffSolid?this._StartPostTicking():this._StopPostTicking()))}_IsBounceOffSolids(){return this._bounceOffSolid}_SetDistanceTravelled(t){this._travelled=t}_GetDistanceTravelled(){return this._travelled}_SetEnabled(t){this._isEnabled=!!t,this._isEnabled?(this._StartTicking(),this._bounceOffSolid&&this._StartPostTicking()):(this._StopTicking(),this._StopPostTicking())}_IsEnabled(){return this._isEnabled}GetDebuggerProperties(){const e="behaviors.bullet";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:e+".debugger.vector-x",value:this._dx,onedit:t=>this._dx=t},{name:e+".debugger.vector-y",value:this._dy,onedit:t=>this._dy=t},{name:e+".properties.speed.name",value:this._GetSpeed(),onedit:t=>this._SetSpeed(t)},{name:e+".debugger.angle-of-motion",value:t.toDegrees(this._GetAngleOfMotion())},{name:e+".properties.gravity.name",value:this._GetGravity(),onedit:t=>this._SetGravity(t)},{name:e+".properties.acceleration.name",value:this._GetAcceleration(),onedit:t=>this._SetAcceleration(t)},{name:e+".debugger.distance-travelled",value:this._GetDistanceTravelled()},{name:e+".properties.enabled.name",value:this._IsEnabled(),onedit:t=>this._SetEnabled(t)}]}]}GetScriptInterfaceClass(){return self.IBulletBehaviorInstance}};const r=new WeakMap;self.IBulletBehaviorInstance=class extends s{constructor(){super(),r.set(this,s._GetInitInst().GetSdkInstance())}get speed(){return r.get(this)._GetSpeed()}set speed(t){e.RequireFiniteNumber(t),r.get(this)._SetSpeed(t)}get acceleration(){return r.get(this)._GetAcceleration()}set acceleration(t){e.RequireFiniteNumber(t),r.get(this)._SetAcceleration(t)}get gravity(){return r.get(this)._GetGravity()}set gravity(t){e.RequireFiniteNumber(t),r.get(this)._SetGravity(t)}get angleOfMotion(){return r.get(this)._GetAngleOfMotion()}set angleOfMotion(t){e.RequireFiniteNumber(t),r.get(this)._SetAngleOfMotion(t)}get bounceOffSolids(){return r.get(this)._IsBounceOffSolids()}set bounceOffSolids(t){r.get(this)._SetBounceOffSolids(!!t)}get distanceTravelled(){return r.get(this)._GetDistanceTravelled()}set distanceTravelled(t){e.RequireFiniteNumber(t),r.get(this)._SetDistanceTravelled(t)}get isEnabled(){return r.get(this)._IsEnabled()}set isEnabled(t){r.get(this)._SetEnabled(t)}}}{const t=self.C3;t.Behaviors.Bullet.Cnds={CompareSpeed(e,s){const i=Math.hypot(this._dx,this._dy);return t.compare(i,e,s)},CompareTravelled(e,s){return t.compare(this._GetDistanceTravelled(),e,s)},OnStep:()=>!0,IsEnabled(){return this._IsEnabled()}}}{const t=self.C3;t.Behaviors.Bullet.Acts={SetSpeed(t){this._SetSpeed(t)},SetAcceleration(t){this._SetAcceleration(t)},SetGravity(t){this._SetGravity(t)},SetAngleOfMotion(e){this._SetAngleOfMotion(t.toRadians(e))},Bounce(e){if(!e)return;const s=e.GetFirstPicked(this._inst);if(!s)return;const i=this._inst.GetWorldInfo(),n=this._runtime.GetCollisionEngine(),h=this._runtime.GetDt(this._inst),a=t.distanceTo(0,0,this._dx,this._dy),_=n.CalculateBounceAngle(this._inst,this._lastX,this._lastY,s);this._dx=Math.cos(_)*a,this._dy=Math.sin(_)*a,i.OffsetXY(this._dx*h,this._dy*h),i.SetBboxChanged(),this._setAngle&&(i.SetAngle(_),this._lastKnownAngle=i.GetAngle(),i.SetBboxChanged()),0!==a&&(this._bounceOffSolid?n.PushOutSolid(this._inst,this._dx/a,this._dy/a,Math.max(2.5*a*h,30))||n.PushOutSolidNearest(this._inst,100):n.PushOut(this._inst,this._dx/a,this._dy/a,Math.max(2.5*a*h,30),s))},SetBounceOffSolids(t){this._SetBounceOffSolids(t)},SetDistanceTravelled(t){this._SetDistanceTravelled(t)},SetEnabled(t){this._SetEnabled(t)},StopStepping(){this._stopStepping=!0}}}{const t=self.C3;t.Behaviors.Bullet.Exps={Speed(){return this._GetSpeed()},Acceleration(){return this._GetAcceleration()},AngleOfMotion(){return t.toDegrees(this._GetAngleOfMotion())},DistanceTravelled(){return this._GetDistanceTravelled()},Gravity(){return this._GetGravity()}}}
}

// scripts/behaviors/destroy/c3runtime/runtime.js
{
{const e=self.C3;e.Behaviors.destroy=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.destroy.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3;e.Behaviors.destroy.Instance=class extends e.SDKBehaviorInstanceBase{constructor(e,s){super(e),this._StartTicking()}Release(){super.Release()}Tick(){const e=this._inst.GetWorldInfo(),s=e.GetBoundingBox(),t=e.GetLayout();(s.getRight()<0||s.getBottom()<0||s.getLeft()>t.GetWidth()||s.getTop()>t.GetHeight())&&this._runtime.DestroyInstance(this._inst)}}}self.C3.Behaviors.destroy.Cnds={};self.C3.Behaviors.destroy.Acts={};self.C3.Behaviors.destroy.Exps={};
}

// scripts/behaviors/solid/c3runtime/runtime.js
{
{const e=self.C3;e.Behaviors.solid=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.solid.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,s=self.C3X,t=self.IBehaviorInstance,a=0,n=1,i=new Set;e.Behaviors.solid.Instance=class extends e.SDKBehaviorInstanceBase{constructor(e,s){super(e),this.SetEnabled(!0),s&&(this.SetEnabled(s[a]),this.SetTags(s[n]))}Release(){super.Release()}SetEnabled(e){this._inst._SetSolidEnabled(!!e)}IsEnabled(){return this._inst._IsSolidEnabled()}SetTags(e){const s=this._inst.GetSavedDataMap();if(!e.trim())return void s.delete("solidTags");let t=s.get("solidTags");t||(t=new Set,s.set("solidTags",t)),t.clear();for(const s of e.split(" "))s&&t.add(s.toLowerCase())}GetTags(){return this._inst.GetSavedDataMap().get("solidTags")||i}_GetTagsString(){return[...this.GetTags()].join(" ")}SaveToJson(){return{"e":this.IsEnabled()}}LoadFromJson(e){this.SetEnabled(e["e"])}GetPropertyValueByIndex(e){if(e===a)return this.IsEnabled()}SetPropertyValueByIndex(e,s){if(e===a)this.SetEnabled(s)}GetDebuggerProperties(){return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:"behaviors.solid.properties.enabled.name",value:this.IsEnabled(),onedit:e=>this.SetEnabled(e)},{name:"behaviors.solid.properties.tags.name",value:this._GetTagsString(),onedit:e=>this.SetTags(e)}]}]}GetScriptInterfaceClass(){return self.ISolidBehaviorInstance}};const r=new WeakMap;self.ISolidBehaviorInstance=class extends t{constructor(){super(),r.set(this,t._GetInitInst().GetSdkInstance())}set isEnabled(e){r.get(this).SetEnabled(!!e)}get isEnabled(){return r.get(this).IsEnabled()}set tags(e){s.RequireString(e),r.get(this).SetTags(e)}get tags(){return r.get(this)._GetTagsString()}}}self.C3.Behaviors.solid.Cnds={IsEnabled(){return this.IsEnabled()}};self.C3.Behaviors.solid.Acts={SetEnabled(e){this.SetEnabled(e)},SetTags(e){this.SetTags(e)}};self.C3.Behaviors.solid.Exps={};
}

// scripts/behaviors/Rotate/c3runtime/runtime.js
{
{const e=self.C3;e.Behaviors.Rotate=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.Rotate.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=self.C3X,s=self.IBehaviorInstance,a=0,i=1,n=2;e.Behaviors.Rotate.Instance=class extends e.SDKBehaviorInstanceBase{constructor(t,s){super(t),this._speed=0,this._acceleration=0,this._isEnabled=!0,s&&(this._speed=e.toRadians(s[a]),this._acceleration=e.toRadians(s[i]),this._isEnabled=s[n]),this._isEnabled&&this._StartTicking()}Release(){super.Release()}_SetSpeed(e){this._speed=e}_GetSpeed(){return this._speed}_SetAcceleration(e){this._acceleration=e}_GetAcceleration(){return this._acceleration}SaveToJson(){return{"s":this._speed,"a":this._acceleration,"e":this._isEnabled}}LoadFromJson(e){this._speed=e["s"],this._acceleration=e["a"],this._SetEnabled(e["e"])}Tick(){if(!this._isEnabled)return;const e=this._runtime.GetDt(this._inst);if(0!==e&&(0!==this._acceleration&&(this._speed+=this._acceleration*e),0!==this._speed)){const t=this._inst.GetWorldInfo();t.SetAngle(t.GetAngle()+this._speed*e),t.SetBboxChanged()}}GetPropertyValueByIndex(t){switch(t){case a:return e.toDegrees(this._GetSpeed());case i:return e.toDegrees(this._GetAcceleration());case n:return this._IsEnabled()}}SetPropertyValueByIndex(t,s){switch(t){case a:this._SetSpeed(e.toRadians(s));break;case i:this._SetAcceleration(e.toRadians(s));break;case n:this._SetEnabled(s)}}_SetEnabled(e){this._isEnabled=!!e,this._isEnabled?this._StartTicking():this._StopTicking()}_IsEnabled(){return this._isEnabled}GetDebuggerProperties(){const t="behaviors.rotate";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:t+".properties.speed.name",value:e.toDegrees(this._GetSpeed()),onedit:t=>this._SetSpeed(e.toRadians(t))},{name:t+".properties.acceleration.name",value:e.toDegrees(this._GetAcceleration()),onedit:t=>this._SetAcceleration(e.toRadians(t))},{name:t+".properties.enabled.name",value:this._IsEnabled(),onedit:e=>this._SetEnabled(e)}]}]}GetScriptInterfaceClass(){return self.IRotateBehaviorInstance}};const r=new WeakMap;self.IRotateBehaviorInstance=class extends s{constructor(){super(),r.set(this,s._GetInitInst().GetSdkInstance())}set speed(e){t.RequireFiniteNumber(e),r.get(this)._SetSpeed(e)}get speed(){return r.get(this)._GetSpeed()}set acceleration(e){t.RequireFiniteNumber(e),r.get(this)._SetAcceleration(e)}get acceleration(){return r.get(this)._GetAcceleration()}get isEnabled(){return r.get(this)._IsEnabled()}set isEnabled(e){r.get(this)._SetEnabled(e)}}}self.C3.Behaviors.Rotate.Cnds={IsEnabled(){return this._IsEnabled()}};{const e=self.C3;e.Behaviors.Rotate.Acts={SetSpeed(t){this._SetSpeed(e.toRadians(t))},SetAcceleration(t){this._SetAcceleration(e.toRadians(t))},SetEnabled(e){this._SetEnabled(e)}}}{const e=self.C3;e.Behaviors.Rotate.Exps={Speed(){return e.toDegrees(this._GetSpeed())},Acceleration(){return e.toDegrees(this._GetAcceleration())}}}
}

// scripts/behaviors/Sin/c3runtime/runtime.js
{
{const e=self.C3;e.Behaviors.Sin=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.Sin.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=self.C3X,i=self.IBehaviorInstance,s=0,a=1,n=2,h=3,_=4,r=5,o=6,l=7,u=8,d=0,m=1,g=2,v=3,c=4,p=5,G=6,b=7,S=8,V=9,w=0,P=1,M=2,I=3,f=4,k=2*Math.PI,W=Math.PI/2,E=3*Math.PI/2,R=[0,1,8,3,4,2,5,6,9,7];e.Behaviors.Sin.Instance=class extends e.SDKBehaviorInstanceBase{constructor(t,i){super(t),this._i=0,this._movement=0,this._wave=0,this._period=0,this._mag=0,this._isEnabled=!0,this._basePeriod=0,this._basePeriodOffset=0,this._baseMag=0,this._periodRandom=0,this._periodOffsetRandom=0,this._magnitudeRandom=0,this._initialValue=0,this._initialValue2=0,this._lastKnownValue=0,this._lastKnownValue2=0,this._ratio=0,i&&(this._movement=R[i[s]],this._wave=i[a],this._periodRandom=this._runtime.Random()*i[h],this._basePeriod=i[n],this._period=i[n],this._period+=this._periodRandom,this._basePeriodOffset=i[_],0!==this._period&&(this._periodOffsetRandom=this._runtime.Random()*i[r],this._i=i[_]/this._period*k,this._i+=this._periodOffsetRandom/this._period*k),this._magnitudeRandom=this._runtime.Random()*i[l],this._baseMag=i[o],this._mag=i[o],this._mag+=this._magnitudeRandom,this._isEnabled=!!i[u]),this._movement===p&&(this._mag=e.toRadians(this._mag)),this.Init(),this._isEnabled&&this._StartTicking()}Release(){super.Release()}SaveToJson(){return{"i":this._i,"e":this._isEnabled,"mv":this._movement,"w":this._wave,"p":this._period,"mag":this._mag,"iv":this._initialValue,"iv2":this._initialValue2,"r":this._ratio,"lkv":this._lastKnownValue,"lkv2":this._lastKnownValue2}}LoadFromJson(e){this._i=e["i"],this._SetEnabled(e["e"]),this._movement=e["mv"],this._wave=e["w"],this._period=e["p"],this._mag=e["mag"],this._initialValue=e["iv"],this._initialValue2=e["iv2"],this._ratio=e["r"],this._lastKnownValue=e["lkv"],this._lastKnownValue2=e["lkv2"]}Init(){const e=this._inst.GetWorldInfo();switch(this._movement){case d:this._initialValue=e.GetX();break;case m:this._initialValue=e.GetY();break;case g:this._initialValue=e.GetWidth(),this._ratio=e.GetHeight()/e.GetWidth();break;case v:this._initialValue=e.GetWidth();break;case c:this._initialValue=e.GetHeight();break;case p:this._initialValue=e.GetAngle();break;case G:this._initialValue=e.GetOpacity();break;case b:this._initialValue=0;break;case S:this._initialValue=e.GetX(),this._initialValue2=e.GetY();break;case V:this._initialValue=e.GetZElevation()}this._lastKnownValue=this._initialValue,this._lastKnownValue2=this._initialValue2}WaveFunc(e){switch(e%=k,this._wave){case w:return Math.sin(e);case P:return e<=W?e/W:e<=E?1-2*(e-W)/Math.PI:(e-E)/W-1;case M:return 2*e/k-1;case I:return-2*e/k+1;case f:return e<Math.PI?-1:1}return 0}Tick(){const e=this._runtime.GetDt(this._inst);this._isEnabled&&0!==e&&(0===this._period?this._i=0:this._i=(this._i+e/this._period*k)%k,this._UpdateFromPhase())}_UpdateFromPhase(){const t=this._inst.GetWorldInfo();switch(this._movement){case d:t.GetX()!==this._lastKnownValue&&(this._initialValue+=t.GetX()-this._lastKnownValue),t.SetX(this._initialValue+this.WaveFunc(this._i)*this._mag),this._lastKnownValue=t.GetX();break;case m:t.GetY()!==this._lastKnownValue&&(this._initialValue+=t.GetY()-this._lastKnownValue),t.SetY(this._initialValue+this.WaveFunc(this._i)*this._mag),this._lastKnownValue=t.GetY();break;case g:t.SetWidth(this._initialValue+this.WaveFunc(this._i)*this._mag),t.SetHeight(t.GetWidth()*this._ratio);break;case v:t.SetWidth(this._initialValue+this.WaveFunc(this._i)*this._mag);break;case c:t.SetHeight(this._initialValue+this.WaveFunc(this._i)*this._mag);break;case p:t.GetAngle()!==this._lastKnownValue&&(this._initialValue=e.clampAngle(this._initialValue+(t.GetAngle()-this._lastKnownValue))),t.SetAngle(this._initialValue+this.WaveFunc(this._i)*this._mag),this._lastKnownValue=t.GetAngle();break;case G:t.SetOpacity(this._initialValue+this.WaveFunc(this._i)*this._mag/100);break;case S:t.GetX()!==this._lastKnownValue&&(this._initialValue+=t.GetX()-this._lastKnownValue),t.GetY()!==this._lastKnownValue2&&(this._initialValue2+=t.GetY()-this._lastKnownValue2),t.SetX(this._initialValue+Math.cos(t.GetAngle())*this.WaveFunc(this._i)*this._mag),t.SetY(this._initialValue2+Math.sin(t.GetAngle())*this.WaveFunc(this._i)*this._mag),this._lastKnownValue=t.GetX(),this._lastKnownValue2=t.GetY();break;case V:t.SetZElevation(this._initialValue+this.WaveFunc(this._i)*this._mag)}t.SetBboxChanged()}_OnSpriteFrameChanged(e,t){}_SetPeriod(e){this._period=e}_GetPeriod(){return this._period}_SetMagnitude(e){this._mag=e}_SetMagnitude_ConvertAngle(t){5===this._movement&&(t=e.toRadians(t)),this._SetMagnitude(t)}_GetMagnitude(){return this._mag}_GetMagnitude_ConvertAngle(){let t=this._GetMagnitude();return 5===this._movement&&(t=e.toDegrees(t)),t}_SetMovement(t){5===this._movement&&5!==t&&(this._mag=e.toDegrees(this._mag)),this._movement=t,this.Init()}_GetMovement(){return this._movement}_SetWave(e){this._wave=e}_GetWave(){return this._wave}_SetPhase(t){this._i=e.clamp(t,0,2*Math.PI),this._UpdateFromPhase()}_GetPhase(){return this._i}_SetEnabled(e){this._isEnabled=!!e,this._isEnabled?this._StartTicking():this._StopTicking()}_IsEnabled(){return this._isEnabled}GetPropertyValueByIndex(e){switch(e){case s:return this._movement;case a:return this._wave;case n:return this._basePeriod;case o:return this._baseMag;case u:return this._isEnabled}}SetPropertyValueByIndex(t,i){switch(t){case s:this._movement=R[i],this.Init();break;case a:this._wave=i;break;case n:this._basePeriod=i,this._period=this._basePeriod+this._periodRandom,this._isEnabled||(0!==this._period?(this._i=this._basePeriodOffset/this._period*k,this._i+=this._periodOffsetRandom/this._period*k):this._i=0);break;case o:this._baseMag=i,this._mag=this._baseMag+this._magnitudeRandom,this._movement===p&&(this._mag=e.toRadians(this._mag));break;case u:this._isEnabled=!!i}}GetDebuggerProperties(){const e="behaviors.sin";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:e+".properties.enabled.name",value:this._IsEnabled(),onedit:e=>this._SetEnabled(e)},{name:e+".properties.period.name",value:this._GetPeriod(),onedit:e=>this._SetPeriod(e)},{name:e+".properties.magnitude.name",value:this._GetMagnitude_ConvertAngle(),onedit:e=>this._SetMagnitude_ConvertAngle(e)},{name:e+".debugger.value",value:this.WaveFunc(this._GetPhase())*this._GetMagnitude_ConvertAngle()}]}]}GetScriptInterfaceClass(){return self.ISineBehaviorInstance}};const C=new WeakMap,K=["horizontal","vertical","size","width","height","angle","opacity","value-only","forwards-backwards","z-elevation"],F=["sine","triangle","sawtooth","reverse-sawtooth","square"];self.ISineBehaviorInstance=class extends i{constructor(){super(),C.set(this,i._GetInitInst().GetSdkInstance())}set period(e){t.RequireFiniteNumber(e),C.get(this)._SetPeriod(e)}get period(){return C.get(this)._GetPeriod()}set magnitude(e){t.RequireFiniteNumber(e),C.get(this)._SetMagnitude(e)}get magnitude(){return C.get(this)._GetMagnitude()}set phase(e){C.get(this)._SetPhase(e)}get phase(){return C.get(this)._GetPhase()}set movement(e){t.RequireString(e);const i=K.indexOf(e);if(-1===i)throw new Error("invalid movement");C.get(this)._SetMovement(i)}get movement(){return K[C.get(this)._GetMovement()]}set wave(e){t.RequireString(e);const i=F.indexOf(e);if(-1===i)throw new Error("invalid wave");C.get(this)._SetWave(i)}get wave(){return F[C.get(this)._GetWave()]}get value(){const e=C.get(this);return e.WaveFunc(e._GetPhase())*e._GetMagnitude()}updateInitialState(){C.get(this).Init()}set isEnabled(e){C.get(this)._SetEnabled(!!e)}get isEnabled(){return C.get(this)._IsEnabled()}}}{const e=self.C3;e.Behaviors.Sin.Cnds={IsEnabled(){return this._IsEnabled()},CompareMovement(e){return this._GetMovement()===e},ComparePeriod(t,i){return e.compare(this._GetPeriod(),t,i)},CompareMagnitude(t,i){return e.compare(this._GetMagnitude_ConvertAngle(),t,i)},CompareWave(e){return this._GetWave()===e}}}self.C3.Behaviors.Sin.Acts={SetEnabled(e){this._SetEnabled(0!==e)},SetPeriod(e){this._SetPeriod(e)},SetMagnitude(e){this._SetMagnitude_ConvertAngle(e)},SetMovement(e){this._SetMovement(e)},SetWave(e){this._wave=e},SetPhase(e){const t=2*Math.PI;this._SetPhase(e*t%t)},UpdateInitialState(){this.Init()}};self.C3.Behaviors.Sin.Exps={CyclePosition(){return this._GetPhase()/(2*Math.PI)},Period(){return this._GetPeriod()},Magnitude(){return this._GetMagnitude_ConvertAngle()},Value(){return this.WaveFunc(this._GetPhase())*this._GetMagnitude_ConvertAngle()}};
}

// scripts/expTable.js
{

const C3 = self.C3;

function unaryminus(n)
{
	return (typeof n === "number" ? -n : n);
}

function bothNumbers(a, b)
{
	return typeof a === "number" && typeof b === "number";
}

function add(l, r)
{
	if (bothNumbers(l, r))
		return l + r;
	else
		return l;
}

function subtract(l, r)
{
	if (bothNumbers(l, r))
		return l - r;
	else
		return l;
}

function multiply(l, r)
{
	if (bothNumbers(l, r))
		return l * r;
	else
		return l;
}

function divide(l, r)
{
	if (bothNumbers(l, r))
		return l / r;
	else
		return l;
}

function mod(l, r)
{
	if (bothNumbers(l, r))
		return l % r;
	else
		return l;
}

function pow(l, r)
{
	if (bothNumbers(l, r))
		return Math.pow(l, r);
	else
		return l;
}

function and(l, r)
{
	if (typeof l === "string" || typeof r === "string")
	{
		// & with either side string does string concatenation
		let lstr, rstr;

		if (typeof l === "number")
			lstr = (Math.round(l * 1e10) / 1e10).toString();
		else
			lstr = l;
		
		if (typeof r === "number")
			rstr = (Math.round(r * 1e10) / 1e10).toString();
		else
			rstr = r;
		
		return lstr + rstr;
	}
	else
	{
		// & with neither side a string does logical AND
		return (l && r ? 1 : 0);
	}
}

function or(l, r)
{
	if (bothNumbers(l, r))
		return (l || r ? 1 : 0);
	else
		return l;
}

self.C3_ExpressionFuncs = [
		() => "START",
		() => "Music",
		() => 90,
		p => {
			const v0 = p._GetNode(0).GetVar();
			return () => v0.GetValue();
		},
		() => "BG",
		() => -5,
		() => -2687,
		() => -34,
		() => -2390,
		() => -16,
		() => -1593,
		() => -10,
		() => -1594,
		() => 2600,
		() => -2165,
		() => 4082,
		() => -683,
		() => 2556,
		() => -2209,
		() => "PLAYER",
		() => 0,
		() => 1,
		() => "Sounds",
		() => 3,
		() => 2,
		() => "",
		() => "Car_Sound",
		() => "ON",
		() => 270,
		p => {
			const v0 = p._GetNode(0).GetVar();
			return () => (v0.GetValue() - 5);
		},
		() => 800,
		() => -1,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() - 1);
		},
		() => -15,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() - 5);
		},
		() => 340,
		() => -30,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() - 10);
		},
		() => 320,
		() => 4,
		() => -45,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() - 15);
		},
		() => 300,
		() => 5,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() + 1);
		},
		() => 15,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() + 5);
		},
		() => 20,
		() => 30,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() + 10);
		},
		() => 40,
		() => 45,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() + 15);
		},
		() => 60,
		() => -40,
		() => -90,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() - 2);
		},
		() => 400,
		() => 650,
		() => 550,
		() => 250,
		() => 450,
		() => 200,
		() => -20,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() + 2);
		},
		p => {
			const n0 = p._GetNode(0);
			return () => n0.ExpObject();
		},
		() => 1418,
		() => 25,
		p => {
			const v0 = p._GetNode(0).GetVar();
			return () => and("SCORE: ", v0.GetValue());
		},
		() => "Sound",
		() => "INTERFACE",
		() => 0.8,
		() => "CARS/BONUS",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0(0, 1, 2, 3, 4, 5);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0(0, 1, 2, 3, 4, 5, 6, 7, 8);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0(0, 1, 2);
		},
		() => "EVENTS",
		() => 896,
		() => -975,
		() => 1186,
		() => 1483,
		() => 2028,
		() => 2340,
		() => 2643,
		() => 886,
		() => -1302,
		() => 1481,
		() => 2021,
		() => 2631,
		() => -111,
		() => 1191,
		() => 1484,
		() => 2035,
		() => 2336,
		() => -1332,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0(0, 1, 2, 3);
		},
		() => "GAME OVER",
		() => "Record",
		() => 541,
		() => 894,
		() => 278.613874,
		() => 944.163047,
		() => 284,
		() => 1097,
		() => 423,
		() => 1294,
		() => 652,
		() => "OFF",
		() => 0.1,
		() => "START2",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0();
		},
		() => "BG2",
		() => "BUTTONS",
		() => "CREDITS",
		() => 540,
		() => 973,
		() => 1331,
		() => "SETTINGS",
		() => 1044,
		() => 1399,
		() => 1076
];


}

