@m2c2kit/core 0.3.24 → 0.3.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,3 +1,3 @@
1
1
  var lt=(g=>(g.Node="Node",g.Scene="Scene",g.Sprite="Sprite",g.Label="Label",g.TextLine="TextLine",g.Shape="Shape",g.Composite="Composite",g.SoundPlayer="SoundPlayer",g.SoundRecorder="SoundRecorder",g))(lt||{});const Ut={Deferred:"Deferred",WillFetch:"WillFetch",Fetching:"Fetching",Fetched:"Fetched",Decoding:"Decoding",Ready:"Ready",Error:"Error"};var gt=(g=>(g.Sequence="Sequence",g.Group="Group",g.Wait="Wait",g.Custom="Custom",g.Move="Move",g.Scale="Scale",g.FadeAlpha="FadeAlpha",g.Rotate="Rotate",g.Play="Play",g.Repeat="Repeat",g.RepeatForever="RepeatForever",g))(gt||{});const _t=class et{static toTypeAsString(t){switch(t){case et.none:return"None";case et.linear:return"Linear";case et.quadraticIn:return"QuadraticIn";case et.quadraticOut:return"QuadraticOut";case et.quadraticInOut:return"QuadraticInOut";case et.cubicIn:return"CubicIn";case et.cubicOut:return"CubicOut";case et.cubicInOut:return"CubicInOut";case et.quarticIn:return"QuarticIn";case et.quarticOut:return"QuarticOut";case et.quarticInOut:return"QuarticInOut";case et.quinticIn:return"QuinticIn";case et.quinticOut:return"QuinticOut";case et.quinticInOut:return"QuinticInOut";case et.sinusoidalIn:return"SinusoidalIn";case et.sinusoidalOut:return"SinusoidalOut";case et.sinusoidalInOut:return"SinusoidalInOut";case et.exponentialIn:return"ExponentialIn";case et.exponentialOut:return"ExponentialOut";case et.exponentialInOut:return"ExponentialInOut";case et.circularIn:return"CircularIn";case et.circularOut:return"CircularOut";case et.circularInOut:return"CircularInOut";default:throw new Error("Easings.toTypeAsString(): Unknown easing function")}}static fromTypeAsString(t){switch(t){case"None":return et.none;case"Linear":return et.linear;case"QuadraticIn":return et.quadraticIn;case"QuadraticOut":return et.quadraticOut;case"QuadraticInOut":return et.quadraticInOut;case"CubicIn":return et.cubicIn;case"CubicOut":return et.cubicOut;case"CubicInOut":return et.cubicInOut;case"QuarticIn":return et.quarticIn;case"QuarticOut":return et.quarticOut;case"QuarticInOut":return et.quarticInOut;case"QuinticIn":return et.quinticIn;case"QuinticOut":return et.quinticOut;case"QuinticInOut":return et.quinticInOut;case"SinusoidalIn":return et.sinusoidalIn;case"SinusoidalOut":return et.sinusoidalOut;case"SinusoidalInOut":return et.sinusoidalInOut;case"ExponentialIn":return et.exponentialIn;case"ExponentialOut":return et.exponentialOut;case"ExponentialInOut":return et.exponentialInOut;case"CircularIn":return et.circularIn;case"CircularOut":return et.circularOut;case"CircularInOut":return et.circularInOut;default:throw new Error(`Easings.fromTypeAsString(): Unknown easing function type ${t}`)}}};_t.none=(g,t,i,n)=>i+t,_t.linear=(g,t,i,n)=>i*g/n+t,_t.quadraticIn=(g,t,i,n)=>(g/=n,i*g*g+t),_t.quadraticOut=(g,t,i,n)=>(g/=n,-i*g*(g-2)+t),_t.quadraticInOut=(g,t,i,n)=>(g/=n/2,g<1?i/2*g*g+t:(g--,-i/2*(g*(g-2)-1)+t)),_t.cubicIn=(g,t,i,n)=>(g/=n,i*g*g*g+t),_t.cubicOut=(g,t,i,n)=>(g/=n,g--,i*(g*g*g+1)+t),_t.cubicInOut=(g,t,i,n)=>(g/=n/2,g<1?i/2*g*g*g+t:(g-=2,i/2*(g*g*g+2)+t)),_t.quarticIn=(g,t,i,n)=>(g/=n,i*g*g*g*g+t),_t.quarticOut=(g,t,i,n)=>(g/=n,g--,-i*(g*g*g*g-1)+t),_t.quarticInOut=(g,t,i,n)=>(g/=n/2,g<1?i/2*g*g*g*g+t:(g-=2,-i/2*(g*g*g*g-2)+t)),_t.quinticIn=(g,t,i,n)=>(g/=n,i*g*g*g*g*g+t),_t.quinticOut=(g,t,i,n)=>(g/=n,g--,i*(g*g*g*g*g+1)+t),_t.quinticInOut=(g,t,i,n)=>(g/=n/2,g<1?i/2*g*g*g*g*g+t:(g-=2,i/2*(g*g*g*g*g+2)+t)),_t.sinusoidalIn=(g,t,i,n)=>-i*Math.cos(g/n*(Math.PI/2))+i+t,_t.sinusoidalOut=(g,t,i,n)=>i*Math.sin(g/n*(Math.PI/2))+t,_t.sinusoidalInOut=(g,t,i,n)=>-i/2*(Math.cos(Math.PI*g/n)-1)+t,_t.exponentialIn=(g,t,i,n)=>i*Math.pow(2,10*(g/n-1))+t,_t.exponentialOut=(g,t,i,n)=>i*(-Math.pow(2,-10*g/n)+1)+t,_t.exponentialInOut=(g,t,i,n)=>(g/=n/2,g<1?i/2*Math.pow(2,10*(g-1))+t:(g--,i/2*(-Math.pow(2,-10*g)+2)+t)),_t.circularIn=(g,t,i,n)=>(g/=n,-i*(Math.sqrt(1-g*g)-1)+t),_t.circularOut=(g,t,i,n)=>(g/=n,g--,i*Math.sqrt(1-g*g)+t),_t.circularInOut=(g,t,i,n)=>(g/=n/2,g<1?-i/2*(Math.sqrt(1-g*g)-1)+t:(g-=2,i/2*(Math.sqrt(1-g*g)+1)+t));let Re=_t;var Wt=(g=>(g.Undefined="Undefined",g.Rectangle="Rectangle",g.Circle="Circle",g.Path="Path",g))(Wt||{});const dn=class jn{constructor(t){this.startTime=NaN,this.stopTime=NaN,this.stopped=!0,this.cumulativeElapsed=NaN,this.name=t}static now(){return window.performance.now()}static new(t){this._timers=this._timers.filter(n=>n.name!==t);const i=new jn(t);i.cumulativeElapsed=0,this._timers.push(i)}static startNew(t){this.new(t),this.start(t)}static start(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't start timer. timer with name ${t} does not exist.`);if(i.stopped===!1)throw new Error(`can't start timer. timer with name ${t} is already started.`);i.startTime=window.performance.now(),i.stopped=!1}static stop(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't stop timer. timer with name ${t} does not exist.`);if(i.stopped===!0)throw new Error(`can't stop timer. timer with name ${t} is already stopped.`);i.stopTime=window.performance.now(),i.cumulativeElapsed=i.cumulativeElapsed+i.stopTime-i.startTime,i.stopped=!0}static elapsed(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't get elapsed time. timer with name ${t} does not exist.`);return i.stopped?i.cumulativeElapsed:i.cumulativeElapsed+window.performance.now()-i.startTime}static remove(t){if(this._timers.filter(n=>n.name===t).find(Boolean)===void 0)throw new Error(`can't remove timer. timer with name ${t} does not exist.`);this._timers=this._timers.filter(n=>n.name!=t)}static removeAll(){this._timers=new Array}static exists(t){return this._timers.some(i=>i.name===t)}};dn._timers=new Array;let Gt=dn;class x{}x.Transparent=[0,0,0,0],x.MediumVioletRed=[199,21,133,1],x.DeepPink=[255,20,147,1],x.PaleVioletRed=[219,112,147,1],x.HotPink=[255,105,180,1],x.LightPink=[255,182,193,1],x.Pink=[255,192,203,1],x.DarkRed=[139,0,0,1],x.Red=[255,0,0,1],x.Firebrick=[178,34,34,1],x.Crimson=[220,20,60,1],x.IndianRed=[205,92,92,1],x.LightCoral=[240,128,128,1],x.Salmon=[250,128,114,1],x.DarkSalmon=[233,150,122,1],x.LightSalmon=[255,160,122,1],x.OrangeRed=[255,69,0,1],x.Tomato=[255,99,71,1],x.DarkOrange=[255,140,0,1],x.Coral=[255,127,80,1],x.Orange=[255,165,0,1],x.DarkKhaki=[189,183,107,1],x.Gold=[255,215,0,1],x.Khaki=[240,230,140,1],x.PeachPuff=[255,218,185,1],x.Yellow=[255,255,0,1],x.PaleGoldenrod=[238,232,170,1],x.Moccasin=[255,228,181,1],x.PapayaWhip=[255,239,213,1],x.LightGoldenrodYellow=[250,250,210,1],x.LemonChiffon=[255,250,205,1],x.LightYellow=[255,255,224,1],x.Maroon=[128,0,0,1],x.Brown=[165,42,42,1],x.SaddleBrown=[139,69,19,1],x.Sienna=[160,82,45,1],x.Chocolate=[210,105,30,1],x.DarkGoldenrod=[184,134,11,1],x.Peru=[205,133,63,1],x.RosyBrown=[188,143,143,1],x.Goldenrod=[218,165,32,1],x.SandyBrown=[244,164,96,1],x.Tan=[210,180,140,1],x.Burlywood=[222,184,135,1],x.Wheat=[245,222,179,1],x.NavajoWhite=[255,222,173,1],x.Bisque=[255,228,196,1],x.BlanchedAlmond=[255,235,205,1],x.Cornsilk=[255,248,220,1],x.DarkGreen=[0,100,0,1],x.Green=[0,128,0,1],x.DarkOliveGreen=[85,107,47,1],x.ForestGreen=[34,139,34,1],x.SeaGreen=[46,139,87,1],x.Olive=[128,128,0,1],x.OliveDrab=[107,142,35,1],x.MediumSeaGreen=[60,179,113,1],x.LimeGreen=[50,205,50,1],x.Lime=[0,255,0,1],x.SpringGreen=[0,255,127,1],x.MediumSpringGreen=[0,250,154,1],x.DarkSeaGreen=[143,188,143,1],x.MediumAquamarine=[102,205,170,1],x.YellowGreen=[154,205,50,1],x.LawnGreen=[124,252,0,1],x.Chartreuse=[127,255,0,1],x.LightGreen=[144,238,144,1],x.GreenYellow=[173,255,47,1],x.PaleGreen=[152,251,152,1],x.Teal=[0,128,128,1],x.DarkCyan=[0,139,139,1],x.LightSeaGreen=[32,178,170,1],x.CadetBlue=[95,158,160,1],x.DarkTurquoise=[0,206,209,1],x.MediumTurquoise=[72,209,204,1],x.Turquoise=[64,224,208,1],x.Aqua=[0,255,255,1],x.Cyan=[0,255,255,1],x.Aquamarine=[127,255,212,1],x.PaleTurquoise=[175,238,238,1],x.LightCyan=[224,255,255,1],x.Navy=[0,0,128,1],x.DarkBlue=[0,0,139,1],x.MediumBlue=[0,0,205,1],x.Blue=[0,0,255,1],x.MidnightBlue=[25,25,112,1],x.RoyalBlue=[65,105,225,1],x.SteelBlue=[70,130,180,1],x.DodgerBlue=[30,144,255,1],x.DeepSkyBlue=[0,191,255,1],x.CornflowerBlue=[100,149,237,1],x.SkyBlue=[135,206,235,1],x.LightSkyBlue=[135,206,250,1],x.LightSteelBlue=[176,196,222,1],x.LightBlue=[173,216,230,1],x.PowderBlue=[176,224,230,1],x.Indigo=[75,0,130,1],x.Purple=[128,0,128,1],x.DarkMagenta=[139,0,139,1],x.DarkViolet=[148,0,211,1],x.DarkSlateBlue=[72,61,139,1],x.BlueViolet=[138,43,226,1],x.DarkOrchid=[153,50,204,1],x.Fuchsia=[255,0,255,1],x.Magenta=[255,0,255,1],x.SlateBlue=[106,90,205,1],x.MediumSlateBlue=[123,104,238,1],x.MediumOrchid=[186,85,211,1],x.MediumPurple=[147,112,219,1],x.Orchid=[218,112,214,1],x.Violet=[238,130,238,1],x.Plum=[221,160,221,1],x.Thistle=[216,191,216,1],x.Lavender=[230,230,250,1],x.MistyRose=[255,228,225,1],x.AntiqueWhite=[250,235,215,1],x.Linen=[250,240,230,1],x.Beige=[245,245,220,1],x.WhiteSmoke=[245,245,245,1],x.LavenderBlush=[255,240,245,1],x.OldLace=[253,245,230,1],x.AliceBlue=[240,248,255,1],x.Seashell=[255,245,238,1],x.GhostWhite=[248,248,255,1],x.Honeydew=[240,255,240,1],x.FloralWhite=[255,250,240,1],x.Azure=[240,255,255,1],x.MintCream=[245,255,250,1],x.Snow=[255,250,250,1],x.Ivory=[255,255,240,1],x.White=[255,255,255,1],x.Black=[0,0,0,1],x.DarkSlateGray=[47,79,79,1],x.DimGray=[105,105,105,1],x.SlateGray=[112,128,144,1],x.Gray=[128,128,128,1],x.LightSlateGray=[119,136,153,1],x.DarkGray=[169,169,169,1],x.Silver=[192,192,192,1],x.LightGray=[211,211,211,1],x.Gainsboro=[220,220,220,1],x.RebeccaPurple=[102,51,153,1];class X{}X.FPS_DISPLAY_TEXT_FONT_SIZE=12,X.FPS_DISPLAY_TEXT_COLOR=[0,0,0,.5],X.FPS_DISPLAY_UPDATE_INTERVAL=1e3,X.MAXIMUM_RECORDED_ACTIVITY_METRICS=32,X.FPS_METRIC_REPORT_THRESHOLD=59,X.DEFAULT_SCENE_BACKGROUND_COLOR=x.White,X.DEFAULT_SHAPE_FILL_COLOR=x.Red,X.DEFAULT_PATH_STROKE_COLOR=x.Red,X.DEFAULT_PATH_LINE_WIDTH=2,X.DEFAULT_FONT_COLOR=x.Black,X.DEFAULT_FONT_SIZE=16,X.LIMITED_FPS_RATE=5,X.FREE_NODES_SCENE_NAME="__freeNodesScene",X.OUTGOING_SCENE_NAME="__outgoingScene",X.OUTGOING_SCENE_SPRITE_NAME="__outgoingSceneSprite",X.OUTGOING_SCENE_IMAGE_NAME="__outgoingSceneSnapshot",X.SESSION_INITIALIZATION_POLLING_INTERVAL_MS=50,X.MODULE_METADATA_PLACEHOLDER={name:"",version:"",dependencies:{}},X.DEFAULT_ROOT_ELEMENT_ID="m2c2kit",X.ERUDA_URL="https://cdn.jsdelivr.net/npm/eruda@3.2.3/eruda.js",X.ERUDA_SRI="sha384-KlRzgy/c+nZSV+eiFqoTkkbZ5pUqToho7HsNuebTbOsYTh4m0m/PAqkGsTMLXK14";class Y{static getUrlFromManifest(t,i){const n=t.manifest;return n&&n[i]?n[i]:i}static urlHasScheme(t){return/^[a-z]+:\/\//i.test(t)}static convertValueToType(t,i){function n(U){return typeof U=="string"||typeof U=="object"||!Number.isNaN(parseFloat(U))||typeof U=="boolean"}function c(U){if(typeof U=="string")return U;if(typeof U=="object")return console.warn(`convertValueToType() converted an object to a string. This may not be the desired behavior. The object was: ${JSON.stringify(U)}`),JSON.stringify(U);if(!Number.isNaN(parseFloat(U)))return U;if(typeof U=="boolean")return U.toString();throw new Error(`Error parsing "${U}" as a string.`)}function h(U){if(typeof U=="number")return!0;if(typeof U!="string")return!1;const at=parseFloat(U);return!Number.isNaN(at)}function C(U){if(typeof U=="number")return U;if(typeof U!="string")throw new Error(`Error parsing "${U}" as a number.`);const at=parseFloat(U);if(Number.isNaN(at))throw new Error(`Error parsing "${U}" as a number.`);return at}function T(U){if(typeof U=="number")return!0;if(typeof U!="string")return!1;const at=parseInt(U);return!Number.isNaN(at)}function B(U){if(typeof U=="number")return U;if(typeof U!="string")throw new Error(`Error parsing "${U}" as an integer.`);const at=parseInt(U);if(Number.isNaN(at))throw new Error(`Error parsing "${U}" as an integer.`);return at}function $(U){return typeof U=="boolean"?!0:!(U!=="true"&&U!=="false")}function it(U){if(typeof U=="boolean")return U;if(U!=="true"&&U!=="false")throw new Error(`Error parsing "${U}" as a boolean.`);return U==="true"}function ct(U){if(Array.isArray(U))return!0;if(typeof U!="string")return!1;try{const at=JSON.parse(U);if(Array.isArray(at))return!0}catch{const at=JSON.parse(decodeURIComponent(U));if(Array.isArray(at))return!0}return!1}function ut(U){if(Array.isArray(U))return U;if(typeof U!="string")throw new Error(`Error parsing "${U}" as an array.`);try{const at=JSON.parse(U);if(Array.isArray(at))return at}catch{const at=JSON.parse(decodeURIComponent(U));if(Array.isArray(at))return at}throw new Error(`Error parsing "${U}" as an array.`)}function bt(U){if(typeof U=="object"&&!Array.isArray(U)&&U!==null)return!0;if(typeof U!="string")return!1;try{const at=JSON.parse(U);if(typeof at=="object"&&!Array.isArray(at)&&at!==null)return!0}catch{const at=JSON.parse(decodeURIComponent(U));if(typeof at=="object"&&!Array.isArray(at)&&at!==null)return!0}return!1}function wt(U){if(typeof U=="object"&&!Array.isArray(U)&&U!==null)return U;if(typeof U!="string")throw new Error(`Error parsing "${U}" as an object.`);try{const at=JSON.parse(U);if(typeof at=="object"&&!Array.isArray(at)&&at!==null)return at}catch{const at=JSON.parse(decodeURIComponent(U));if(typeof at=="object"&&!Array.isArray(at)&&at!==null)return at}throw new Error(`Error parsing "${U}" as an object.`)}function Ht(U){return U===null||U==="null"}function fe(U){if(U!=="null"&&U!==null)throw new Error(`Error parsing "${U}" as null.`);return null}const pe={string:n,number:h,integer:T,boolean:$,array:ct,object:bt,null:Ht},ve={string:c,number:C,integer:B,boolean:it,array:ut,object:wt,null:fe};if(i===void 0)throw new Error(`Error with "${t}" as a target type.`);if(!Array.isArray(i)){if(pe[i](t))return ve[i](t);throw new Error(`Error parsing "${t}" as a ${i}.`)}for(const U of i)if(pe[U](t))return ve[U](t);throw new Error(`Error parsing "${t}" as one of ${i}.`)}static loadScriptUrls(t){if(!Array.isArray(t)||!t.every(i=>typeof i=="string")){console.warn('Error parsing "scripts" parameter. "scripts" must be an array of URL strings, and it is recommended to be URI encoded.');return}t.forEach(i=>{if(!m2c2Globals.addedScriptUrls.includes(i)){const n=document.createElement("script");n.src=i,n.async=!0,document.head.appendChild(n),console.log(`\u26AA added script: ${i}`),m2c2Globals.addedScriptUrls.push(i)}})}static loadEruda(t=100,i=50){if(m2c2Globals.erudaRequested===!0)return;console.log(`\u26AA added eruda script: ${X.ERUDA_URL}`);const n=document.createElement("script");n.src=X.ERUDA_URL,n.integrity=X.ERUDA_SRI,n.crossOrigin="anonymous",n.async=!0,document.head.appendChild(n),m2c2Globals.erudaRequested=!0;let c=0;const h=()=>{const C=window?.eruda;typeof C<"u"?(console.log("\u26AA eruda ready"),C.init(),m2c2Globals.erudaInitialized=!0):c<i?(c++,setTimeout(h,t)):console.log(`eruda was requested, but could not be loaded after ${t*i} milliseconds.`)};h()}static registerM2NodeClass(...t){m2c2Globals.m2NodeClassRegistry||(m2c2Globals.m2NodeClassRegistry={}),t.forEach(i=>{m2c2Globals.m2NodeClassRegistry={...m2c2Globals.m2NodeClassRegistry,[i.name]:i}})}static createFrameUpdateTimestamps(){return{timestamp:Number.isNaN(m2c2Globals?.now)||m2c2Globals?.now===void 0?Gt.now():m2c2Globals.now,iso8601Timestamp:m2c2Globals.iso8601Now?m2c2Globals.iso8601Now:new Date().toISOString()}}static createTimestamps(){return{timestamp:Gt.now(),iso8601Timestamp:new Date().toISOString()}}static calculateRotatedPoints(t){const i=t.ancestors;i.reverse(),i.push(t);const n=i.map(c=>{const h=Y.calculateNodeAbsoluteBoundingBox(c);return Y.boundingBoxToPoints(h)});for(let c=0;c<n.length;c++){if(!sr(i[c]))continue;const h=n[c],C=i[c].zRotation,T=Y.findCentroid(h);for(let B=c;B<i.length;B++)n[B]=Vs(n[B],C,T)}return n[n.length-1]}static rotateCanvasForDrawableNode(t,i){const n=Y.calculateRotationTransforms(i);if(n.length===0)return;const c=m2c2Globals.canvasScale/i.absoluteScale;Ks(n,c,t)}static calculateNodeAbsoluteBoundingBox(t){const i=t.anchorPoint,n=t.absoluteScale;let c=t.size.width,h=t.size.height;if(t.type===lt.Shape&&t.shapeType===Wt.Circle){const it=t.circleOfRadius;if(!it)throw"circleOfRadius is undefined";c=it*2,h=it*2}const C=t.absolutePosition.x-c*i.x*n,T=t.absolutePosition.x+c*(1-i.x)*n,B=t.absolutePosition.y-h*i.y*n,$=t.absolutePosition.y+h*(1-i.y)*n;return{xMin:C,xMax:T,yMin:B,yMax:$}}static radiansToDegrees(t){return-Y.normalizeAngleRadians(t)*(180/Math.PI)}static normalizeAngleRadians(t){const i=Math.floor(t/(2*Math.PI));let n=t-i*(2*Math.PI);return n<0&&(n+=2*Math.PI),n}static arePointsOnSameSideOfLine(t,i,n,c){const h=(c.x-n.x)*(t.y-n.y)-(c.y-n.y)*(t.x-n.x),C=(c.x-n.x)*(i.y-n.y)-(c.y-n.y)*(i.x-n.x);return h*C>=0}static isPointInsideRectangle(t,i){if(i.length!==4)throw new Error("Invalid input: expected an array of four points");return Y.arePointsOnSameSideOfLine(t,i[2],i[0],i[1])&&Y.arePointsOnSameSideOfLine(t,i[3],i[1],i[2])&&Y.arePointsOnSameSideOfLine(t,i[0],i[2],i[3])&&Y.arePointsOnSameSideOfLine(t,i[1],i[3],i[0])}static nodeOrAncestorHasBeenRotated(t){const i=t.ancestors;return i.push(t),i.some(n=>sr(n))}static boundingBoxToPoints(t){const{xMin:i,xMax:n,yMin:c,yMax:h}=t;return[{x:i,y:c},{x:n,y:c},{x:n,y:h},{x:i,y:h}]}static findCentroid(t){if(t.length!==4)throw new Error("Invalid input: expected an array of four points");let i=0,n=0;for(const C of t)i+=C.x,n+=C.y;const c=i/4,h=n/4;return{x:c,y:h}}static rotatePoint(t,i,n){const c=t.x-n.x,h=t.y-n.y,C=c*Math.cos(-i)-h*Math.sin(-i),T=c*Math.sin(-i)+h*Math.cos(-i);return{x:C+n.x,y:T+n.y}}static calculateRotationTransforms(t){const i=[],n=t.ancestors;return n.reverse(),n.push(t),n.forEach(c=>{if(sr(c)){const h=c;if(h.type===lt.Scene){const $={x:h.absolutePosition.x+h.size.width*.5,y:h.absolutePosition.y+h.size.height*.5};i.push({radians:h.zRotation,center:$});return}const C=Y.calculateNodeAbsoluteBoundingBox(h),T=Y.boundingBoxToPoints(C),B=Y.findCentroid(T);i.push({radians:h.zRotation,center:B})}}),i}}function Ks(g,t,i){g.forEach(n=>{i.rotate(Y.radiansToDegrees(n.radians),n.center.x*t,n.center.y*t)})}function sr(g){return Y.normalizeAngleRadians(g.zRotation)!==0&&g.isDrawable}function Vs(g,t,i){if(g.length!==4)throw new Error("Invalid input: expected an array of four points");const n=[];for(const c of g)n.push(Y.rotatePoint(c,t,i));return n}class Nt{constructor(t){if(this.expression=new Array,this.WARNING_EXPRESSION_LENGTH=32,typeof t=="number"){this.pushToExpression(t);return}if(t===void 0){this.pushToExpression(1/0);return}this.pushToExpression(t)}pushToExpression(t){if(t===this)throw new Error("Cannot add, subtract, or assign a Futurable with itself.");this.expression.push(t),this.expression.length===this.WARNING_EXPRESSION_LENGTH&&console.warn(`Expression length is ${this.WARNING_EXPRESSION_LENGTH} elements. Something may be wrong.`)}assign(t){for(;this.expression.length>0;)this.expression.pop();this.pushToExpression(t)}add(...t){return this.appendOperation(Ri.Add,...t),this}subtract(...t){return this.appendOperation(Ri.Subtract,...t),this}appendOperation(t,...i){i.forEach(n=>{this.pushToExpression(t),this.pushToExpression(n)})}get value(){let t=0;const i=this.expression.flat(1/0);let n=1;for(let c=0;c<i.length;c++){if(typeof i[c]=="number"){t=t+n*i[c];continue}if(i[c]instanceof Nt){t=t+n*i[c].value;continue}if(i[c]===Ri.Add){n=1;continue}if(i[c]===Ri.Subtract){n=-1;continue}}return t}}const Ri={Add:"Add",Subtract:"Subtract"};class q{constructor(t=!1){this.startOffset=new Nt(0),this.started=!1,this.running=!1,this._completed=!1,this.runStartTime=-1,this.duration=new Nt,this.runDuringTransition=t}initialize(t){const i=this.clone();return this.assignParents(i,i,t),this.propagateRunDuringTransition(i),this.assignDurations(i),this.assignStartOffsets(i),i}assignParents(t,i,n){if(n!==void 0&&(t.key=n),this.isParent(t)){const c=t.children;c.forEach(h=>{h.parent=t}),c.filter(h=>this.isParent(h)).forEach(h=>this.assignParents(h,i,n))}}propagateRunDuringTransition(t){this.isParent(t)&&(t.descendants.some(i=>i.runDuringTransition)&&(t.runDuringTransition=!0),t.children.forEach(i=>this.propagateRunDuringTransition(i)))}assignDurations(t){t.duration=this.calculateDuration(t),this.isParent(t)&&t.children.forEach(i=>this.assignDurations(i))}calculateDuration(t){if(t.type===gt.Group){const n=t.children.map(c=>this.calculateDuration(c)).reduce((c,h)=>Math.max(c,h.value),0);return new Nt(n)}if(t.type===gt.Sequence){const n=t.children.map(c=>this.calculateDuration(c)).reduce((c,h)=>c+h.value,0);return new Nt(n)}return this.isRepeating(t)?new Nt:t.duration}assignStartOffsets(t){t.startOffset=this.calculateStartOffset(t),this.isParent(t)&&t.children.forEach(i=>this.assignStartOffsets(i))}calculateStartOffset(t){if(t.parent===void 0)return new Nt(0);if(t.parent.type!==gt.Sequence)return t.parent.startOffset;const i=new Nt(0);i.add(t.parent.startOffset);for(const n of t.parent.children){if(n===t)break;i.add(n.duration)}return i}static evaluateAction(t,i,n,c){if(i.involvedInSceneTransition()&&!t.runDuringTransition||(t.runStartTime===-1&&t.assignRunStartTimes(t,n),n<t.runStartTime+t.startOffset.value))return;if(t.shouldBeRunning(n)&&(t.running=!0),t.isParent(t)){if(t.children.forEach(C=>{q.evaluateAction(C,i,n,c)}),!t.isRepeating(t)){t.started||(t.started=!0),t.running&&t.completed&&(t.running=!1);return}q.evaluateRepeatingActions(t,n);return}if(t.shouldBeRunning(n)||(t.running=!1),t.running===!1&&t.completed===!0)return;const h=n-(t.runStartTime+t.startOffset.value);switch(t.type){case gt.Custom:q.evaluateCustomAction(t);break;case gt.Play:q.evaluatePlayAction(i,t);break;case gt.Wait:q.evaluateWaitAction(t,n);break;case gt.Move:q.evaluateMoveAction(t,i,h);break;case gt.Scale:q.evaluateScaleAction(t,i,h,c);break;case gt.FadeAlpha:q.evaluateFadeAlphaAction(t,i,h,c);break;case gt.Rotate:q.evaluateRotateAction(t,i,h,c);break;default:throw new Error(`Action type not recognized: ${t.type}`)}}static evaluateRepeatingActions(t,i){if(t.started||(t.started=!0),t.repetitionHasCompleted){t.completedRepetitions++;const n=t.children[0].duration.value;if(t.cumulativeDuration=t.cumulativeDuration+n,!isFinite(n))throw"repetitionDuration is not finite";if(!t.completed)t.restartAction(t,i);else{if(t.type===gt.RepeatForever)throw new Error("RepeatForever action should never complete");t.duration.assign(t.cumulativeDuration),t.running=!1}}}static evaluateRotateAction(t,i,n,c){const h=t;h.started||(h.byAngle!==void 0&&(h.delta=h.byAngle),h.toAngle!==void 0&&(h.toAngle=Y.normalizeAngleRadians(h.toAngle),i.zRotation=Y.normalizeAngleRadians(i.zRotation),h.delta=h.toAngle-i.zRotation,h.shortestUnitArc===!0&&Math.abs(h.delta)>Math.PI&&(h.delta=2*Math.PI-Math.abs(h.delta))),h.started=!0,h.finalValue=i.zRotation+h.delta),n<h.duration.value?(i.zRotation=i.zRotation+h.delta*(c/h.duration.value),h.delta<=0&&i.zRotation<h.finalValue&&(i.zRotation=h.finalValue),h.delta>0&&i.zRotation>h.finalValue&&(i.zRotation=h.finalValue)):(i.zRotation=h.finalValue,h.running=!1,h.completed=!0)}static evaluateFadeAlphaAction(t,i,n,c){const h=t;h.started||(h.delta=h.alpha-i.alpha,h.started=!0),n<h.duration.value?i.alpha=i.alpha+h.delta*(c/h.duration.value):(i.alpha=h.alpha,h.running=!1,h.completed=!0)}static evaluateScaleAction(t,i,n,c){const h=t;h.started||(h.delta=h.scale-i.scale,h.started=!0),n<h.duration.value?i.scale=i.scale+h.delta*(c/h.duration.value):(i.scale=h.scale,h.running=!1,h.completed=!0)}static evaluateMoveAction(t,i,n){const c=t;c.started||(c.dx=c.point.x-i.position.x,c.dy=c.point.y-i.position.y,c.startPoint.x=i.position.x,c.startPoint.y=i.position.y,c.started=!0),n<c.duration.value?(i.position.x=c.easing(n,c.startPoint.x,c.dx,c.duration.value),i.position.y=c.easing(n,c.startPoint.y,c.dy,c.duration.value)):(i.position.x=c.point.x,i.position.y=c.point.y,c.running=!1,c.completed=!0)}static evaluateWaitAction(t,i){const n=t;i>t.runStartTime+t.startOffset.value+t.duration.value&&(n.running=!1,n.completed=!0)}static evaluatePlayAction(t,i){if(t.type!==lt.SoundPlayer)throw new Error("Play action can only be used with a SoundPlayer");const n=i,c=t,h=c.game.soundManager;if(!n.started){const C=h.getSound(c.soundName);if(C.audioBuffer){const T=h.audioContext.createBufferSource();T.buffer=C.audioBuffer,T.onended=()=>{n.running=!1,n.completed=!0;const B=performance.now()-(i.runStartTime+i.startOffset.value);i.duration.assign(B)},T.connect(h.audioContext.destination),T.start(),n.started=!0}else{if(C.status===Ut.Error)throw new Error(`error loading sound ${C.soundName} (url ${C.url})`);console.warn(`Play action: audio buffer not ready for sound ${c.soundName} (url: ${C.url}); will try next frame`),C.status===Ut.Deferred&&h.fetchDeferredSound(C)}}}static evaluateCustomAction(t){const i=t;i.callback(),i.running=!1,i.completed=!0}assignRunStartTimes(t,i){t.runStartTime=i,t.isParent(t)&&t.children.forEach(n=>{t.assignRunStartTimes(n,i)})}restartAction(t,i){if(t.runStartTime=i,t.running=!0,t.started=!0,t.type===gt.Play&&(t.duration=new Nt),t.isParent(t)){t.children.forEach(n=>{t.restartAction(n,i)});return}t.completed=!1}shouldBeRunning(t){return t>=this.runStartTime+this.startOffset.value&&t<=this.runStartTime+this.startOffset.value+this.duration.value}static move(t){return new wn(t.point,new Nt(t.duration),t.easing??Re.linear,t.runDuringTransition??!1)}static wait(t){return new vn(new Nt(t.duration),t.runDuringTransition??!1)}static custom(t){return new gn(t.callback,t.runDuringTransition??!1)}static play(t){return new yn(t?.runDuringTransition??!1)}static scale(t){return new Sn(t.scale,new Nt(t.duration),t.runDuringTransition)}static fadeAlpha(t){return new bn(t.alpha,new Nt(t.duration),t.runDuringTransition)}static rotate(t){if(t.byAngle!==void 0&&t.toAngle!==void 0)throw new Error("rotate Action: cannot specify both byAngle and toAngle");if(t.byAngle===void 0&&t.toAngle===void 0)throw new Error("rotate Action: must specify either byAngle or toAngle");if(t.toAngle===void 0&&t.shortestUnitArc!==void 0)throw new Error("rotate Action: shortestUnitArc can only be specified when toAngle is provided");return t.toAngle!==void 0&&t.shortestUnitArc===void 0&&(t.shortestUnitArc=!0),new Pn(t.byAngle,t.toAngle,t.shortestUnitArc,new Nt(t.duration),t.runDuringTransition)}static sequence(t){const i=new fn(t);return i.children=t,i}static group(t){const i=new pn(t);return i.children=t,i}static repeat(t){return new ar(t.action,t.count,t.runDuringTransition)}static repeatForever(t){return new mn(t.action,t.runDuringTransition)}isParent(t){return t.type===gt.Group||t.type===gt.Sequence||t.type===gt.Repeat||t.type===gt.RepeatForever}isRepeating(t){return t.type===gt.Repeat||t.type===gt.RepeatForever}get completed(){return this._completed}set completed(t){this._completed=t}}class fn extends q{constructor(t){super(),this.type=gt.Sequence,this.children=t}clone(){const t=this.children.map(n=>n.clone()),i=q.sequence(t);return i.children.forEach(n=>n.key=this.key),i.key=this.key,i}get completed(){return this.children.every(t=>t.completed)}get descendants(){return or(this)}}class pn extends q{constructor(t){super(),this.type=gt.Group,this.children=new Array,this.children=t}clone(){const t=this.children.map(n=>n.clone()),i=q.group(t);return i.children.forEach(n=>n.key=this.key),i.key=this.key,i}get completed(){return this.children.every(t=>t.completed)}get descendants(){return or(this)}}class ar extends q{constructor(t,i,n=!1){super(n),this.type=gt.Repeat,this.completedRepetitions=0,this.cumulativeDuration=0,this.children=[t],this.count=i,this.duration=new Nt}clone(){if(this.children.length!==1)throw new Error("Repeat action must have exactly one child");const t=q.repeat({action:this.children[0].clone(),count:this.count,runDuringTransition:this.runDuringTransition});return t.children[0].key=this.key,t.key=this.key,t}get completed(){return this.children.every(t=>t.completed)&&this.completedRepetitions===this.count}get descendantsAreCompleted(){return this.children.every(t=>t.completed)}get repetitionHasCompleted(){return this.running&&this.descendantsAreCompleted&&!this.completed}get descendants(){return or(this)}}class mn extends ar{constructor(t,i=!1){super(t,1/0,i),this.type=gt.RepeatForever,this.count=1/0}clone(){if(this.children.length!==1)throw new Error("RepeatForever action must have exactly one child");const t=q.repeatForever({action:this.children[0].clone(),runDuringTransition:this.runDuringTransition});return t.children[0].key=this.key,t.key=this.key,t}}function or(g){const t=[];function i(n){if(n.isParent(n))for(const c of n.children)t.push(c),i(c)}return i(g),t}class gn extends q{constructor(t,i=!1){super(i),this.type=gt.Custom,this.callback=t,this.duration=new Nt(0)}clone(){const t=q.custom({callback:this.callback,runDuringTransition:this.runDuringTransition});return t.key=this.key,t}}class yn extends q{constructor(t=!1){super(t),this.type=gt.Play,this.duration=new Nt}clone(){const t=q.play({runDuringTransition:this.runDuringTransition});return t.key=this.key,t}}class vn extends q{constructor(t,i){super(i),this.type=gt.Wait,this.duration=t}clone(){const t=q.wait({duration:this.duration.value,runDuringTransition:this.runDuringTransition});return t.key=this.key,t}}class wn extends q{constructor(t,i,n,c){super(c),this.type=gt.Move,this.startPoint={x:NaN,y:NaN},this.dx=0,this.dy=0,this.duration=i,this.point=t,this.easing=n}clone(){const t=q.move({point:this.point,duration:this.duration.value,easing:this.easing,runDuringTransition:this.runDuringTransition});return t.key=this.key,t}}class Sn extends q{constructor(t,i,n=!1){super(n),this.type=gt.Scale,this.delta=0,this.duration=i,this.scale=t}clone(){const t=q.scale({scale:this.scale,duration:this.duration.value,runDuringTransition:this.runDuringTransition});return t.key=this.key,t}}class bn extends q{constructor(t,i,n=!1){super(n),this.type=gt.FadeAlpha,this.delta=0,this.duration=i,this.alpha=t}clone(){const t=q.fadeAlpha({alpha:this.alpha,duration:this.duration.value,runDuringTransition:this.runDuringTransition});return t.key=this.key,t}}class Pn extends q{constructor(t,i,n,c,h=!1){super(h),this.type=gt.Rotate,this.delta=0,this.finalValue=NaN,this.duration=c,this.byAngle=t,this.toAngle=i,this.shortestUnitArc=n}clone(){const t=q.rotate({byAngle:this.byAngle,toAngle:this.toAngle,shortestUnitArc:this.shortestUnitArc,duration:this.duration.value,runDuringTransition:this.runDuringTransition});return t.key=this.key,t}}var oi=(g=>(g.Game="Game",g.Survey="Survey",g))(oi||{});class xt{static Dispose(t){t.filter(i=>!i?.isDeleted()).forEach(i=>i?.delete())}static makePaint(t,i,n,c){const h=new t.Paint;return h.setColor(t.Color(i[0],i[1],i[2],i[3])),h.setStyle(n),h.setAntiAlias(c),h}}class Oi{constructor(){this._subpaths=new Array,this.currentPath=new Array}get subpaths(){return this.currentPath.length>0?[...this._subpaths,this.currentPath]:this._subpaths}move(t){this.currentPath.length>0&&this._subpaths.push(this.currentPath),this.currentPath=new Array,this.currentPath.push(t)}addLine(t){this.currentPath.push(t)}clear(){this._subpaths=new Array,this.currentPath=new Array}duplicate(){const t=new Oi;return t._subpaths=JSON.parse(JSON.stringify(this._subpaths)),t.currentPath=JSON.parse(JSON.stringify(this.currentPath)),t}}class qs extends Oi{constructor(){super(...arguments),this.strokeColor=X.DEFAULT_PATH_STROKE_COLOR,this.lineWidth=X.DEFAULT_PATH_LINE_WIDTH,this.linePresentations=[]}addLine(t){this.isNewLinePresentation()&&this.linePresentations.push({strokeColor:this.strokeColor,lineWidth:this.lineWidth,subpathIndex:this._subpaths.length,pointIndex:this.currentPath.length-1}),this.currentPath.push(t)}isNewLinePresentation(){if(this.linePresentations.length===0)return!0;const t=this.linePresentations[this.linePresentations.length-1];return t.strokeColor!==this.strokeColor||t.lineWidth!==this.lineWidth}clear(){super.clear(),this.linePresentations=[],this.strokeColor=X.DEFAULT_PATH_STROKE_COLOR,this.lineWidth=X.DEFAULT_PATH_LINE_WIDTH}duplicate(){const t=super.duplicate();return t.strokeColor=JSON.parse(JSON.stringify(this.strokeColor)),t.lineWidth=this.lineWidth,t.linePresentations=JSON.parse(JSON.stringify(this.linePresentations)),t}}var Bt=(g=>(g.topToTopOf="topToTopOf",g.topToBottomOf="topToBottomOf",g.bottomToTopOf="bottomToTopOf",g.bottomToBottomOf="bottomToBottomOf",g.startToStartOf="startToStartOf",g.startToEndOf="startToEndOf",g.endToEndOf="endToEndOf",g.endToStartOf="endToStartOf",g))(Bt||{});class An{constructor(t,i){this.verticalConstraint=!1,this.focalNodeMinimum=!1,this.alterNodeMinimum=!1,this.verticalTypes=[Bt.topToTopOf,Bt.topToBottomOf,Bt.bottomToTopOf,Bt.bottomToBottomOf],this.focalNodeMinimumTypes=[Bt.topToTopOf,Bt.topToBottomOf,Bt.startToStartOf,Bt.startToEndOf],this.alterNodeMinimumTypes=[Bt.topToTopOf,Bt.bottomToTopOf,Bt.startToStartOf,Bt.endToStartOf],this.type=t,this.alterNode=i,this.verticalTypes.includes(t)?(this.verticalConstraint=!0,this.focalNodeMinimumTypes.includes(t)?this.focalNodeMinimum=!0:this.focalNodeMinimum=!1,this.alterNodeMinimumTypes.includes(t)?this.alterNodeMinimum=!0:this.alterNodeMinimum=!1):(this.verticalConstraint=!1,this.focalNodeMinimumTypes.includes(t)?this.focalNodeMinimum=!0:this.focalNodeMinimum=!1,this.alterNodeMinimumTypes.includes(t)?this.alterNodeMinimum=!0:this.alterNodeMinimum=!1)}}class Ue{static generate(){try{return crypto.randomUUID()}catch{let t;try{t=()=>crypto.getRandomValues(new Uint8Array(1))[0]}catch{t=()=>Math.floor(Math.random()*256)}return("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,i=>(Number(i)^t()&15>>Number(i)/4).toString(16))}}static isValid(t){return t?t==="00000000-0000-0000-0000-000000000000"?!0:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t):!1}}const j={ActivityStart:"ActivityStart",ActivityEnd:"ActivityEnd",ActivityCancel:"ActivityCancel",ActivityData:"ActivityData",GameWarmupStart:"GameWarmupStart",GameWarmupEnd:"GameWarmupEnd",TapDown:"TapDown",TapUp:"TapUp",TapUpAny:"TapUpAny",TapLeave:"TapLeave",PointerDown:"PointerDown",PointerUp:"PointerUp",PointerMove:"PointerMove",PointerLeave:"PointerLeave",Drag:"Drag",DragStart:"DragStart",DragEnd:"DragEnd",Composite:"Composite",FrameDidSimulatePhysics:"FrameDidSimulatePhysics",SceneSetup:"SceneSetup",SceneAppear:"SceneAppear",ScenePresent:"ScenePresent",NodeNew:"NodeNew",NodeAddChild:"NodeAddChild",NodeRemoveChild:"NodeRemoveChild",NodePropertyChange:"NodePropertyChange",DomPointerDown:"DomPointerDown",BrowserImageDataReady:"BrowserImageDataReady",I18nDataReadyEvent:"I18nDataReadyEvent"};class H{static rgbaColor(t,i){return!t||!i?!1:t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]}static value(t,i){return typeof t!=typeof i?!1:t&&typeof t=="object"&&i&&typeof i=="object"?H.objectsDeepEqual(t,i):t===i}static objectsDeepEqual(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!H.objectsDeepEqual(t[n],i[n]))return!1;return!0}if(typeof t=="object"&&!Array.isArray(t)&&t!==null&&typeof i=="object"&&!Array.isArray(i)&&i!==null){const n=Object.keys(t),c=Object.keys(i);if(n.length!==c.length)return!1;for(const h of n)if(!(h in i)||!H.objectsDeepEqual(t[h],i[h]))return!1;return!0}return!1}}function Ys(g,t){t.anchorPoint&&(g.anchorPoint=t.anchorPoint),t.zPosition!==void 0&&(g.zPosition=t.zPosition)}function Js(g,t){t.text!==void 0&&(g.text=t.text),t.fontName!==void 0&&(g.fontName=t.fontName),t.fontColor&&(g.fontColor=t.fontColor),t.fontSize!==void 0&&(g.fontSize=t.fontSize),t.interpolation&&(g.interpolation=t.interpolation),t.localize!==void 0&&(g.localize=t.localize)}function Ne(g,t){g.isDrawable&&Ys(g,t),g.isText&&Js(g,t)}class ae{constructor(t={}){this.type=lt.Node,this.isDrawable=!1,this.isShape=!1,this.isText=!1,this._suppressEvents=!1,this._position={x:0,y:0},this._scale=1,this._alpha=1,this._zRotation=0,this._isUserInteractionEnabled=!1,this._draggable=!1,this._hidden=!1,this.layout={},this.children=new Array,this.absolutePosition={x:0,y:0},this._size={width:0,height:0},this.absoluteScale=1,this.absoluteAlpha=1,this.absoluteAlphaChange=0,this.actions=new Array,this.eventListeners=new Array,this.uuid=Ue.generate(),this.needsInitialization=!0,this.userData={},this.loopMessages=new Set,this.nodeEvents=new Array,this.pressed=!1,this.withinHitArea=!1,this.pressedAndWithinHitArea=!1,this.pressedInitialPointerOffset={x:NaN,y:NaN},this.draggingLastPointerOffset={x:NaN,y:NaN},this.dragging=!1,this.toString=()=>{let i=this.type.toString();return this.type==lt.Composite&&(i=this.compositeType),this.name!==this.uuid?`${this.name} (${i}, ${this.uuid})`:`${i} (${this.uuid})`},t.suppressEvents!==void 0&&(this.suppressEvents=t.suppressEvents),this.constructionTimeStamp=Number.isNaN(m2c2Globals?.now)||m2c2Globals?.now===void 0?Gt.now():m2c2Globals.now,this.constructionIso8601TimeStamp=new Date().toISOString(),this.constructionSequence=m2c2Globals.eventSequence,this.options=t,t.uuid!==void 0&&(this.uuid=t.uuid),t.name===void 0?this.name=this.uuid:this.name=t.name,t.position!==void 0&&(this.position=t.position),t.scale!==void 0&&(this.scale=t.scale),t.alpha!==void 0&&(this.alpha=t.alpha),t.zRotation!==void 0&&(this.zRotation=t.zRotation),t.isUserInteractionEnabled!==void 0&&(this.isUserInteractionEnabled=t.isUserInteractionEnabled),t.draggable!==void 0&&(this.draggable=t.draggable),t.hidden!==void 0&&(this.hidden=t.hidden),t.layout!==void 0&&(this.layout=t.layout)}initialize(){throw new Error("initialize() called in abstract base class Node.")}get completeNodeOptions(){throw new Error("get completeNodeOptions() called in abstract base class Node.")}saveNodeNewEvent(){if(this.suppressEvents)return;const t={type:j.NodeNew,target:this,nodeType:this.type,compositeType:this.type===lt.Composite?this.compositeType:void 0,timestamp:this.constructionTimeStamp,iso8601Timestamp:this.constructionIso8601TimeStamp,nodeOptions:this.completeNodeOptions,sequence:this.constructionSequence};this.saveEvent(t)}savePropertyChangeEvent(t,i){if(this.suppressEvents)return;const n={type:j.NodePropertyChange,target:this,uuid:this.uuid,property:t,value:i,...Y.createFrameUpdateTimestamps()};this.saveEvent(n)}saveEvent(t){t.sequence===void 0&&(t.sequence=m2c2Globals.eventSequence);try{this.game.eventStore.addEvent(t)}catch{this.nodeEvents.push(t)}}get game(){const t=i=>{if(i.parent)return i.parent.type===lt.Scene?i.parent:t(i.parent);throw new Error(`Node ${this} has not been added to a scene.`)};return t(this).game}isPartOfGame(){if(this.type===lt.Scene&&this._game===void 0)return!1;if(this.type===lt.Scene&&this._game!==void 0)return!0;const t=i=>{if(i.parent)return i.parent.type===lt.Scene?i.parent:t(i.parent)};return t(this)?._game!==void 0}addChild(t){const i=this.suppressEvents||t.suppressEvents;if(t===this)throw new Error(`Cannot add node ${t.toString()} as a child to itself.`);if(t.type==lt.Scene)throw new Error(`Cannot add scene ${t.toString()} as a child to node ${this.toString()}. A scene cannot be the child of a node. A scene can only be added to a game object.`);if(this.children.filter(h=>h!==t).map(h=>h.name).includes(t.name))throw new Error(`Cannot add child node ${t.toString()} to parent node ${this.toString()}. A child with name "${t.name}" already exists on this parent.`);let n=new Array;if(this.isPartOfGame())n=this.game.nodes.filter(h=>h.children.includes(t));else{const h=this.descendants;h.includes(t)&&(n=h.filter(C=>C.children.includes(t)).map(C=>C.parent??void 0))}if(n.length===0){t.parent=this,this.children.push(t);const h={type:"NodeAddChild",target:this,uuid:this.uuid,childUuid:t.uuid,...Y.createFrameUpdateTimestamps()};i||this.saveEvent(h),this.saveChildEvents(t);return}const c=n.find(Boolean);throw c===this?new Error(`Cannot add child node ${t.toString()} to parent node ${this.toString()}. This child already exists on this parent. The child cannot be added again.`):new Error(`Cannot add child node ${t.toString()} to parent node ${this.toString()}. This child already exists on other parent node: ${c?.toString()}}. Remove the child from the other parent first.`)}saveChildEvents(t){t.nodeEvents.forEach(i=>{this.saveEvent(i)}),t.nodeEvents.length=0;for(const i of t.children)this.saveChildEvents(i)}removeAllChildren(){this.children.forEach(t=>this.removeChild(t))}removeChild(t){const i=this.suppressEvents||t.suppressEvents;if(this.children.includes(t))t.parent=void 0,this.children=this.children.filter(c=>c!==t);else throw new Error(`cannot remove node ${t} from parent ${this} because the node is not currently a child of the parent`);const n={type:"NodeRemoveChild",target:this,uuid:this.uuid,childUuid:t.uuid,...Y.createFrameUpdateTimestamps()};i||this.saveEvent(n)}removeChildren(t){t.forEach(i=>{if(!this.children.includes(i))throw new Error(`cannot remove node ${i} from parent ${this} because the node is not currently a child of the parent`);this.removeChild(i)})}descendant(t){const i=this.descendants.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`descendant with name ${t} not found on parent ${this.toString()}`);return i}get descendants(){function t(n,c){c.push(n),n.children.forEach(h=>t(h,c))}const i=new Array;return this.children.forEach(n=>t(n,i)),i}get ancestors(){function t(n,c){return n.type==lt.Scene||!n.parent?c:(c.push(n.parent),t(n.parent,c))}const i=new Array;return t(this,i)}involvedInActionAffectingAppearance(){return this.ancestors.concat(this).flatMap(n=>n.actions).some(n=>n.running&&(n.type===gt.Move||n.type===gt.Scale))}involvedInSceneTransition(){let t;return this.type===lt.Scene?t=this:t=this.parentSceneAsNode,t._transitioning}onTapDown(t,i){this.addEventListener(j.TapDown,t,i)}onTapUp(t,i){this.addEventListener(j.TapUp,t,i)}onTapUpAny(t,i){this.addEventListener(j.TapUpAny,t,i)}onTapLeave(t,i){this.addEventListener(j.TapLeave,t,i)}onPointerDown(t,i){this.addEventListener(j.PointerDown,t,i)}onPointerUp(t,i){this.addEventListener(j.PointerUp,t,i)}onPointerMove(t,i){this.addEventListener(j.PointerMove,t,i)}onPointerLeave(t,i){this.addEventListener(j.PointerLeave,t,i)}onDragStart(t,i){this.addEventListener(j.DragStart,t,i)}onDrag(t,i){this.addEventListener(j.Drag,t,i)}onDragEnd(t,i){this.addEventListener(j.DragEnd,t,i)}addEventListener(t,i,n){const c={type:t,nodeUuid:this.uuid,callback:i};n?.replaceExisting&&(this.eventListeners=this.eventListeners.filter(h=>!(h.nodeUuid===c.nodeUuid&&h.type===c.type))),this.eventListeners.push(c)}parseLayoutConstraints(t,i){const n=new Array;return Object.values(Bt).forEach(h=>{if(t[h]!==void 0){let C,T="";if(typeof t[h]=="object")C=t[h];else{const $=t[h];C=i.filter(it=>it.name===$||it.uuid===$).find(Boolean),C||(C=this.game.materializedNodes.filter(it=>it.name===$||it.uuid===$).find(Boolean)),T=`. sibling node named "${$}" has not been added to the game object`}if(C===void 0)throw new Error("could not find sibling node for constraint"+T);const B=new An(h,C);n.push(B)}}),n}calculateYFromConstraint(t,i,n,c){let h=t.alterNode.absolutePosition.y;return t.alterNodeMinimum?t.alterNode.type!==lt.Scene&&(h=h-t.alterNode.size.height*.5*c):t.alterNode.type!==lt.Scene?h=h+t.alterNode.size.height*.5*c:h=h+t.alterNode.size.height*c,t.focalNodeMinimum?(h=h+this.size.height*.5*c,h=h+i*c):(h=h-this.size.height*.5*c,h=h-n*c),h}calculateXFromConstraint(t,i,n,c){let h=t.alterNode.absolutePosition.x;return t.alterNodeMinimum?t.alterNode.type!==lt.Scene&&(h=h-t.alterNode.size.width*.5*c):t.alterNode.type!==lt.Scene?h=h+t.alterNode.size.width*.5*c:h=h+t.alterNode.size.width*c,t.focalNodeMinimum?(h=h+this.size.width*.5*c,h=h+i*c):(h=h-this.size.width*.5*c,h=h-n*c),h}calculateAbsoluteAlpha(t,i){const n=i.reduce((c,h)=>c*h.alpha,1);return t*n}update(){if(this.needsInitialization&&this.initialize(),this.absoluteAlphaChange=this.calculateAbsoluteAlpha(this.alpha,this.ancestors)-this.absoluteAlpha,this.absoluteAlpha+=this.absoluteAlphaChange,this.parent===void 0)this.absolutePosition.x=this.position.x*this.scale,this.absolutePosition.y=this.position.y*this.scale,this.absoluteScale=this.scale;else if(this.absoluteScale=this.parent.absoluteScale*this.scale,this.layout?.constraints===void 0)this.absolutePosition.x=this.parent.absolutePosition.x+this.position.x*this.parent.absoluteScale,this.absolutePosition.y=this.parent.absolutePosition.y+this.position.y*this.parent.absoluteScale;else{const c=this.layout?.constraints?.horizontalBias??.5,h=this.layout?.constraints?.verticalBias??.5,C=this.layout?.marginTop??0,T=this.layout?.marginBottom??0,B=this.layout?.marginStart??0,$=this.layout?.marginEnd??0,it=this.parseLayoutConstraints(this.layout?.constraints,this.parentSceneAsNode.descendants),ct=this.parent.absoluteScale,ut=it.filter(wt=>wt.verticalConstraint).map(wt=>this.calculateYFromConstraint(wt,C,T,ct));ut.length===0||(ut.length===1?this.absolutePosition.y=ut[0]:ut.length===2&&(this.absolutePosition.y=Math.min(ut[0],ut[1])+h*Math.abs(ut[0]-ut[1])));const bt=it.filter(wt=>!wt.verticalConstraint).map(wt=>this.calculateXFromConstraint(wt,B,$,ct));bt.length===0||(bt.length===1?this.absolutePosition.x=bt[0]:bt.length===2&&(this.absolutePosition.x=Math.min(bt[0],bt[1])+c*Math.abs(bt[0]-bt[1])))}this.actions.forEach(c=>q.evaluateAction(c,this,m2c2Globals.now,m2c2Globals.deltaTime));function t(c,h){const C=new Array;return h===void 0||Object.values(Bt).forEach(B=>{if(h[B]!==void 0){let $,it="";if(typeof h[B]=="object")$=h[B];else{const ct=h[B];let ut;c.type===lt.Scene?ut=c.descendants:ut=c.parentSceneAsNode.descendants,$=ut.filter(bt=>bt.name===ct||bt.uuid===ct).find(Boolean),$===void 0&&($=c.game.materializedNodes.filter(bt=>bt.name===ct||bt.uuid===ct).find(Boolean)),$===void 0&&(it=`. sibling node named "${ct}" has not been added to the game object`)}if($===void 0)throw new Error("error getting uuid of sibling constraint"+it);$!==c&&C.push($.uuid)}}),C}const i=new Map;this.children.forEach(c=>{i.set(c.uuid,t(this,c.layout?.constraints))});const n=this.findTopologicalSort(i);if(n.length>0){const c=n.reverse(),h=new Array;c.forEach(C=>{const T=this.children.filter(B=>B.uuid===C).find(Boolean);if(T===void 0)throw new Error("error in dag topological sort");h.push(T)}),h.forEach(C=>C.update())}else this.children.forEach(c=>c.update())}drawChildren(t){this.children.filter(i=>!i.hidden&&i.isDrawable).map(i=>i).sort((i,n)=>i.zPosition-n.zPosition).forEach(i=>i.draw(t))}run(t,i){this.actions.push(t.initialize(i))}removeAction(t){this.actions=this.actions.filter(i=>i.key!==t)}removeAllActions(){for(;this.actions.length;)this.actions.pop()}getNodeOptions(){return{name:this.name,position:this.position,scale:this.scale,alpha:this.alpha,zRotation:this.zRotation,isUserInteractionEnabled:this.isUserInteractionEnabled,draggable:this.draggable,hidden:this.hidden,layout:this.layout,uuid:this.uuid}}getDrawableOptions(){if(!this.isDrawable)throw new Error("getDrawableOptions() called object that is not IDrawable");return{anchorPoint:this.anchorPoint,zPosition:this.zPosition}}getTextOptions(){if(!this.isText)throw new Error("getTextOptions() called object that is not IText");return{text:this.text,fontName:this.fontName,fontColor:this.fontColor,fontSize:this.fontSize}}get canvasKit(){return this.game.canvasKit}get parentSceneAsNode(){if(this.type===lt.Scene)throw new Error(`Node ${this} is a scene and cannot have a parent scene`);if(this.parent&&this.parent.type===lt.Scene)return this.parent;if(this.parent)return this.parent.parentSceneAsNode;throw new Error(`Node ${this} has not been added to a scene`)}get size(){const t=this;return{get height(){return t._size.height},set height(i){H.value(t._size.height,i)||(t._size.height=i,t.savePropertyChangeEvent("size",t.size))},get width(){return t._size.width},set width(i){H.value(t._size.width,i)||(t._size.width=i,t.savePropertyChangeEvent("size",t.size))}}}set size(t){H.value(this._size.width,t.width)||(this._size=t,this.savePropertyChangeEvent("size",this.size))}get position(){const t=this;return{get x(){return t._position.x},set x(i){H.value(t._position.x,i)||(t._position.x=i,t.savePropertyChangeEvent("position",t.position))},get y(){return t._position.y},set y(i){H.value(t._position.y,i)||(t._position.y=i,t.savePropertyChangeEvent("position",t.position))}}}set position(t){H.value(this._position,t)||(this._position=t,this.savePropertyChangeEvent("position",this.position))}get zRotation(){return this._zRotation}set zRotation(t){H.value(this._zRotation,t)||(this._zRotation=t,this.savePropertyChangeEvent("zRotation",t))}get scale(){return this._scale}set scale(t){H.value(this._scale,t)||(this._scale=t,this.savePropertyChangeEvent("scale",t))}get alpha(){return this._alpha}set alpha(t){H.value(this._alpha,t)||(this._alpha=t,this.savePropertyChangeEvent("alpha",t))}get isUserInteractionEnabled(){return this._isUserInteractionEnabled}set isUserInteractionEnabled(t){H.value(this._isUserInteractionEnabled,t)||(this._isUserInteractionEnabled=t,this.savePropertyChangeEvent("isUserInteractionEnabled",t))}get hidden(){return this._hidden}set hidden(t){H.value(this._hidden,t)||(this._hidden=t,this.savePropertyChangeEvent("hidden",t))}get draggable(){return this._draggable}set draggable(t){H.value(this._draggable,t)||(this._draggable=t,this.savePropertyChangeEvent("draggable",t))}get suppressEvents(){return this._suppressEvents}set suppressEvents(t){this._suppressEvents=t}findTopologicalSort(t){const i=[],n=new Map;t.forEach((h,C)=>{n.has(C)||n.set(C,0),h.forEach(T=>{if(n.has(T)){const B=n.get(T);if(B===void 0)throw new Error(`Could not find inDegree for edge ${T}`);n.set(T,B+1)}else n.set(T,1)})});const c=[];for(n.forEach((h,C)=>{h==0&&c.push(C)});c.length>0;){const h=c.shift();if(h===void 0)throw"current vertex is undefined";i.push(h),t.has(h)&&t.get(h)?.forEach(C=>{const T=n.get(C);if(T===void 0)throw new Error(`Could not find inDegree for edge ${C}`);if(n.has(C)&&T>0){const B=T-1;n.set(C,B),B==0&&c.push(C)}})}return i}}class Xs extends ae{constructor(t={}){super(t),this.type=lt.Composite,this.compositeType="<compositeType>",this.isDrawable=!0,this._anchorPoint={x:.5,y:.5},this._zPosition=0,Ne(this,t)}initialize(){}get anchorPoint(){const t=this;return{get x(){return t._anchorPoint.x},set x(i){H.value(t._anchorPoint.x,i)||(t._anchorPoint.x=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))},get y(){return t._anchorPoint.y},set y(i){H.value(t._anchorPoint.y,i)||(t._anchorPoint.y=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))}}}set anchorPoint(t){H.value(this._anchorPoint,t)||(this._anchorPoint=t,this.savePropertyChangeEvent("anchorPoint",this.anchorPoint))}get zPosition(){return this._zPosition}set zPosition(t){H.value(this._zPosition,t)||(this._zPosition=t,this.savePropertyChangeEvent("zPosition",t))}dispose(){}update(){super.update()}draw(t){super.drawChildren(t)}handleCompositeEvent(t){}}var Cn=(g=>(g[g.MatchConstraint=0]="MatchConstraint",g))(Cn||{});const Qt={Deferred:"Deferred",Loading:"Loading",Ready:"Ready",Error:"Error"};class lr{constructor(t,i){this.images={},this.game=t,this.baseUrls=i,this.canvasKit=t.canvasKit}initializeImages(t){return this.loadImages(t??[])}async loadImages(t){if(t.length===0)return;this.checkImageNamesForDuplicates(t);const i=t.map(n=>{let c=n.url;n.url&&!Y.urlHasScheme(n.url)&&(c=Y.getUrlFromManifest(this.game,`${this.baseUrls.assets}/${n.url}`)),n.dataUrl&&(c=n.dataUrl);const h={imageName:n.imageName,url:c,originalUrl:c,isFallback:!1,localize:n.localize??!1,svgString:n.svgString,canvaskitImage:void 0,width:n.width,height:n.height,status:n.lazy?Qt.Deferred:Qt.Loading};return h.localize&&this.configureImageLocalization(h),this.images[n.imageName]=h,h.status===Qt.Loading?this.renderM2Image(h):Promise.resolve()});await Promise.all(i)}configureImageLocalization(t){t.fallbackLocalizationUrls=new Array,t.originalUrl&&this.game.i18n?.locale&&(t.status="Deferred",this.game.i18n?.fallbackLocale&&this.game.i18n?.fallbackLocale!==this.game.i18n?.baseLocale&&t.fallbackLocalizationUrls.push(this.localizeImageUrl(t.originalUrl,this.game.i18n.fallbackLocale)),this.game.i18n?.locale===this.game.i18n?.baseLocale?t.url=t.originalUrl:t.url=this.localizeImageUrl(t.originalUrl,this.game.i18n.locale),t.url!==t.originalUrl&&t.fallbackLocalizationUrls.push(t.originalUrl),this.game.i18n.missingLocalizationColor&&!this.missingLocalizationImagePaint&&(this.missingLocalizationImagePaint=xt.makePaint(this.canvasKit,this.game.i18n.missingLocalizationColor,this.canvasKit.PaintStyle.Stroke,!0),this.missingLocalizationImagePaint.setStrokeWidth(4)))}localizeImageUrl(t,i){const n=t.lastIndexOf(".");if(n===-1)throw new Error("URL does not have an extension");return t.slice(0,n)+`.${i}`+t.slice(n)}reinitializeLocalizedImages(){Object.keys(this.game.imageManager.images).forEach(i=>{const n=this.game.imageManager.images[i];n.localize&&this.game.imageManager.configureImageLocalization(n)}),this.game.nodes.filter(i=>i.type===lt.Sprite).forEach(i=>{i.needsInitialization=!0})}checkImageNamesForDuplicates(t){const n=(c=>c.filter((h,C)=>c.indexOf(h)!=C))(t.map(c=>c.imageName));if(n.length>0)throw new Error(`image names must be unique. these image names are duplicated within a game ${this.game.id}: `+n.join(", "))}prepareDeferredImage(t){return t.status=Qt.Loading,t.isFallback=!1,this.renderM2Image(t).catch(async()=>{for(t.isFallback=!0;t.fallbackLocalizationUrls?.length;){t.url=t.fallbackLocalizationUrls.shift();try{await this.renderM2Image(t)}catch(i){if(t.fallbackLocalizationUrls.length===0)throw i instanceof Error?i:new Error(`prepareDeferredImage(): unable to render image named ${t.imageName}. image source was ${t.svgString?"svgString":`url: ${t.url}`}`)}}})}renderM2Image(t){const i=document.createElement("img"),n=c=>{if(!this.scratchCanvas||!this.ctx||!this.scale)throw new Error("image manager not set up");this.scratchCanvas.width=t.width*this.scale,this.scratchCanvas.height=t.height*this.scale,this.ctx.scale(this.scale,this.scale),this.ctx.clearRect(0,0,t.width,t.height),this.ctx.drawImage(i,0,0,t.width,t.height),this.scratchCanvas.toBlob(h=>{if(!h)throw new Error(`renderM2Image(): blob is undefined for ${t.imageName}`);h.arrayBuffer().then(C=>{const T=this.canvasKit.MakeImageFromEncoded(C);if(!T)throw new Error(`could not create image with name "${t.imageName}."`);console.log(`image loaded. name: ${t.imageName}, w: ${t.width}, h: ${t.height}`),this.images[t.imageName].canvaskitImage=T,this.images[t.imageName].status=Qt.Ready,this.game.nodes.filter($=>$.type==="Sprite").forEach($=>{$.imageName===t.imageName&&($.needsInitialization=!0)}),c()})})};return new Promise((c,h)=>{if(i.width=t.width,i.height=t.height,i.crossOrigin="Anonymous",i.onerror=()=>{h(new Error(`unable to render image named ${t.imageName}. image source was ${t.svgString?"svgString":`url: ${t.url}`}`))},i.onload=()=>{n(c)},!t.svgString&&!t.url)throw new Error(`no svgString or url provided for image named ${t.imageName}`);if(t.svgString&&t.url)throw new Error(`provide svgString or url. both were provided for image named ${t.imageName}`);if(t.svgString){i.src="data:image/svg+xml,"+encodeURIComponent(t.svgString);const C={type:j.BrowserImageDataReady,target:this,imageName:t.imageName,width:t.width,height:t.height,svgString:t.svgString,...Y.createFrameUpdateTimestamps()};this.game.eventStore.addEvent(C)}else t.url&&fetch(t.url).then(C=>C.arrayBuffer()).then(C=>{this.arrayBufferToBase64Async(C).then(T=>{const B=this.inferImageSubtypeFromUrl(t.url);i.src="data:image/"+B+";base64,"+T;const $={type:j.BrowserImageDataReady,target:this,imageName:t.imageName,width:t.width,height:t.height,dataUrl:i.src,...Y.createFrameUpdateTimestamps()};this.game.eventStore.addEvent($)})})})}arrayBufferToBase64Async(t){return new Promise((i,n)=>{const c=new FileReader;c.onload=()=>{i(c.result?.toString().split(",")[1]??"")},c.onerror=n,c.readAsDataURL(new Blob([t]))})}inferImageSubtypeFromUrl(t){if(t?.startsWith("data:image/"))return t.split(";")[0].split("/")[1];let i="jpeg";return t?.includes(".")&&(i=t.split(".").pop()?.toLowerCase()??"jpeg",i===""&&(i="jpeg")),i==="svg"&&(i="svg+xml"),i}getImage(t){return this.images[t]}addImage(t){this.images[t.imageName]=t}get scratchCanvas(){if(!this._scratchCanvas){this._scratchCanvas=document.createElement("canvas"),this._scratchCanvas.id=`m2c2kit-scratch-canvas-${this.game.id}-${Math.floor(Math.random()*1e6)}`,this._scratchCanvas.hidden=!0,document.body.appendChild(this._scratchCanvas);const t=this._scratchCanvas.getContext("2d");if(t===null)throw new Error("could not get 2d canvas context from scratch canvas");this.ctx=t,this.scale=window.devicePixelRatio}return this._scratchCanvas}removeScratchCanvas(){this.ctx=void 0,this._scratchCanvas?.remove()}}class Ni{constructor(t,i){this.locale="",this.fallbackLocale="en-US",this.baseLocale="en-US",this.game=t,this._translation=this.mergeAdditionalTranslation(i.translation,i.additionalTranslation)??{},this.translation.configuration?.baseLocale&&(this.baseLocale=this.translation.configuration.baseLocale),i.missingLocalizationColor&&(this.missingLocalizationColor=i.missingLocalizationColor),i.locale&&(this.locale=i.locale),i.fallbackLocale&&(this.fallbackLocale=i.fallbackLocale)}async initialize(){await this.configureInitialLocale()}async configureInitialLocale(){if(this.game.hasDataStores()){const t=await this.game.storeGetItem("locale"),i=await this.game.storeGetItem("fallbackLocale");if(typeof t=="string"&&typeof i=="string"){this.locale=t,this.fallbackLocale=i;return}}if(this.locale?.toLowerCase()==="auto"){const t=this.getEnvironmentLocale();t?this.localeTranslationAvailable(t)?(this.locale=t,this.localeTranslationAvailable(this.fallbackLocale)||(this.fallbackLocale=this.baseLocale)):this.fallbackLocale&&this.localeTranslationAvailable(this.fallbackLocale)?(console.warn(`auto locale requested, but detected locale ${t} does not have translation. Setting locale to fallback locale ${this.fallbackLocale}`),this.locale=this.fallbackLocale,this.fallbackLocale=this.baseLocale):(console.warn(`auto locale requested, but detected locale ${t} does not have translation, and fallback locale does not have translation or was not specified (fallback locale is ${this.fallbackLocale}). Setting locale to base locale ${this.baseLocale}.`),this.locale=this.baseLocale,this.fallbackLocale=this.baseLocale):this.fallbackLocale&&this.localeTranslationAvailable(this.fallbackLocale)?(console.warn(`auto locale requested, but environment cannot detect locale. Setting locale to fallback locale ${this.fallbackLocale}`),this.locale=this.fallbackLocale,this.fallbackLocale=this.baseLocale):(console.warn(`auto locale requested, but environment cannot detect locale, and fallback locale does not have translation or was not specified (fallback locale is ${this.fallbackLocale}). Setting locale to base locale ${this.baseLocale}.`),this.locale=this.baseLocale,this.fallbackLocale=this.baseLocale)}else this.locale=this.locale??"",this.fallbackLocale||(this.fallbackLocale=this.baseLocale)}localeTranslationAvailable(t){return this.translation[t]!==void 0||t===this.baseLocale}switchToLocale(t){this.locale=t,this.game.nodes.filter(i=>i.isText).forEach(i=>i.needsInitialization=!0),this.game.imageManager.reinitializeLocalizedImages(),this.game&&this.game.hasDataStores()&&(this.game.storeSetItem("locale",this.locale),this.game.storeSetItem("fallbackLocale",this.fallbackLocale))}getTextLocalization(t,i){let n="",c=!1,h=this.tf(t,i);return h?.text!==void 0?n=h.text:(h=this.tf(t,{useFallbackLocale:!0,...i}),h===void 0||h.text===void 0?n=t:n=h.text,c=!0),{text:n,fontSize:h?.fontSize,fontName:h?.fontName,fontNames:h?.fontNames,isFallbackOrMissingTranslation:c}}t(t,i){const{useFallbackLocale:n,...c}=i??{};if(n!==!0){const C=this.translation[this.locale]?.[t];return this.isStringOrTextWithFontCustomization(C)?this.insertInterpolations(this.getKeyText(C),c):void 0}const h=this.translation[this.fallbackLocale]?.[t];if(this.isStringOrTextWithFontCustomization(h))return this.insertInterpolations(this.getKeyText(h),c)}tf(t,i){const{useFallbackLocale:n,...c}=i??{};if(n!==!0){const C=this.translation[this.locale]?.[t];if(this.isStringOrTextWithFontCustomization(C)){const T=this.getKeyTextAndFont(C,this.locale);return T.text&&(T.text=this.insertInterpolations(T.text,c)),T}return}const h=this.translation[this.fallbackLocale]?.[t];if(this.isStringOrTextWithFontCustomization(h)){const C=this.getKeyTextAndFont(h,this.fallbackLocale);return C.text&&(C.text=this.insertInterpolations(C.text,c)),C}}getKeyText(t){return this.isTextWithFontCustomization(t)?t.text:t}getKeyTextAndFont(t,i){let n,c=new Array;this.isString(this.translation[i]?.fontName)?c.push(this.translation[i].fontName):this.isStringArray(this.translation[i]?.fontName)?c.push(...this.translation[i].fontName):c.push("default");let h;switch(this.isTextWithFontCustomization(t)?(h=t.text,n=t.fontSize,this.isString(t.additionalFontName)&&c.push(t.additionalFontName),this.isStringArray(t.additionalFontName)&&c.push(...t.additionalFontName),t.overrideFontName&&(c.length=0,this.isString(t.overrideFontName)&&c.push(t.overrideFontName),this.isStringArray(t.overrideFontName)&&c.push(...t.overrideFontName))):h=t,c=c.filter(C=>C!=="default"),c.length){case 0:return{text:h,fontSize:n};case 1:return{text:h,fontSize:n,fontName:c[0]};default:return{text:h,fontSize:n,fontNames:c}}}insertInterpolations(t,i){return i?t.replace(/\{\{(.*?)\}\}/g,(n,c)=>{if(Object.prototype.hasOwnProperty.call(i,c))return i[c];throw new Error(`insertInterpolations(): placeholder "${c}" not found. Text was ${t}, provided interpolation was ${JSON.stringify(i)}`)}):t}get translation(){return this._translation}set translation(t){this._translation=t}getEnvironmentLocale(){return(navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language)??""}mergeAdditionalTranslation(t,i){if(!t&&!i)return;if(!i)return t;if(!t)return i;const n={},c=new Array;for(const h in t)c.push(h),n[h]={...t[h],...i[h]};for(const h in i)c.includes(h)||(n[h]=i[h]);return n}static makeLocalizationParameters(){return JSON.parse(JSON.stringify({locale:{type:["string","null"],default:null,description:'Locale to use for localization, or "auto" to request from the environment.'},fallback_locale:{type:["string","null"],default:null,description:'Locale to use if requested locale translation is not available, or if "auto" locale was requested and environment cannot provide a locale.'},missing_localization_color:{type:["array","null"],default:null,description:"Font color for strings that are missing translation and outline color for images that are missing localization, [r,g,b,a].",items:{type:"number"}},translation:{type:["object","null"],default:null,description:"Additional translation for localization."}}))}isTextWithFontCustomization(t){return t?.text!==void 0}isStringOrTextWithFontCustomization(t){return typeof t=="string"||this.isTextWithFontCustomization(t)}isStringArray(t){return Array.isArray(t)&&t.every(i=>typeof i=="string")}isString(t){return typeof t=="string"}}const de={Disabled:"Disabled",Record:"Record",Replay:"Replay"};class En{constructor(){this.events=new Array,this.replayBeginTimestamp=NaN,this.firstTimestamp=NaN,this.replayThoughSequence=Number.MAX_VALUE,this.serializedEventsBeforeReplay="",this.mode=de.Disabled}serializeEvent(t){const i=t.target;if(t.type===j.NodeNew&&t.nodeOptions?.layout?.constraints!==void 0){const c=t.nodeOptions?.layout?.constraints,h={};for(const T in c){if(T==="horizontalBias"||T==="verticalBias"){h[T]=c[T];continue}const B=c[T];B instanceof ae&&(h[T]=B.uuid)}t.target=i.uuid,t.nodeOptions.layout.constraints=h;const C=JSON.stringify(t);return t.target=i,t.nodeOptions.layout.constraints=c,C}if(i instanceof ae){t.target=i.uuid;const c=JSON.stringify(t);return t.target=i,c}if(i instanceof Element){t.target=i.nodeName;const c=JSON.stringify(t);return t.target=i,c}if(i instanceof lr){t.target="ImageManager";const c=JSON.stringify(t);return t.target=i,c}if(i instanceof Ni){t.target="I18n";const c=JSON.stringify(t);return t.target=i,c}t.target="object";const n=JSON.stringify(t);return t.target=i,n}addEvent(t){if(this.mode===de.Record){t.sequence===void 0&&(t.sequence=m2c2Globals.eventSequence);const i=this.serializeEvent(t);this.events.push(JSON.parse(i))}}addEvents(t){t.forEach(i=>{this.addEvent(i)})}clearEvents(){this.events=[]}record(){this.mode=de.Record}replay(t){if(t&&(this.events=t),this.events.length===0)if(this.serializedEventsBeforeReplay!=="")this.events=JSON.parse(this.serializedEventsBeforeReplay);else{console.log("Event store has no events to replay.");return}this.mode=de.Replay,this.replayBeginTimestamp=Gt.now(),this.sortEventStore(this.events),this.serializedEventsBeforeReplay===""&&(this.serializedEventsBeforeReplay=JSON.stringify(this.events)),this.firstTimestamp=this.events[0].timestamp,console.log(`Event store has ${this.events.length} events. Replay beginning.`);const i=document.getElementById("sequence-number");i&&(this.replayThoughSequence=parseInt(i.value))}getEvents(){return this.sortEventStore(this.events),this.events}dequeueEvents(t){const i=new Array,n=t-this.replayBeginTimestamp+this.firstTimestamp;for(;this.events.length>0&&this.events[0].timestamp<=n;){const c=this.events.shift();if(!c)throw new Error("EventStore.dequeueEvents(): undefined event");c.sequence!==void 0&&c.sequence>this.replayThoughSequence||i.push(c)}return i}get eventQueueLength(){return this.events.length}sortEventStore(t){t.sort((i,n)=>{if(i.sequence===void 0||n.sequence===void 0)throw new Error("EventStore.sortEventStore(): undefined sequence");return i.sequence!==n.sequence?i.sequence-n.sequence:0})}}var $e=(g=>(g[g.Center=0]="Center",g[g.Left=1]="Left",g[g.Right=2]="Right",g))($e||{});const Zt={Deferred:"Deferred",Loading:"Loading",Ready:"Ready",Error:"Error"};class Ii extends ae{constructor(t={}){super(t),this.type=lt.Label,this.isDrawable=!0,this.isText=!0,this._anchorPoint={x:.5,y:.5},this._zPosition=0,this._text="",this._fontColor=X.DEFAULT_FONT_COLOR,this._fontSize=X.DEFAULT_FONT_SIZE,this._interpolation={},this._horizontalAlignmentMode=$e.Center,this._localize=!0,this.localizedFontNames=[],Ne(this,t),t.horizontalAlignmentMode&&(this.horizontalAlignmentMode=t.horizontalAlignmentMode),t.preferredMaxLayoutWidth!==void 0&&(this.preferredMaxLayoutWidth=t.preferredMaxLayoutWidth),t.backgroundColor&&(this.backgroundColor=t.backgroundColor),t.fontNames&&(this.fontNames=t.fontNames),this.saveNodeNewEvent()}get completeNodeOptions(){return{...this.options,...this.getNodeOptions(),...this.getDrawableOptions(),...this.getTextOptions(),horizontalAlignmentMode:this.horizontalAlignmentMode,preferredMaxLayoutWidth:this.preferredMaxLayoutWidth,backgroundColor:this.backgroundColor,fontNames:this.fontNames}}initialize(){let t=this.canvasKit.TextAlign.Center;switch(this.horizontalAlignmentMode){case $e.Center:t=this.canvasKit.TextAlign.Center;break;case $e.Left:t=this.canvasKit.TextAlign.Left;break;case $e.Right:t=this.canvasKit.TextAlign.Right;break;default:throw new Error("unknown horizontalAlignmentMode")}this.text||(this.text="");let i=this.canvasKit.Color(this.fontColor[0],this.fontColor[1],this.fontColor[2],this.fontColor[3]),n;const c=this.game.i18n;if(c&&this.localize!==!1){const $=c.getTextLocalization(this.text,this.interpolation);n=$.text,this.localizedFontSize=$.fontSize,this.localizedFontName=$.fontName,this.localizedFontNames=$.fontNames??[],$.isFallbackOrMissingTranslation&&c.missingLocalizationColor&&(i=this.canvasKit.Color(c.missingLocalizationColor[0],c.missingLocalizationColor[1],c.missingLocalizationColor[2],c.missingLocalizationColor[3]))}else n=this.text;if(this.fontName&&this.fontNames)throw new Error("cannot specify both fontName and fontNames");const h=this.game.fontManager,C=this.getRequiredLabelFonts(h);if(C.forEach($=>{if($.status===Zt.Deferred){h.prepareDeferredFont($);return}}),!C.every($=>$.status===Zt.Ready))return;this.paraStyle=new this.canvasKit.ParagraphStyle({textStyle:{},textAlign:t}),this.builder&&this.builder.delete(),this.builder=this.canvasKit.ParagraphBuilder.MakeFromFontProvider(this.paraStyle,h.provider),this._backgroundPaint||(this._backgroundPaint=new this.canvasKit.Paint),this._fontPaint||(this._fontPaint=new this.canvasKit.Paint),this.fontPaint.setColor(i),this.fontPaint.setAlphaf(this.absoluteAlpha),this.backgroundColor?(this.backgroundPaint.setColor(this.backgroundColor),this.backgroundPaint.setAlphaf(this.absoluteAlpha)):this.backgroundPaint.setColor(this.canvasKit.Color(0,0,0,0)),this.builder.pushPaintStyle({fontFamilies:C.map($=>$.fontName),fontSize:(this.localizedFontSize??this.fontSize)*m2c2Globals.canvasScale,fontStyle:{weight:this.canvasKit.FontWeight.Normal,width:this.canvasKit.FontWidth.Normal,slant:this.canvasKit.FontSlant.Oblique},decoration:0,decorationThickness:1,decorationStyle:this.canvasKit.DecorationStyle.Solid,heightMultiplier:-1,halfLeading:!1,letterSpacing:0,wordSpacing:0},this.fontPaint,this.backgroundPaint),this.builder.addText(n),this.paragraph&&this.paragraph.delete(),this.paragraph=this.builder.build();const T=this.preferredMaxLayoutWidth??m2c2Globals.canvasCssWidth;let B=T;if(T===0||this.layout.width===0){if(this.parent===void 0)throw new Error("width is set to match parent, but node has no parent");const $=this.layout.marginStart??0,it=this.layout.marginEnd??0;B=this.parent.size.width-($+it)}this.paragraph.layout(B*m2c2Globals.canvasScale),T===0||this.layout.width===0?this.size.width=B:(this.paragraph.layout(Math.ceil(this.paragraph.getLongestLine())),this.size.width=this.paragraph.getMaxWidth()/m2c2Globals.canvasScale),this.size.height=this.paragraph.getHeight()/m2c2Globals.canvasScale,this.needsInitialization=!1}getRequiredLabelFonts(t){let i;if(this.game.i18n&&this.localize!==!1){if(this.localizedFontName)return i=[t.fonts[this.localizedFontName]],i;if(this.localizedFontNames.length>0)return i=this.localizedFontNames.map(n=>t.fonts[n]),i}if(this.fontName===void 0&&this.fontNames===void 0)i=[t.getDefaultFont()];else if(this.fontName!==void 0)i=[t.fonts[this.fontName]];else if(this.fontNames!==void 0&&this.fontNames.length>0)i=this.fontNames.map(n=>t.fonts[n]);else throw new Error("cannot determine required fonts");return i}dispose(){xt.Dispose([this.paragraph,this.builder,this._fontPaint,this._backgroundPaint])}get text(){return this._text}set text(t){H.value(this._text,t)||(this._text=t,this.needsInitialization=!0,this.savePropertyChangeEvent("text",t))}get interpolation(){return this._interpolation}set interpolation(t){H.value(this._interpolation,t)||(this._interpolation=t,Object.freeze(this._interpolation),this.needsInitialization=!0,this.savePropertyChangeEvent("interpolation",t))}get fontName(){return this._fontName}set fontName(t){H.value(this._fontName,t)||(this._fontName=t,this.needsInitialization=!0,this.savePropertyChangeEvent("fontName",t))}get fontNames(){return this._fontNames}set fontNames(t){H.value(this._fontNames,t)||(this._fontNames=t,this.needsInitialization=!0,this.savePropertyChangeEvent("fontNames",t))}get fontColor(){return this._fontColor}set fontColor(t){H.value(this._fontColor,t)||(this._fontColor=t,this.needsInitialization=!0,this.savePropertyChangeEvent("fontColor",t))}get fontSize(){return this._fontSize}set fontSize(t){H.value(this._fontSize,t)||(this._fontSize=t,this.needsInitialization=!0,this.savePropertyChangeEvent("fontSize",t))}get horizontalAlignmentMode(){return this._horizontalAlignmentMode}set horizontalAlignmentMode(t){H.value(this._horizontalAlignmentMode,t)||(this._horizontalAlignmentMode=t,this.needsInitialization=!0,this.savePropertyChangeEvent("horizontalAlignmentMode",t))}get preferredMaxLayoutWidth(){return this._preferredMaxLayoutWidth}set preferredMaxLayoutWidth(t){H.value(this._preferredMaxLayoutWidth,t)||(this._preferredMaxLayoutWidth=t,this.needsInitialization=!0,this.savePropertyChangeEvent("preferredMaxLayoutWidth",t))}get backgroundColor(){return this._backgroundColor}set backgroundColor(t){H.value(this._backgroundColor,t)||(this._backgroundColor=t,this.needsInitialization=!0,this.savePropertyChangeEvent("backgroundColor",t))}get localize(){return this._localize}set localize(t){H.value(this._localize,t)||(this._localize=t,this.needsInitialization=!0,this.savePropertyChangeEvent("localize",t))}get anchorPoint(){const t=this;return{get x(){return t._anchorPoint.x},set x(i){H.value(t._anchorPoint.x,i)||(t._anchorPoint.x=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))},get y(){return t._anchorPoint.y},set y(i){H.value(t._anchorPoint.y,i)||(t._anchorPoint.y=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))}}}set anchorPoint(t){H.value(this._anchorPoint,t)||(this._anchorPoint=t,this.savePropertyChangeEvent("anchorPoint",this.anchorPoint))}get zPosition(){return this._zPosition}set zPosition(t){H.value(this._zPosition,t)||(this._zPosition=t,this.savePropertyChangeEvent("zPosition",t))}get backgroundPaint(){if(!this._backgroundPaint)throw new Error("backgroundPaint cannot be undefined");return this._backgroundPaint}set backgroundPaint(t){this._backgroundPaint=t}get fontPaint(){if(!this._fontPaint)throw new Error("fontPaint cannot be undefined");return this._fontPaint}set fontPaint(t){this._fontPaint=t}duplicate(t){const i=new Ii({...this.getNodeOptions(),...this.getDrawableOptions(),...this.getTextOptions(),horizontalAlignmentMode:this.horizontalAlignmentMode,preferredMaxLayoutWidth:this.preferredMaxLayoutWidth,backgroundColor:this.backgroundColor,name:t});return this.children.length>0&&(i.children=this.children.map(n=>{const c=n.duplicate();return c.parent=i,c})),i}update(){super.update(),this.absoluteAlphaChange!==0&&this.initialize()}draw(t){if(this.parent&&this.text!==""&&!this.needsInitialization){t.save();const i=m2c2Globals.canvasScale/this.absoluteScale;t.scale(1/i,1/i),Y.rotateCanvasForDrawableNode(t,this);const n=(this.absolutePosition.x-this.size.width*this.anchorPoint.x*this.absoluteScale)*i,c=(this.absolutePosition.y-this.size.height*this.anchorPoint.y*this.absoluteScale)*i;if(this.paragraph===void 0)throw new Error("no paragraph");t.drawParagraph(this.paragraph,n,c),t.restore()}super.drawChildren(t)}warmup(t){const i=this.game.i18n;if(i&&this.localize!==!1){const c=i.getTextLocalization(this.text,this.interpolation);this.localizedFontName=c.fontName,this.localizedFontNames=c.fontNames??[]}if(!this.getRequiredLabelFonts(this.game.fontManager).some(c=>c.status===Zt.Deferred)&&Object.keys(this.layout).length===0){if(this.initialize(),!this.paragraph)throw new Error(`warmup Label node ${this.toString()}: paragraph is undefined`);t.drawParagraph(this.paragraph,0,0)}}}class Ge extends ae{constructor(t={}){super(t),this.type=lt.Scene,this.isDrawable=!0,this._anchorPoint={x:0,y:0},this._zPosition=0,this._backgroundColor=X.DEFAULT_SCENE_BACKGROUND_COLOR,this._active=!1,this._transitioning=!1,Ne(this,t),t.backgroundColor&&(this.backgroundColor=t.backgroundColor),this.saveNodeNewEvent()}get completeNodeOptions(){return{...this.options,...this.getNodeOptions(),...this.getDrawableOptions(),backgroundColor:this.backgroundColor}}initialize(){this.scale=m2c2Globals.rootScale,this.size.width=this.game.canvasCssWidth,this.size.height=this.game.canvasCssHeight,this.backgroundPaint&&this.backgroundPaint.delete(),this.backgroundPaint=xt.makePaint(this.canvasKit,this.backgroundColor,this.canvasKit.PaintStyle.Fill,!1),this.needsInitialization=!1}dispose(){xt.Dispose([this.backgroundPaint])}set game(t){this._game=t}get game(){if(this._game===void 0)throw new Error(`Scene ${this} has not been added to a game.`);return this._game}get backgroundColor(){return this._backgroundColor}set backgroundColor(t){H.value(this._backgroundColor,t)||(this._backgroundColor=t,this.needsInitialization=!0,this.savePropertyChangeEvent("backgroundColor",t))}get anchorPoint(){const t=this;return{get x(){return t._anchorPoint.x},set x(i){H.value(t._anchorPoint.x,i)||(t._anchorPoint.x=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))},get y(){return t._anchorPoint.y},set y(i){H.value(t._anchorPoint.y,i)||(t._anchorPoint.y=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))}}}set anchorPoint(t){H.value(this._anchorPoint,t)||(this._anchorPoint=t,this.savePropertyChangeEvent("anchorPoint",this.anchorPoint))}get zPosition(){return this._zPosition}set zPosition(t){H.value(this._zPosition,t)||(this._zPosition=t,this.savePropertyChangeEvent("zPosition",t))}duplicate(t){const i=new Ge({...this.getNodeOptions(),...this.getDrawableOptions(),backgroundColor:this.backgroundColor,name:t});return i.game=this.game,this.children.length>0&&(i.children=this.children.map(n=>{const c=n.duplicate();return c.parent=i,c})),i}onSetup(t,i){this.addEventListener("SceneSetup",t,i)}onAppear(t,i){this.addEventListener("SceneAppear",t,i)}update(){super.update()}draw(t){t.save();const i=m2c2Globals.canvasScale/this.absoluteScale;if(t.scale(1/i,1/i),Y.rotateCanvasForDrawableNode(t,this),!this.backgroundPaint)throw new Error(`in Scene ${this}, background paint is undefined.`);this.absoluteAlphaChange!==0&&this.backgroundPaint.setAlphaf(this.absoluteAlpha),t.drawRect([this.position.x*i*m2c2Globals.rootScale,this.position.y*i*m2c2Globals.rootScale,(this.position.x+this.size.width)*i*m2c2Globals.rootScale,(this.position.y+this.size.height)*i*m2c2Globals.rootScale],this.backgroundPaint),t.restore(),super.drawChildren(t)}warmup(t){this.initialize(),t.save();const i=m2c2Globals.canvasScale/this.absoluteScale;if(t.scale(1/i,1/i),!this.backgroundPaint)throw new Error(`in Scene ${this}, background paint is undefined.`);t.drawRect([this.position.x*i*m2c2Globals.rootScale,this.position.y*i*m2c2Globals.rootScale,(this.position.x+this.size.width)*i*m2c2Globals.rootScale,(this.position.y+this.size.height)*i*m2c2Globals.rootScale],this.backgroundPaint),t.restore(),this.children.forEach(n=>{n.isDrawable&&n.warmup(t)})}}class li extends ae{constructor(t={}){if(super(t),this.type=lt.Shape,this.isDrawable=!0,this.isShape=!0,this._anchorPoint={x:.5,y:.5},this._zPosition=0,this.shapeType=Wt.Undefined,this.ckPath=null,this._cornerRadius=0,this._fillColor=X.DEFAULT_SHAPE_FILL_COLOR,this._isAntialiased=!0,this.svgPathScaleForResizing=1,this.svgPathWidth=0,this.svgPathHeight=0,this.svgPreviousAbsoluteX=NaN,this.svgPreviousAbsoluteY=NaN,this.svgFirstPathDraw=!0,this.colorfulPathPaints=new Map,Ne(this,t),t.path!==void 0){if(this.path=t.path,this.shapeType=Wt.Path,this.shapeIsM2Path()&&t.size!==void 0&&(this.size=t.size),this.shapeIsSvgStringPath()&&t.size!==void 0)throw new Error("Size cannot be specified when path is SVG string path");if(this.svgPathRequestedWidth=t.path.width,this.svgPathRequestedHeight=t.path.height,this.svgPathRequestedHeight!==void 0&&this.svgPathRequestedWidth!==void 0)throw new Error("Cannot specify both width and height for SVG string path.");if(this.strokeColor||(this.strokeColor=X.DEFAULT_PATH_STROKE_COLOR),this.lineWidth===void 0&&(this.lineWidth=X.DEFAULT_PATH_LINE_WIDTH),t.circleOfRadius||t.rect)throw new Error("Shape must specify only one of: path, circleOfRadius, or rect")}if(t.circleOfRadius!==void 0){if(this.circleOfRadius=t.circleOfRadius,this.shapeType=Wt.Circle,t.size!==void 0)throw new Error("Size cannot be specified for circle shape");if(t.path||t.rect)throw new Error("Shape must specify only one of: path, circleOfRadius, or rect");this.size.width=this.circleOfRadius*2,this.size.height=this.circleOfRadius*2}if(t.rect&&(this.rect=t.rect,t.rect.size?(this.size.width=t.rect.size.width,this.size.height=t.rect.size.height):t.rect.width!==void 0&&t.rect.height!==void 0&&(this.size.width=t.rect.width,this.size.height=t.rect.height),t.rect.origin?this.position=t.rect.origin:t.rect.x!==void 0&&t.rect.y!==void 0&&(this.position={x:t.rect.x,y:t.rect.y}),this.shapeType=Wt.Rectangle,t.size!==void 0))throw new Error("Size cannot be specified for rectangle shape");t.cornerRadius!==void 0&&(this.cornerRadius=t.cornerRadius),t.fillColor&&(this.fillColor=t.fillColor),t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth),t.isAntialiased!==void 0&&(this.isAntialiased=t.isAntialiased),t.strokeColor&&!t.lineWidth&&console.warn(`warning: for node ${this}, strokeColor = ${t.strokeColor} but lineWidth is non-zero. In normal usage, both would be set or both would be undefined.`),t.strokeColor===void 0&&t.lineWidth&&console.warn(`warning: for node ${this}, lineWidth = ${t.lineWidth} but strokeColor is undefined. In normal usage, both would be set or both would be undefined.`),this.saveNodeNewEvent()}get completeNodeOptions(){let t;return this.shapeIsM2Path()&&(t=this.size),{...this.options,...this.getNodeOptions(),...this.getDrawableOptions(),circleOfRadius:this.circleOfRadius,rect:this.rect,cornerRadius:this.cornerRadius,fillColor:this.fillColor,strokeColor:this.strokeColor,lineWidth:this.lineWidth,path:this.path,size:t,isAntialiased:this.isAntialiased}}initialize(){if(this.shapeType===Wt.Path&&this.shapeIsSvgStringPath()){const t=this.path.pathString??this.path.svgPathString;if(!t)throw new Error("SVG Path string is null/undefined");if(this.path.svgPathString!==void 0&&console.warn("warning: svgPathString is deprecated. Use pathString instead."),this.ckPath=this.canvasKit.Path.MakeFromSVGString(t),!this.ckPath)throw new Error("could not make CanvasKit Path from SVG string");const i=this.ckPath.getBounds();this.svgPathWidth=i[2]+(i[0]<0?Math.abs(i[0]):0),this.svgPathHeight=i[3]+(i[1]<0?Math.abs(i[1]):0),this.svgPathRequestedHeight!==void 0?this.svgPathScaleForResizing=this.svgPathRequestedHeight/this.svgPathHeight:this.svgPathRequestedWidth!==void 0&&(this.svgPathScaleForResizing=this.svgPathRequestedWidth/this.svgPathWidth),this.size.width=this.svgPathWidth*this.svgPathScaleForResizing,this.size.height=this.svgPathHeight*this.svgPathScaleForResizing,this.svgPreviousAbsoluteX=0,this.svgPreviousAbsoluteY=0}if(this.shapeIsM2Path()&&(this.size.width===0||this.size.height===0||this.size.width===void 0||this.size.height===void 0))throw new Error("Size of shape must have non-zero height and width when path is M2Path");this.fillColor&&(this.fillColorPaintAntialiased=xt.makePaint(this.canvasKit,this.fillColor,this.canvasKit.PaintStyle.Fill,!0),this.fillColorPaintNotAntialiased=xt.makePaint(this.canvasKit,this.fillColor,this.canvasKit.PaintStyle.Fill,!1)),this.strokeColor&&(this.strokeColorPaintAntialiased=xt.makePaint(this.canvasKit,this.strokeColor,this.canvasKit.PaintStyle.Stroke,!0),this.strokeColorPaintNotAntialiased=xt.makePaint(this.canvasKit,this.strokeColor,this.canvasKit.PaintStyle.Stroke,!1)),this.svgFirstPathDraw=!0,this.needsInitialization=!1}get anchorPoint(){const t=this;return{get x(){return t._anchorPoint.x},set x(i){H.value(t._anchorPoint.x,i)||(t._anchorPoint.x=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))},get y(){return t._anchorPoint.y},set y(i){H.value(t._anchorPoint.y,i)||(t._anchorPoint.y=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))}}}set anchorPoint(t){H.value(this._anchorPoint,t)||(this._anchorPoint=t,this.savePropertyChangeEvent("anchorPoint",this.anchorPoint))}get zPosition(){return this._zPosition}set zPosition(t){H.value(this._zPosition,t)||(this._zPosition=t,this.savePropertyChangeEvent("zPosition",t))}dispose(){xt.Dispose([this._strokeColorPaintAntialiased,this._strokeColorPaintNotAntialiased,this._fillColorPaintAntialiased,this._fillColorPaintNotAntialiased,this.ckPath,...Array.from(this.colorfulPathPaints.values())])}duplicate(t){const i=new li({...this.getNodeOptions(),...this.getDrawableOptions(),shapeType:this.shapeType,circleOfRadius:this.circleOfRadius,rect:this.rect,cornerRadius:this.cornerRadius,fillColor:this.fillColor,strokeColor:this.strokeColor,lineWidth:this.lineWidth,name:t});return this.children.length>0&&(i.children=this.children.map(n=>{const c=n.duplicate();return c.parent=i,c})),i}update(){super.update()}draw(t){t.save();const i=m2c2Globals.canvasScale/this.absoluteScale;t.scale(1/i,1/i),Y.rotateCanvasForDrawableNode(t,this),this.absoluteAlphaChange!==0&&this.applyAlphaToPaints(this.absoluteAlpha,[this._fillColorPaintAntialiased,this._fillColorPaintNotAntialiased,this._strokeColorPaintAntialiased,this._strokeColorPaintNotAntialiased]),this.shapeIsM2Path()&&this.drawPathFromM2Path(t),this.shapeIsSvgStringPath()&&this.drawPathFromSvgString(t),this.shapeType===Wt.Circle&&this.drawCircle(t),this.shapeType===Wt.Rectangle&&this.drawRectangle(t),t.restore(),super.drawChildren(t)}applyAlphaToPaints(t,i){i.forEach(n=>{n&&n.setAlphaf(t)})}drawPathFromM2Path(t){const i=m2c2Globals.canvasScale/this.absoluteScale,n=(this.absolutePosition.x-this.anchorPoint.x*this.size.width*this.absoluteScale)*i,c=(this.absolutePosition.y-this.anchorPoint.y*this.size.height*this.absoluteScale)*i;if(this.pathIsM2ColorfulPath(this.path)){const h=this.path.linePresentations;let C=0;const T=this.path.subpaths;let B;for(let $=0;$<T.length;$++){const ct=T[$].flat();for(let ut=0;ut<ct.length-1;ut++){if(h[C].subpathIndex===$&&h[C].pointIndex===ut){const bt=h[C].strokeColor,wt=h[C].lineWidth,Ht=[...bt,wt].toString();B=this.colorfulPathPaints.get(Ht),B===void 0&&(B=xt.makePaint(this.canvasKit,bt,this.canvasKit.PaintStyle.Stroke,!0),B.setStrokeWidth(wt*m2c2Globals.canvasScale),this.colorfulPathPaints.set(Ht,B)),C<h.length-1&&C++}if(B===void 0)throw new Error("paint is undefined");t.drawLine(n+ct[ut].x*m2c2Globals.canvasScale,c+ct[ut].y*m2c2Globals.canvasScale,n+ct[ut+1].x*m2c2Globals.canvasScale,c+ct[ut+1].y*m2c2Globals.canvasScale,B)}}return}if(this.strokeColor&&this.strokeColorPaintAntialiased&&this.lineWidth){this.strokeColorPaintAntialiased.setStrokeWidth(this.lineWidth*m2c2Globals.canvasScale);const h=this.path.subpaths;for(const C of h){const T=C.flat();for(let B=0;B<T.length-1;B++)t.drawLine(n+T[B].x*m2c2Globals.canvasScale,c+T[B].y*m2c2Globals.canvasScale,n+T[B+1].x*m2c2Globals.canvasScale,c+T[B+1].y*m2c2Globals.canvasScale,this.strokeColorPaintAntialiased)}}}drawPathFromSvgString(t){if(!this.ckPath)return;const i=this.calculateSvgPathX(),n=this.calculateSvgPathY();if(this.pathNeedsTransform(i,n)){const h=m2c2Globals.canvasScale/this.absoluteScale*this.svgPathScaleForResizing*m2c2Globals.rootScale,C=this.calculateTransformationMatrix(h,i,n);this.ckPath=this.ckPath.transform(C),this.saveSvgPathAbsolutePosition(i,n)}if(this.fillColor){const c=this.getFillPaint();t.drawPath(this.ckPath,c)}if(this.strokeColor&&this.lineWidth){const c=this.getStrokePaint(this.lineWidth);t.drawPath(this.ckPath,c)}}calculateSvgPathY(){const t=m2c2Globals.canvasScale/this.absoluteScale;return(this.absolutePosition.y-this.size.height*this.absoluteScale/2)*t}calculateSvgPathX(){const t=m2c2Globals.canvasScale/this.absoluteScale;return(this.absolutePosition.x-this.size.width*this.absoluteScale/2)*t}saveSvgPathAbsolutePosition(t,i){this.svgPreviousAbsoluteX=t,this.svgPreviousAbsoluteY=i}calculateTransformationMatrix(t,i,n){let c;this.svgFirstPathDraw?(c=t,this.svgFirstPathDraw=!1):c=1;const h=i-this.svgPreviousAbsoluteX,C=n-this.svgPreviousAbsoluteY;return[c,0,h,0,c,C,0,0,1]}pathNeedsTransform(t,i){return this.svgFirstPathDraw===!0||t!==this.svgPreviousAbsoluteX||i!==this.svgPreviousAbsoluteY}shapeIsSvgStringPath(){return this.path?.pathString!==void 0||this.path?.svgPathString!==void 0}shapeIsM2Path(){return this.path?.subpaths!==void 0}pathIsM2ColorfulPath(t){return t!==void 0&&"linePresentations"in t}drawCircle(t){if(this.circleOfRadius){if(this.fillColor){const i=this.getFillPaint();this.drawCircleWithCanvasKit(t,i)}if(this.strokeColor&&this.lineWidth){const i=this.getStrokePaint(this.lineWidth);this.drawCircleWithCanvasKit(t,i)}}}drawRectangle(t){if(this.fillColor){const i=this.getFillPaint();this.drawRectangleWithCanvasKit(t,i)}if(this.strokeColor&&this.lineWidth){const i=this.getStrokePaint(this.lineWidth);this.drawRectangleWithCanvasKit(t,i)}}drawCircleWithCanvasKit(t,i){if(!this.circleOfRadius)return;const n=m2c2Globals.canvasScale/this.absoluteScale,c=this.absolutePosition.x*n,h=this.absolutePosition.y*n,C=this.circleOfRadius*this.absoluteScale*n;t.drawCircle(c,h,C,i)}drawRectangleWithCanvasKit(t,i){const n=this.calculateCKRoundedRectangle();t.drawRRect(n,i)}calculateCKRoundedRectangle(){const t=m2c2Globals.canvasScale/this.absoluteScale;return this.canvasKit.RRectXY(this.canvasKit.LTRBRect((this.absolutePosition.x-this.anchorPoint.x*this.size.width*this.absoluteScale)*t,(this.absolutePosition.y-this.anchorPoint.y*this.size.height*this.absoluteScale)*t,(this.absolutePosition.x+this.size.width*this.absoluteScale-this.anchorPoint.x*this.size.width*this.absoluteScale)*t,(this.absolutePosition.y+this.size.height*this.absoluteScale-this.anchorPoint.y*this.size.height*this.absoluteScale)*t),this.cornerRadius*t,this.cornerRadius*t)}getFillPaint(){return this.involvedInActionAffectingAppearance()?this.fillColorPaintNotAntialiased:this.isAntialiased?this.fillColorPaintAntialiased:this.fillColorPaintNotAntialiased}getStrokePaint(t){let i;this.involvedInActionAffectingAppearance()?i=this.strokeColorPaintNotAntialiased:i=this.isAntialiased?this.strokeColorPaintAntialiased:this.strokeColorPaintNotAntialiased;const n=m2c2Globals.canvasScale/this.absoluteScale;return i.setStrokeWidth(t*n),i}warmup(t){this.initialize(),t.save();const i=m2c2Globals.canvasScale/this.absoluteScale;t.scale(1/i,1/i),this.shapeType===Wt.Circle&&(this.fillColor&&this.warmupFilledCircle(t),this.strokeColor&&this.lineWidth&&this.warmupStrokedCircle(t)),this.shapeType===Wt.Rectangle&&(this.fillColor&&this.warmupFilledRectangle(t),this.strokeColor&&this.lineWidth&&this.warmupStrokedRectangle(t)),t.restore(),this.children.forEach(n=>{n.isDrawable&&n.warmup(t)})}warmupFilledCircle(t){this.circleOfRadius&&(this.drawCircleWithCanvasKit(t,this.fillColorPaintAntialiased),this.drawCircleWithCanvasKit(t,this.fillColorPaintNotAntialiased))}warmupStrokedCircle(t){if(!this.lineWidth||!this.circleOfRadius)return;const i=m2c2Globals.canvasScale/this.absoluteScale;this.strokeColorPaintAntialiased.setStrokeWidth(this.lineWidth*i),this.drawCircleWithCanvasKit(t,this.strokeColorPaintAntialiased),this.strokeColorPaintNotAntialiased.setStrokeWidth(this.lineWidth*i),this.drawCircleWithCanvasKit(t,this.strokeColorPaintNotAntialiased)}warmupFilledRectangle(t){this.drawRectangleWithCanvasKit(t,this.fillColorPaintAntialiased),this.drawRectangleWithCanvasKit(t,this.fillColorPaintNotAntialiased)}warmupStrokedRectangle(t){if(!this.lineWidth||!this.circleOfRadius)return;const i=m2c2Globals.canvasScale/this.absoluteScale;this.strokeColorPaintAntialiased.setStrokeWidth(this.lineWidth*i),this.drawRectangleWithCanvasKit(t,this.strokeColorPaintAntialiased),this.strokeColorPaintNotAntialiased.setStrokeWidth(this.lineWidth*i),this.drawRectangleWithCanvasKit(t,this.strokeColorPaintNotAntialiased)}get circleOfRadius(){return this._circleOfRadius}set circleOfRadius(t){H.value(t,this._circleOfRadius)||(this._circleOfRadius=t,this.needsInitialization=!0,this.savePropertyChangeEvent("circleOfRadius",t))}get rect(){return this._rect}set rect(t){H.value(t,this._rect)||(this._rect=t,this.needsInitialization=!0,this.savePropertyChangeEvent("rect",t))}get cornerRadius(){return this._cornerRadius}set cornerRadius(t){H.value(t,this._cornerRadius)||(this._cornerRadius=t??0,this.needsInitialization=!0,this.savePropertyChangeEvent("cornerRadius",t??0))}get lineWidth(){return this._lineWidth}set lineWidth(t){H.value(t,this._lineWidth)||(this._lineWidth=t,this.needsInitialization=!0,this.savePropertyChangeEvent("lineWidth",t))}get path(){return this._path}set path(t){H.value(t,this._path)||(this._path=t,this.needsInitialization=!0,this.savePropertyChangeEvent("path",t))}get fillColor(){return this._fillColor}set fillColor(t){H.value(t,this._fillColor)||(this._fillColor=t,this.needsInitialization=!0,this.savePropertyChangeEvent("fillColor",t))}get strokeColor(){return this._strokeColor}set strokeColor(t){H.value(t,this._strokeColor)||(this._strokeColor=t,this.needsInitialization=!0,this.savePropertyChangeEvent("strokeColor",t))}get isAntialiased(){return this._isAntialiased}set isAntialiased(t){H.value(t,this._isAntialiased)||(this._isAntialiased=t,this.needsInitialization=!0,this.savePropertyChangeEvent("isAntialiased",t))}get fillColorPaintAntialiased(){if(!this._fillColorPaintAntialiased)throw new Error("fillColorPaintAntiAliased is undefined");return this._fillColorPaintAntialiased}set fillColorPaintAntialiased(t){this._fillColorPaintAntialiased=t}get strokeColorPaintAntialiased(){if(!this._strokeColorPaintAntialiased)throw new Error("strokeColorPaintAntiAliased is undefined");return this._strokeColorPaintAntialiased}set strokeColorPaintAntialiased(t){this._strokeColorPaintAntialiased=t}get fillColorPaintNotAntialiased(){if(!this._fillColorPaintNotAntialiased)throw new Error("fillColorPaintNotAntiAliased is undefined");return this._fillColorPaintNotAntialiased}set fillColorPaintNotAntialiased(t){this._fillColorPaintNotAntialiased=t}get strokeColorPaintNotAntialiased(){if(!this._strokeColorPaintNotAntialiased)throw new Error("strokeColorPaintNotAntiAliased is undefined");return this._strokeColorPaintNotAntialiased}set strokeColorPaintNotAntialiased(t){this._strokeColorPaintNotAntialiased=t}}class Li extends ae{constructor(t={}){super(t),this.type=lt.TextLine,this.isDrawable=!0,this.isText=!0,this._zPosition=0,this._anchorPoint={x:0,y:.5},this._text="",this._fontColor=X.DEFAULT_FONT_COLOR,this._fontSize=X.DEFAULT_FONT_SIZE,this._interpolation={},this._localize=!0,this.typeface=null,this.tryMissingTranslationPaint=!1,this.textForDraw="",this.localizedFontNames=[],Ne(this,t),this.size.height=this.localizedFontSize??this.fontSize,this.size.width=t.width??NaN,this.saveNodeNewEvent()}get completeNodeOptions(){return{...this.options,...this.getNodeOptions(),...this.getDrawableOptions(),...this.getTextOptions(),width:this.size.width}}initialize(){const t=this.game.i18n;if(this.tryMissingTranslationPaint=!1,t&&this.localize!==!1){const n=t.getTextLocalization(this.text,this.interpolation);this.textForDraw=n.text,this.localizedFontSize=n.fontSize,this.localizedFontName=n.fontName,this.localizedFontNames=n.fontNames??[],n.isFallbackOrMissingTranslation&&(this.tryMissingTranslationPaint=!0)}else this.textForDraw=this.text;const i=this.game.fontManager;if(this.fontForDraw=this.getRequiredTextLineFont(i),this.fontForDraw.status===Zt.Deferred){i.prepareDeferredFont(this.fontForDraw);return}this.fontForDraw.status!==Zt.Loading&&(this.createFontPaint(t),this.createFont(i),this.needsInitialization=!1)}getRequiredTextLineFont(t){if(this.game.i18n){if(this.localizedFontName!==void 0&&this.localizedFontNames.length!==0||this.localizedFontNames.length>1)throw new Error("TextLine supports only one font, but multiple fonts are specified in translation.");if(this.localizedFontName!==void 0)return t.fonts[this.localizedFontName];if(this.localizedFontNames.length==1)return t.fonts[this.localizedFontNames[0]]}return this.fontName===void 0?t.getDefaultFont():t.getFont(this.fontName)}createFontPaint(t){this.paint&&this.paint.delete(),this.paint=new this.canvasKit.Paint,this.tryMissingTranslationPaint&&this.localize!==!1?t?.missingLocalizationColor&&this.paint.setColor(this.canvasKit.Color(t.missingLocalizationColor[0],t.missingLocalizationColor[1],t.missingLocalizationColor[2],t.missingLocalizationColor[3])):this.paint.setColor(this.canvasKit.Color(this.fontColor[0],this.fontColor[1],this.fontColor[2],this.fontColor[3])),this.paint.setStyle(this.canvasKit.PaintStyle.Fill),this.paint.setAntiAlias(!0)}createFont(t){if(this.fontForDraw)this.typeface=t.getTypeface(this.fontForDraw.fontName);else{const i=t.getFontNames();i.length>0&&(this.typeface=t.getTypeface(i[0]))}this.font&&this.font.delete(),this.font=new this.canvasKit.Font(this.typeface,(this.localizedFontSize??this.fontSize)*m2c2Globals.canvasScale)}get text(){return this._text}set text(t){H.value(this._text,t)||(this._text=t,this.needsInitialization=!0,this.savePropertyChangeEvent("text",t))}get fontName(){return this._fontName}set fontName(t){H.value(this._fontName,t)||(this._fontName=t,this.needsInitialization=!0,this.savePropertyChangeEvent("fontName",t))}get fontColor(){return this._fontColor}set fontColor(t){H.value(this._fontColor,t)||(this._fontColor=t,this.needsInitialization=!0,this.savePropertyChangeEvent("fontColor",t))}get fontSize(){return this._fontSize}set fontSize(t){H.value(this._fontSize,t)||(this._fontSize=t,this.needsInitialization=!0,this.savePropertyChangeEvent("fontSize",t))}get interpolation(){return this._interpolation}set interpolation(t){H.value(this._interpolation,t)||(this._interpolation=t,Object.freeze(this._interpolation),this.needsInitialization=!0,this.savePropertyChangeEvent("interpolation",t))}get localize(){return this._localize}set localize(t){H.value(this._localize,t)||(this._localize=t,this.needsInitialization=!0,this.savePropertyChangeEvent("localize",t))}get anchorPoint(){const t=this;return{get x(){return t._anchorPoint.x},set x(i){H.value(t._anchorPoint.x,i)||(t._anchorPoint.x=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))},get y(){return t._anchorPoint.y},set y(i){H.value(t._anchorPoint.y,i)||(t._anchorPoint.y=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))}}}set anchorPoint(t){H.value(this._anchorPoint,t)||(this._anchorPoint=t,this.savePropertyChangeEvent("anchorPoint",this.anchorPoint))}get zPosition(){return this._zPosition}set zPosition(t){H.value(this._zPosition,t)||(this._zPosition=t,this.savePropertyChangeEvent("zPosition",t))}dispose(){xt.Dispose([this.font,this.typeface,this.paint])}duplicate(t){const i=new Li({...this.getNodeOptions(),...this.getDrawableOptions(),...this.getTextOptions(),width:this.size.width,name:t});return this.children.length>0&&(i.children=this.children.map(n=>{const c=n.duplicate();return c.parent=i,c})),i}update(){super.update()}draw(t){if(this.parent&&this.text&&!this.needsInitialization){t.save();const i=m2c2Globals.canvasScale/this.absoluteScale;t.scale(1/i,1/i),Y.rotateCanvasForDrawableNode(t,this);const n=this.absolutePosition.x*i,c=(this.absolutePosition.y+this.size.height*this.anchorPoint.y*this.absoluteScale)*i;if(this.paint===void 0||this.font===void 0)throw new Error(`in TextLine node ${this}, Paint or Font is undefined.`);this.absoluteAlphaChange!==0&&this.paint.setAlphaf(this.absoluteAlpha),t.drawText(this.textForDraw,n,c,this.paint,this.font),t.restore()}super.drawChildren(t)}warmup(t){const i=this.game.i18n;if(i&&this.localize!==!1){const c=i.getTextLocalization(this.text,this.interpolation);this.localizedFontName=c.fontName,this.localizedFontNames=c.fontNames??[]}if(this.getRequiredTextLineFont(this.game.fontManager).status!==Zt.Deferred){if(this.initialize(),this.paint===void 0||this.font===void 0)throw new Error(`warmup TextLine node ${this.toString()}: Paint or Font is undefined.`);t.drawText(this.text,0,0,this.paint,this.font)}}}class hi extends ae{constructor(t={}){super(t),this.type=lt.Sprite,this.isDrawable=!0,this._anchorPoint={x:.5,y:.5},this._zPosition=0,this._imageName="",Ne(this,t),t.imageName!==void 0&&(this.imageName=t.imageName),this.saveNodeNewEvent()}get completeNodeOptions(){return{...this.options,...this.getNodeOptions(),...this.getDrawableOptions(),imageName:this.imageName}}initialize(){if(this.m2Image=this.game.imageManager.getImage(this._imageName),!this.m2Image)throw new Error(`could not create sprite. the image named ${this._imageName} has not been loaded`);this.size.width=this.m2Image.width,this.size.height=this.m2Image.height,this._paint||(this.paint=new this.canvasKit.Paint),this.needsInitialization=!1}dispose(){xt.Dispose([this.m2Image?.canvaskitImage,this._paint])}get imageName(){return this._imageName}set imageName(t){H.value(this._imageName,t)||(this._imageName=t,this.needsInitialization=!0)}get anchorPoint(){const t=this;return{get x(){return t._anchorPoint.x},set x(i){H.value(t._anchorPoint.x,i)||(t._anchorPoint.x=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))},get y(){return t._anchorPoint.y},set y(i){H.value(t._anchorPoint.y,i)||(t._anchorPoint.y=i,t.savePropertyChangeEvent("anchorPoint",t.anchorPoint))}}}set anchorPoint(t){H.value(this._anchorPoint,t)||(this._anchorPoint=t,this.savePropertyChangeEvent("anchorPoint",this.anchorPoint))}get zPosition(){return this._zPosition}set zPosition(t){H.value(this._zPosition,t)||(this._zPosition=t,this.savePropertyChangeEvent("zPosition",t))}set paint(t){this._paint=t}get paint(){if(!this._paint)throw new Error(`in paint getter: Sprite node ${this.toString()} paint is undefined.`);return this._paint}duplicate(t){const i=new hi({...this.getNodeOptions(),...this.getDrawableOptions(),imageName:this.imageName,name:t});return this.children.length>0&&(i.children=this.children.map(n=>{const c=n.duplicate();return c.parent=i,c})),i}update(){super.update()}draw(t){if(!this.hidden){if(this.m2Image){t.save();const i=m2c2Globals.canvasScale/this.absoluteScale;t.scale(1/i,1/i),Y.rotateCanvasForDrawableNode(t,this);const n=(this.absolutePosition.x-this.size.width*this.anchorPoint.x*this.absoluteScale)*i,c=(this.absolutePosition.y-this.size.height*this.anchorPoint.y*this.absoluteScale)*i;if(this.absoluteAlphaChange!==0&&this.paint.setAlphaf(this.absoluteAlpha),this.m2Image.status===Qt.Ready&&this.m2Image.canvaskitImage)this.m2Image.isFallback&&this.drawFallbackImageBorder(t),t.drawImage(this.m2Image.canvaskitImage,n,c,this.paint);else if(this.m2Image.status===Qt.Deferred&&(console.log(`begin loading lazy image ${this.m2Image.imageName} for Sprite node ${this.toString()}`),this.game.imageManager.prepareDeferredImage(this.m2Image)),this.m2Image.status===Qt.Error)throw new Error(`error status on image ${this.m2Image.imageName} for Sprite node ${this.toString()}`);t.restore()}super.drawChildren(t)}}warmup(t){if(this.m2Image?.status===Qt.Ready){if(this.initialize(),!this.m2Image)throw new Error(`in Sprite.warmup(): Sprite node ${this.toString()}: image not loaded.`);if(!this.m2Image.canvaskitImage)throw new Error(`in Sprite.warmup(): Sprite node ${this.toString()} image ${this.m2Image.imageName} is undefined.`);t.drawImage(this.m2Image.canvaskitImage,0,0)}this.children.forEach(i=>{i.isDrawable&&i.warmup(t)})}drawFallbackImageBorder(t){const i=this.game.imageManager.missingLocalizationImagePaint;if(!i)return;const n=m2c2Globals.canvasScale/this.absoluteScale,c=this.canvasKit.RRectXY(this.canvasKit.LTRBRect((this.absolutePosition.x-this.anchorPoint.x*this.size.width*this.absoluteScale)*n,(this.absolutePosition.y-this.anchorPoint.y*this.size.height*this.absoluteScale)*n,(this.absolutePosition.x+this.size.width*this.absoluteScale-this.anchorPoint.x*this.size.width*this.absoluteScale)*n,(this.absolutePosition.y+this.size.height*this.absoluteScale-this.anchorPoint.y*this.size.height*this.absoluteScale)*n),0,0);t.drawRRect(c,i)}}class _n{constructor(){Y.registerM2NodeClass(Ii,li,hi,Ge,Li)}createNode(t,i,n){const c=i||t;if(!this.hasClassRegistration(c))throw new Error(`Unknown node type: ${c}`);if(!m2c2Globals.m2NodeClassRegistry)throw new Error("Node class registry is not initialized.");const h=m2c2Globals.m2NodeClassRegistry[c];return new h(n)}hasClassRegistration(t){return Object.keys(m2c2Globals.m2NodeClassRegistry??{}).includes(t)}}class Qs{static rgbaColor(t,i){return!t||!i?!1:t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]}}class Tn{constructor(t,i){this.fonts={},this.game=t,this.baseUrls=i,this.canvasKit=t.canvasKit,this.provider=this.canvasKit.TypefaceFontProvider.Make()}initializeFonts(t){return this.loadFonts(t??[])}async loadFonts(t){if(t.length===0)return;const i=t.map((n,c)=>{let h=n.url;Y.urlHasScheme(n.url)||(h=Y.getUrlFromManifest(this.game,`${this.baseUrls.assets}/${n.url}`));const C={fontName:n.fontName,typeface:void 0,data:n.sharedFont?.data,default:c===0,url:n.sharedFont?.url??h,status:n.lazy?Zt.Deferred:Zt.Loading};if(this.fonts[n.fontName]=C,C.status===Zt.Loading)return this.prepareFont(C)});await Promise.all(i)}async prepareFont(t){const i=t.data??await this.fetchFontAsArrayBuffer(t);this.registerFont(i,t),console.log(`\u26AA font ${t.fontName}${t.default?" (default)":""} loaded for game ${this.game.id} from ${t.url}`)}async prepareDeferredFont(t){return t.status=Zt.Loading,this.prepareFont(t)}async fetchFontAsArrayBuffer(t){const i=await fetch(t.url);if(!i.ok)throw new Error(`cannot fetch font ${t.fontName} at url ${t.url}: ${i.statusText}`);return await i.arrayBuffer()}registerFont(t,i){this.provider.registerFont(t,i.fontName);const n=this.canvasKit.Typeface.MakeFreeTypeFaceFromData(t);if(!n)throw new Error(`cannot make typeface for font ${i.fontName} at url ${i.url}`);i.typeface=n,i.status=Zt.Ready}getFont(t){return this.fonts[t]}getDefaultFont(){const t=Object.values(this.fonts).find(i=>i.default);if(!t)throw new Error("no default font found; please make sure at least one font is loaded");return t}dispose(){const t=Object.entries(this.fonts).map(([,i])=>i.typeface);xt.Dispose([...t,this.provider])}getTypeface(t){const i=this.fonts[t]?.typeface;if(!i)throw new Error(`font ${t} not found`);return i}getFontNames(){return Object.keys(this.fonts)}}var hr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Zs(g){return g&&g.__esModule&&Object.prototype.hasOwnProperty.call(g,"default")?g.default:g}function Fn(g){if(g.__esModule)return g;var t=g.default;if(typeof t=="function"){var i=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(g).forEach(function(n){var c=Object.getOwnPropertyDescriptor(g,n);Object.defineProperty(i,n,c.get?c:{enumerable:!0,get:function(){return g[n]}})}),i}var cr={exports:{}},ta={},ea=Object.freeze({__proto__:null,default:ta}),ia=Fn(ea);function Mn(g,t){for(var i=0,n=g.length-1;n>=0;n--){var c=g[n];c==="."?g.splice(n,1):c===".."?(g.splice(n,1),i++):i&&(g.splice(n,1),i--)}if(t)for(;i--;i)g.unshift("..");return g}var ra=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,ur=function(g){return ra.exec(g).slice(1)};function ki(){for(var g="",t=!1,i=arguments.length-1;i>=-1&&!t;i--){var n=i>=0?arguments[i]:"/";if(typeof n!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!n)continue;g=n+"/"+g,t=n.charAt(0)==="/"}return g=Mn(pr(g.split("/"),function(c){return!!c}),!t).join("/"),(t?"/":"")+g||"."}function dr(g){var t=fr(g),i=sa(g,-1)==="/";return g=Mn(pr(g.split("/"),function(n){return!!n}),!t).join("/"),!g&&!t&&(g="."),g&&i&&(g+="/"),(t?"/":"")+g}function fr(g){return g.charAt(0)==="/"}function xn(){var g=Array.prototype.slice.call(arguments,0);return dr(pr(g,function(t,i){if(typeof t!="string")throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))}function Rn(g,t){g=ki(g).substr(1),t=ki(t).substr(1);function i($){for(var it=0;it<$.length&&$[it]==="";it++);for(var ct=$.length-1;ct>=0&&$[ct]==="";ct--);return it>ct?[]:$.slice(it,ct-it+1)}for(var n=i(g.split("/")),c=i(t.split("/")),h=Math.min(n.length,c.length),C=h,T=0;T<h;T++)if(n[T]!==c[T]){C=T;break}for(var B=[],T=C;T<n.length;T++)B.push("..");return B=B.concat(c.slice(C)),B.join("/")}var Nn="/",kn=":";function On(g){var t=ur(g),i=t[0],n=t[1];return!i&&!n?".":(n&&(n=n.substr(0,n.length-1)),i+n)}function In(g,t){var i=ur(g)[2];return t&&i.substr(-1*t.length)===t&&(i=i.substr(0,i.length-t.length)),i}function Ln(g){return ur(g)[3]}var na={extname:Ln,basename:In,dirname:On,sep:Nn,delimiter:kn,relative:Rn,join:xn,isAbsolute:fr,normalize:dr,resolve:ki};function pr(g,t){if(g.filter)return g.filter(t);for(var i=[],n=0;n<g.length;n++)t(g[n],n,g)&&i.push(g[n]);return i}var sa="ab".substr(-1)==="b"?function(g,t,i){return g.substr(t,i)}:function(g,t,i){return t<0&&(t=g.length+t),g.substr(t,i)},aa=Object.freeze({__proto__:null,basename:In,default:na,delimiter:kn,dirname:On,extname:Ln,isAbsolute:fr,join:xn,normalize:dr,relative:Rn,resolve:ki,sep:Nn}),oa=Fn(aa),Dn;function la(){return Dn||(Dn=1,function(g,t){var i=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(c={}){var h=c,C,T;h.ready=new Promise((e,r)=>{C=e,T=r}),function(e){e.Td=e.Td||[],e.Td.push(function(){e.MakeSWCanvasSurface=function(r){var s=r,l=typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas;if(!(typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||l||(s=document.getElementById(r),s)))throw"Canvas with id "+r+" was not found";return(r=e.MakeSurface(s.width,s.height))&&(r.Ld=s),r},e.MakeCanvasSurface||(e.MakeCanvasSurface=e.MakeSWCanvasSurface),e.MakeSurface=function(r,s){var l={width:r,height:s,colorType:e.ColorType.RGBA_8888,alphaType:e.AlphaType.Unpremul,colorSpace:e.ColorSpace.SRGB},d=r*s*4,m=e._malloc(d);return(l=e.Surface._makeRasterDirect(l,m,4*r))&&(l.Ld=null,l.Hf=r,l.Df=s,l.Ff=d,l.bf=m,l.getCanvas().clear(e.TRANSPARENT)),l},e.MakeRasterDirectSurface=function(r,s,l){return e.Surface._makeRasterDirect(r,s.byteOffset,l)},e.Surface.prototype.flush=function(r){if(e.Md(this.Kd),this._flush(),this.Ld){var s=new Uint8ClampedArray(e.HEAPU8.buffer,this.bf,this.Ff);s=new ImageData(s,this.Hf,this.Df),r?this.Ld.getContext("2d").putImageData(s,0,0,r[0],r[1],r[2]-r[0],r[3]-r[1]):this.Ld.getContext("2d").putImageData(s,0,0)}},e.Surface.prototype.dispose=function(){this.bf&&e._free(this.bf),this.delete()},e.Md=e.Md||function(){},e.Te=e.Te||function(){return null}})}(h),function(e){e.Td=e.Td||[],e.Td.push(function(){function r(y,v,A){return y&&y.hasOwnProperty(v)?y[v]:A}function s(y){var v=De(Yt);return Yt[v]=y,v}function l(y){return y.naturalHeight||y.videoHeight||y.displayHeight||y.height}function d(y){return y.naturalWidth||y.videoWidth||y.displayWidth||y.width}function m(y,v,A,O){return y.bindTexture(y.TEXTURE_2D,v),O||A.alphaType!==e.AlphaType.Premul||y.pixelStorei(y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),v}function P(y,v,A){A||v.alphaType!==e.AlphaType.Premul||y.pixelStorei(y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),y.bindTexture(y.TEXTURE_2D,null)}e.GetWebGLContext=function(y,v){if(!y)throw"null canvas passed into makeWebGLContext";var A={alpha:r(v,"alpha",1),depth:r(v,"depth",1),stencil:r(v,"stencil",8),antialias:r(v,"antialias",0),premultipliedAlpha:r(v,"premultipliedAlpha",1),preserveDrawingBuffer:r(v,"preserveDrawingBuffer",0),preferLowPowerToHighPerformance:r(v,"preferLowPowerToHighPerformance",0),failIfMajorPerformanceCaveat:r(v,"failIfMajorPerformanceCaveat",0),enableExtensionsByDefault:r(v,"enableExtensionsByDefault",1),explicitSwapControl:r(v,"explicitSwapControl",0),renderViaOffscreenBackBuffer:r(v,"renderViaOffscreenBackBuffer",0)};if(A.majorVersion=v&&v.majorVersion?v.majorVersion:typeof WebGL2RenderingContext<"u"?2:1,A.explicitSwapControl)throw"explicitSwapControl is not supported";return y=Ss(y,A),y?(Kr(y),rt.fe.getExtension("WEBGL_debug_renderer_info"),y):0},e.deleteContext=function(y){rt===ce[y]&&(rt=null),typeof JSEvents=="object"&&JSEvents.ug(ce[y].fe.canvas),ce[y]&&ce[y].fe.canvas&&(ce[y].fe.canvas.zf=void 0),ce[y]=null},e._setTextureCleanup({deleteTexture:function(y,v){var A=Yt[v];A&&ce[y].fe.deleteTexture(A),Yt[v]=null}}),e.MakeWebGLContext=function(y){if(!this.Md(y))return null;var v=this._MakeGrContext();if(!v)return null;v.Kd=y;var A=v.delete.bind(v);return v.delete=function(){e.Md(this.Kd),A()}.bind(v),rt.ff=v},e.MakeGrContext=e.MakeWebGLContext,e.GrDirectContext.prototype.getResourceCacheLimitBytes=function(){e.Md(this.Kd),this._getResourceCacheLimitBytes()},e.GrDirectContext.prototype.getResourceCacheUsageBytes=function(){e.Md(this.Kd),this._getResourceCacheUsageBytes()},e.GrDirectContext.prototype.releaseResourcesAndAbandonContext=function(){e.Md(this.Kd),this._releaseResourcesAndAbandonContext()},e.GrDirectContext.prototype.setResourceCacheLimitBytes=function(y){e.Md(this.Kd),this._setResourceCacheLimitBytes(y)},e.MakeOnScreenGLSurface=function(y,v,A,O,D,K){return!this.Md(y.Kd)||(v=D===void 0||K===void 0?this._MakeOnScreenGLSurface(y,v,A,O):this._MakeOnScreenGLSurface(y,v,A,O,D,K),!v)?null:(v.Kd=y.Kd,v)},e.MakeRenderTarget=function(){var y=arguments[0];if(!this.Md(y.Kd))return null;if(arguments.length===3){var v=this._MakeRenderTargetWH(y,arguments[1],arguments[2]);if(!v)return null}else if(arguments.length===2){if(v=this._MakeRenderTargetII(y,arguments[1]),!v)return null}else return null;return v.Kd=y.Kd,v},e.MakeWebGLCanvasSurface=function(y,v,A){v=v||null;var O=y,D=typeof OffscreenCanvas<"u"&&O instanceof OffscreenCanvas;if(!(typeof HTMLCanvasElement<"u"&&O instanceof HTMLCanvasElement||D||(O=document.getElementById(y),O)))throw"Canvas with id "+y+" was not found";if(y=this.GetWebGLContext(O,A),!y||0>y)throw"failed to create webgl context: err "+y;return y=this.MakeWebGLContext(y),v=this.MakeOnScreenGLSurface(y,O.width,O.height,v),v||(v=O.cloneNode(!0),O.parentNode.replaceChild(v,O),v.classList.add("ck-replaced"),e.MakeSWCanvasSurface(v))},e.MakeCanvasSurface=e.MakeWebGLCanvasSurface,e.Surface.prototype.makeImageFromTexture=function(y,v){return e.Md(this.Kd),y=s(y),(v=this._makeImageFromTexture(this.Kd,y,v))&&(v.Le=y),v},e.Surface.prototype.makeImageFromTextureSource=function(y,v,A){v||(v={height:l(y),width:d(y),colorType:e.ColorType.RGBA_8888,alphaType:A?e.AlphaType.Premul:e.AlphaType.Unpremul}),v.colorSpace||(v.colorSpace=e.ColorSpace.SRGB),e.Md(this.Kd);var O=rt.fe;return A=m(O,O.createTexture(),v,A),rt.version===2?O.texImage2D(O.TEXTURE_2D,0,O.RGBA,v.width,v.height,0,O.RGBA,O.UNSIGNED_BYTE,y):O.texImage2D(O.TEXTURE_2D,0,O.RGBA,O.RGBA,O.UNSIGNED_BYTE,y),P(O,v),this._resetContext(),this.makeImageFromTexture(A,v)},e.Surface.prototype.updateTextureFromSource=function(y,v,A){if(y.Le){e.Md(this.Kd);var O=y.getImageInfo(),D=rt.fe,K=m(D,Yt[y.Le],O,A);rt.version===2?D.texImage2D(D.TEXTURE_2D,0,D.RGBA,d(v),l(v),0,D.RGBA,D.UNSIGNED_BYTE,v):D.texImage2D(D.TEXTURE_2D,0,D.RGBA,D.RGBA,D.UNSIGNED_BYTE,v),P(D,O,A),this._resetContext(),Yt[y.Le]=null,y.Le=s(K),O.colorSpace=y.getColorSpace(),v=this._makeImageFromTexture(this.Kd,y.Le,O),A=y.Jd.Rd,D=y.Jd.Yd,y.Jd.Rd=v.Jd.Rd,y.Jd.Yd=v.Jd.Yd,v.Jd.Rd=A,v.Jd.Yd=D,v.delete(),O.colorSpace.delete()}},e.MakeLazyImageFromTextureSource=function(y,v,A){v||(v={height:l(y),width:d(y),colorType:e.ColorType.RGBA_8888,alphaType:A?e.AlphaType.Premul:e.AlphaType.Unpremul}),v.colorSpace||(v.colorSpace=e.ColorSpace.SRGB);var O={makeTexture:function(){var D=rt,K=D.fe,F=m(K,K.createTexture(),v,A);return D.version===2?K.texImage2D(K.TEXTURE_2D,0,K.RGBA,v.width,v.height,0,K.RGBA,K.UNSIGNED_BYTE,y):K.texImage2D(K.TEXTURE_2D,0,K.RGBA,K.RGBA,K.UNSIGNED_BYTE,y),P(K,v,A),s(F)},freeSrc:function(){}};return y.constructor.name==="VideoFrame"&&(O.freeSrc=function(){y.close()}),e.Image._makeFromGenerator(v,O)},e.Md=function(y){return y?Kr(y):!1},e.Te=function(){return rt&&rt.ff&&!rt.ff.isDeleted()?rt.ff:null}})}(h),function(e){function r(o,a,u,p,b){for(var _=0;_<o.length;_++)a[_*u+(_*b+p+u)%u]=o[_];return a}function s(o){for(var a=o*o,u=Array(a);a--;)u[a]=a%(o+1)===0?1:0;return u}function l(o){return o?o.constructor===Float32Array&&o.length===4:!1}function d(o){return(y(255*o[3])<<24|y(255*o[0])<<16|y(255*o[1])<<8|y(255*o[2])<<0)>>>0}function m(o){if(o&&o._ck)return o;if(o instanceof Float32Array){for(var a=Math.floor(o.length/4),u=new Uint32Array(a),p=0;p<a;p++)u[p]=d(o.slice(4*p,4*(p+1)));return u}if(o instanceof Uint32Array)return o;if(o instanceof Array&&o[0]instanceof Float32Array)return o.map(d)}function P(o){if(o===void 0)return 1;var a=parseFloat(o);return o&&o.indexOf("%")!==-1?a/100:a}function y(o){return Math.round(Math.max(0,Math.min(o||0,255)))}function v(o,a){a&&a._ck||e._free(o)}function A(o,a,u){if(!o||!o.length)return ft;if(o&&o._ck)return o.byteOffset;var p=e[a].BYTES_PER_ELEMENT;return u||(u=e._malloc(o.length*p)),e[a].set(o,u/p),u}function O(o){var a={be:ft,count:o.length,colorType:e.ColorType.RGBA_F32};if(o instanceof Float32Array)a.be=A(o,"HEAPF32"),a.count=o.length/4;else if(o instanceof Uint32Array)a.be=A(o,"HEAPU32"),a.colorType=e.ColorType.RGBA_8888;else if(o instanceof Array){if(o&&o.length){for(var u=e._malloc(16*o.length),p=0,b=u/4,_=0;_<o.length;_++)for(var N=0;4>N;N++)e.HEAPF32[b+p]=o[_][N],p++;o=u}else o=ft;a.be=o}else throw"Invalid argument to copyFlexibleColorArray, Not a color array "+typeof o;return a}function D(o){if(!o)return ft;var a=Zi.toTypedArray();if(o.length){if(o.length===6||o.length===9)return A(o,"HEAPF32",Ae),o.length===6&&e.HEAPF32.set(js,6+Ae/4),Ae;if(o.length===16)return a[0]=o[0],a[1]=o[1],a[2]=o[3],a[3]=o[4],a[4]=o[5],a[5]=o[7],a[6]=o[12],a[7]=o[13],a[8]=o[15],Ae;throw"invalid matrix size"}if(o.m11===void 0)throw"invalid matrix argument";return a[0]=o.m11,a[1]=o.m21,a[2]=o.m41,a[3]=o.m12,a[4]=o.m22,a[5]=o.m42,a[6]=o.m14,a[7]=o.m24,a[8]=o.m44,Ae}function K(o){if(!o)return ft;var a=tr.toTypedArray();if(o.length){if(o.length!==16&&o.length!==6&&o.length!==9)throw"invalid matrix size";return o.length===16?A(o,"HEAPF32",Be):(a.fill(0),a[0]=o[0],a[1]=o[1],a[3]=o[2],a[4]=o[3],a[5]=o[4],a[7]=o[5],a[10]=1,a[12]=o[6],a[13]=o[7],a[15]=o[8],o.length===6&&(a[12]=0,a[13]=0,a[15]=1),Be)}if(o.m11===void 0)throw"invalid matrix argument";return a[0]=o.m11,a[1]=o.m21,a[2]=o.m31,a[3]=o.m41,a[4]=o.m12,a[5]=o.m22,a[6]=o.m32,a[7]=o.m42,a[8]=o.m13,a[9]=o.m23,a[10]=o.m33,a[11]=o.m43,a[12]=o.m14,a[13]=o.m24,a[14]=o.m34,a[15]=o.m44,Be}function F(o,a){return A(o,"HEAPF32",a||xe)}function J(o,a,u,p){var b=er.toTypedArray();return b[0]=o,b[1]=a,b[2]=u,b[3]=p,xe}function st(o){for(var a=new Float32Array(4),u=0;4>u;u++)a[u]=e.HEAPF32[o/4+u];return a}function nt(o,a){return A(o,"HEAPF32",a||Ft)}function $t(o,a){return A(o,"HEAPF32",a||nr)}function kt(){for(var o=0,a=0;a<arguments.length-1;a+=2)o+=arguments[a]*arguments[a+1];return o}function ii(o,a,u){for(var p=Array(o.length),b=0;b<u;b++)for(var _=0;_<u;_++){for(var N=0,W=0;W<u;W++)N+=o[u*b+W]*a[u*W+_];p[b*u+_]=N}return p}function ri(o,a){for(var u=ii(a[0],a[1],o),p=2;p<a.length;)u=ii(u,a[p],o),p++;return u}e.Color=function(o,a,u,p){return p===void 0&&(p=1),e.Color4f(y(o)/255,y(a)/255,y(u)/255,p)},e.ColorAsInt=function(o,a,u,p){return p===void 0&&(p=255),(y(p)<<24|y(o)<<16|y(a)<<8|y(u)<<0&268435455)>>>0},e.Color4f=function(o,a,u,p){return p===void 0&&(p=1),Float32Array.of(o,a,u,p)},Object.defineProperty(e,"TRANSPARENT",{get:function(){return e.Color4f(0,0,0,0)}}),Object.defineProperty(e,"BLACK",{get:function(){return e.Color4f(0,0,0,1)}}),Object.defineProperty(e,"WHITE",{get:function(){return e.Color4f(1,1,1,1)}}),Object.defineProperty(e,"RED",{get:function(){return e.Color4f(1,0,0,1)}}),Object.defineProperty(e,"GREEN",{get:function(){return e.Color4f(0,1,0,1)}}),Object.defineProperty(e,"BLUE",{get:function(){return e.Color4f(0,0,1,1)}}),Object.defineProperty(e,"YELLOW",{get:function(){return e.Color4f(1,1,0,1)}}),Object.defineProperty(e,"CYAN",{get:function(){return e.Color4f(0,1,1,1)}}),Object.defineProperty(e,"MAGENTA",{get:function(){return e.Color4f(1,0,1,1)}}),e.getColorComponents=function(o){return[Math.floor(255*o[0]),Math.floor(255*o[1]),Math.floor(255*o[2]),o[3]]},e.parseColorString=function(o,a){if(o=o.toLowerCase(),o.startsWith("#")){switch(a=255,o.length){case 9:a=parseInt(o.slice(7,9),16);case 7:var u=parseInt(o.slice(1,3),16),p=parseInt(o.slice(3,5),16),b=parseInt(o.slice(5,7),16);break;case 5:a=17*parseInt(o.slice(4,5),16);case 4:u=17*parseInt(o.slice(1,2),16),p=17*parseInt(o.slice(2,3),16),b=17*parseInt(o.slice(3,4),16)}return e.Color(u,p,b,a/255)}return o.startsWith("rgba")?(o=o.slice(5,-1),o=o.split(","),e.Color(+o[0],+o[1],+o[2],P(o[3]))):o.startsWith("rgb")?(o=o.slice(4,-1),o=o.split(","),e.Color(+o[0],+o[1],+o[2],P(o[3]))):o.startsWith("gray(")||o.startsWith("hsl")||!a||(o=a[o],o===void 0)?e.BLACK:o},e.multiplyByAlpha=function(o,a){return o=o.slice(),o[3]=Math.max(0,Math.min(o[3]*a,1)),o},e.Malloc=function(o,a){var u=e._malloc(a*o.BYTES_PER_ELEMENT);return{_ck:!0,length:a,byteOffset:u,qe:null,subarray:function(p,b){return p=this.toTypedArray().subarray(p,b),p._ck=!0,p},toTypedArray:function(){return this.qe&&this.qe.length?this.qe:(this.qe=new o(e.HEAPU8.buffer,u,a),this.qe._ck=!0,this.qe)}}},e.Free=function(o){e._free(o.byteOffset),o.byteOffset=ft,o.toTypedArray=null,o.qe=null};var Ae=ft,Zi,Be=ft,tr,xe=ft,er,se,Ft=ft,an,Ce=ft,on,ir=ft,ln,rr=ft,xi,ni=ft,hn,nr=ft,cn,un=ft,js=Float32Array.of(0,0,1),ft=0;e.onRuntimeInitialized=function(){function o(a,u,p,b,_,N,W){N||(N=4*b.width,b.colorType===e.ColorType.RGBA_F16?N*=2:b.colorType===e.ColorType.RGBA_F32&&(N*=4));var Z=N*b.height,Q=_?_.byteOffset:e._malloc(Z);if(W?!a._readPixels(b,Q,N,u,p,W):!a._readPixels(b,Q,N,u,p))return _||e._free(Q),null;if(_)return _.toTypedArray();switch(b.colorType){case e.ColorType.RGBA_8888:case e.ColorType.RGBA_F16:a=new Uint8Array(e.HEAPU8.buffer,Q,Z).slice();break;case e.ColorType.RGBA_F32:a=new Float32Array(e.HEAPU8.buffer,Q,Z).slice();break;default:return null}return e._free(Q),a}er=e.Malloc(Float32Array,4),xe=er.byteOffset,tr=e.Malloc(Float32Array,16),Be=tr.byteOffset,Zi=e.Malloc(Float32Array,9),Ae=Zi.byteOffset,hn=e.Malloc(Float32Array,12),nr=hn.byteOffset,cn=e.Malloc(Float32Array,12),un=cn.byteOffset,se=e.Malloc(Float32Array,4),Ft=se.byteOffset,an=e.Malloc(Float32Array,4),Ce=an.byteOffset,on=e.Malloc(Float32Array,3),ir=on.byteOffset,ln=e.Malloc(Float32Array,3),rr=ln.byteOffset,xi=e.Malloc(Int32Array,4),ni=xi.byteOffset,e.ColorSpace.SRGB=e.ColorSpace._MakeSRGB(),e.ColorSpace.DISPLAY_P3=e.ColorSpace._MakeDisplayP3(),e.ColorSpace.ADOBE_RGB=e.ColorSpace._MakeAdobeRGB(),e.GlyphRunFlags={IsWhiteSpace:e._GlyphRunFlags_isWhiteSpace},e.Path.MakeFromCmds=function(a){var u=A(a,"HEAPF32"),p=e.Path._MakeFromCmds(u,a.length);return v(u,a),p},e.Path.MakeFromVerbsPointsWeights=function(a,u,p){var b=A(a,"HEAPU8"),_=A(u,"HEAPF32"),N=A(p,"HEAPF32"),W=e.Path._MakeFromVerbsPointsWeights(b,a.length,_,u.length,N,p&&p.length||0);return v(b,a),v(_,u),v(N,p),W},e.Path.prototype.addArc=function(a,u,p){return a=nt(a),this._addArc(a,u,p),this},e.Path.prototype.addCircle=function(a,u,p,b){return this._addCircle(a,u,p,!!b),this},e.Path.prototype.addOval=function(a,u,p){return p===void 0&&(p=1),a=nt(a),this._addOval(a,!!u,p),this},e.Path.prototype.addPath=function(){var a=Array.prototype.slice.call(arguments),u=a[0],p=!1;if(typeof a[a.length-1]=="boolean"&&(p=a.pop()),a.length===1)this._addPath(u,1,0,0,0,1,0,0,0,1,p);else if(a.length===2)a=a[1],this._addPath(u,a[0],a[1],a[2],a[3],a[4],a[5],a[6]||0,a[7]||0,a[8]||1,p);else if(a.length===7||a.length===10)this._addPath(u,a[1],a[2],a[3],a[4],a[5],a[6],a[7]||0,a[8]||0,a[9]||1,p);else return null;return this},e.Path.prototype.addPoly=function(a,u){var p=A(a,"HEAPF32");return this._addPoly(p,a.length/2,u),v(p,a),this},e.Path.prototype.addRect=function(a,u){return a=nt(a),this._addRect(a,!!u),this},e.Path.prototype.addRRect=function(a,u){return a=$t(a),this._addRRect(a,!!u),this},e.Path.prototype.addVerbsPointsWeights=function(a,u,p){var b=A(a,"HEAPU8"),_=A(u,"HEAPF32"),N=A(p,"HEAPF32");this._addVerbsPointsWeights(b,a.length,_,u.length,N,p&&p.length||0),v(b,a),v(_,u),v(N,p)},e.Path.prototype.arc=function(a,u,p,b,_,N){return a=e.LTRBRect(a-p,u-p,a+p,u+p),_=(_-b)/Math.PI*180-360*!!N,N=new e.Path,N.addArc(a,b/Math.PI*180,_),this.addPath(N,!0),N.delete(),this},e.Path.prototype.arcToOval=function(a,u,p,b){return a=nt(a),this._arcToOval(a,u,p,b),this},e.Path.prototype.arcToRotated=function(a,u,p,b,_,N,W){return this._arcToRotated(a,u,p,!!b,!!_,N,W),this},e.Path.prototype.arcToTangent=function(a,u,p,b,_){return this._arcToTangent(a,u,p,b,_),this},e.Path.prototype.close=function(){return this._close(),this},e.Path.prototype.conicTo=function(a,u,p,b,_){return this._conicTo(a,u,p,b,_),this},e.Path.prototype.computeTightBounds=function(a){this._computeTightBounds(Ft);var u=se.toTypedArray();return a?(a.set(u),a):u.slice()},e.Path.prototype.cubicTo=function(a,u,p,b,_,N){return this._cubicTo(a,u,p,b,_,N),this},e.Path.prototype.dash=function(a,u,p){return this._dash(a,u,p)?this:null},e.Path.prototype.getBounds=function(a){this._getBounds(Ft);var u=se.toTypedArray();return a?(a.set(u),a):u.slice()},e.Path.prototype.lineTo=function(a,u){return this._lineTo(a,u),this},e.Path.prototype.moveTo=function(a,u){return this._moveTo(a,u),this},e.Path.prototype.offset=function(a,u){return this._transform(1,0,a,0,1,u,0,0,1),this},e.Path.prototype.quadTo=function(a,u,p,b){return this._quadTo(a,u,p,b),this},e.Path.prototype.rArcTo=function(a,u,p,b,_,N,W){return this._rArcTo(a,u,p,b,_,N,W),this},e.Path.prototype.rConicTo=function(a,u,p,b,_){return this._rConicTo(a,u,p,b,_),this},e.Path.prototype.rCubicTo=function(a,u,p,b,_,N){return this._rCubicTo(a,u,p,b,_,N),this},e.Path.prototype.rLineTo=function(a,u){return this._rLineTo(a,u),this},e.Path.prototype.rMoveTo=function(a,u){return this._rMoveTo(a,u),this},e.Path.prototype.rQuadTo=function(a,u,p,b){return this._rQuadTo(a,u,p,b),this},e.Path.prototype.stroke=function(a){return a=a||{},a.width=a.width||1,a.miter_limit=a.miter_limit||4,a.cap=a.cap||e.StrokeCap.Butt,a.join=a.join||e.StrokeJoin.Miter,a.precision=a.precision||1,this._stroke(a)?this:null},e.Path.prototype.transform=function(){if(arguments.length===1){var a=arguments[0];this._transform(a[0],a[1],a[2],a[3],a[4],a[5],a[6]||0,a[7]||0,a[8]||1)}else if(arguments.length===6||arguments.length===9)a=arguments,this._transform(a[0],a[1],a[2],a[3],a[4],a[5],a[6]||0,a[7]||0,a[8]||1);else throw"transform expected to take 1 or 9 arguments. Got "+arguments.length;return this},e.Path.prototype.trim=function(a,u,p){return this._trim(a,u,!!p)?this:null},e.Image.prototype.encodeToBytes=function(a,u){var p=e.Te();return a=a||e.ImageFormat.PNG,u=u||100,p?this._encodeToBytes(a,u,p):this._encodeToBytes(a,u)},e.Image.prototype.makeShaderCubic=function(a,u,p,b,_){return _=D(_),this._makeShaderCubic(a,u,p,b,_)},e.Image.prototype.makeShaderOptions=function(a,u,p,b,_){return _=D(_),this._makeShaderOptions(a,u,p,b,_)},e.Image.prototype.readPixels=function(a,u,p,b,_){var N=e.Te();return o(this,a,u,p,b,_,N)},e.Canvas.prototype.clear=function(a){e.Md(this.Kd),a=F(a),this._clear(a)},e.Canvas.prototype.clipRRect=function(a,u,p){e.Md(this.Kd),a=$t(a),this._clipRRect(a,u,p)},e.Canvas.prototype.clipRect=function(a,u,p){e.Md(this.Kd),a=nt(a),this._clipRect(a,u,p)},e.Canvas.prototype.concat=function(a){e.Md(this.Kd),a=K(a),this._concat(a)},e.Canvas.prototype.drawArc=function(a,u,p,b,_){e.Md(this.Kd),a=nt(a),this._drawArc(a,u,p,b,_)},e.Canvas.prototype.drawAtlas=function(a,u,p,b,_,N,W){if(a&&b&&u&&p&&u.length===p.length){e.Md(this.Kd),_||(_=e.BlendMode.SrcOver);var Z=A(u,"HEAPF32"),Q=A(p,"HEAPF32"),pt=p.length/4,yt=A(m(N),"HEAPU32");if(W&&"B"in W&&"C"in W)this._drawAtlasCubic(a,Q,Z,yt,pt,_,W.B,W.C,b);else{let S=e.FilterMode.Linear,k=e.MipmapMode.None;W&&(S=W.filter,"mipmap"in W&&(k=W.mipmap)),this._drawAtlasOptions(a,Q,Z,yt,pt,_,S,k,b)}v(Z,u),v(Q,p),v(yt,N)}},e.Canvas.prototype.drawCircle=function(a,u,p,b){e.Md(this.Kd),this._drawCircle(a,u,p,b)},e.Canvas.prototype.drawColor=function(a,u){e.Md(this.Kd),a=F(a),u!==void 0?this._drawColor(a,u):this._drawColor(a)},e.Canvas.prototype.drawColorInt=function(a,u){e.Md(this.Kd),this._drawColorInt(a,u||e.BlendMode.SrcOver)},e.Canvas.prototype.drawColorComponents=function(a,u,p,b,_){e.Md(this.Kd),a=J(a,u,p,b),_!==void 0?this._drawColor(a,_):this._drawColor(a)},e.Canvas.prototype.drawDRRect=function(a,u,p){e.Md(this.Kd),a=$t(a,nr),u=$t(u,un),this._drawDRRect(a,u,p)},e.Canvas.prototype.drawImage=function(a,u,p,b){e.Md(this.Kd),this._drawImage(a,u,p,b||null)},e.Canvas.prototype.drawImageCubic=function(a,u,p,b,_,N){e.Md(this.Kd),this._drawImageCubic(a,u,p,b,_,N||null)},e.Canvas.prototype.drawImageOptions=function(a,u,p,b,_,N){e.Md(this.Kd),this._drawImageOptions(a,u,p,b,_,N||null)},e.Canvas.prototype.drawImageNine=function(a,u,p,b,_){e.Md(this.Kd),u=A(u,"HEAP32",ni),p=nt(p),this._drawImageNine(a,u,p,b,_||null)},e.Canvas.prototype.drawImageRect=function(a,u,p,b,_){e.Md(this.Kd),nt(u,Ft),nt(p,Ce),this._drawImageRect(a,Ft,Ce,b,!!_)},e.Canvas.prototype.drawImageRectCubic=function(a,u,p,b,_,N){e.Md(this.Kd),nt(u,Ft),nt(p,Ce),this._drawImageRectCubic(a,Ft,Ce,b,_,N||null)},e.Canvas.prototype.drawImageRectOptions=function(a,u,p,b,_,N){e.Md(this.Kd),nt(u,Ft),nt(p,Ce),this._drawImageRectOptions(a,Ft,Ce,b,_,N||null)},e.Canvas.prototype.drawLine=function(a,u,p,b,_){e.Md(this.Kd),this._drawLine(a,u,p,b,_)},e.Canvas.prototype.drawOval=function(a,u){e.Md(this.Kd),a=nt(a),this._drawOval(a,u)},e.Canvas.prototype.drawPaint=function(a){e.Md(this.Kd),this._drawPaint(a)},e.Canvas.prototype.drawParagraph=function(a,u,p){e.Md(this.Kd),this._drawParagraph(a,u,p)},e.Canvas.prototype.drawPatch=function(a,u,p,b,_){if(24>a.length)throw"Need 12 cubic points";if(u&&4>u.length)throw"Need 4 colors";if(p&&8>p.length)throw"Need 4 shader coordinates";e.Md(this.Kd);const N=A(a,"HEAPF32"),W=u?A(m(u),"HEAPU32"):ft,Z=p?A(p,"HEAPF32"):ft;b||(b=e.BlendMode.Modulate),this._drawPatch(N,W,Z,b,_),v(Z,p),v(W,u),v(N,a)},e.Canvas.prototype.drawPath=function(a,u){e.Md(this.Kd),this._drawPath(a,u)},e.Canvas.prototype.drawPicture=function(a){e.Md(this.Kd),this._drawPicture(a)},e.Canvas.prototype.drawPoints=function(a,u,p){e.Md(this.Kd);var b=A(u,"HEAPF32");this._drawPoints(a,b,u.length/2,p),v(b,u)},e.Canvas.prototype.drawRRect=function(a,u){e.Md(this.Kd),a=$t(a),this._drawRRect(a,u)},e.Canvas.prototype.drawRect=function(a,u){e.Md(this.Kd),a=nt(a),this._drawRect(a,u)},e.Canvas.prototype.drawRect4f=function(a,u,p,b,_){e.Md(this.Kd),this._drawRect4f(a,u,p,b,_)},e.Canvas.prototype.drawShadow=function(a,u,p,b,_,N,W){e.Md(this.Kd);var Z=A(_,"HEAPF32"),Q=A(N,"HEAPF32");u=A(u,"HEAPF32",ir),p=A(p,"HEAPF32",rr),this._drawShadow(a,u,p,b,Z,Q,W),v(Z,_),v(Q,N)},e.getShadowLocalBounds=function(a,u,p,b,_,N,W){return a=D(a),p=A(p,"HEAPF32",ir),b=A(b,"HEAPF32",rr),this._getShadowLocalBounds(a,u,p,b,_,N,Ft)?(u=se.toTypedArray(),W?(W.set(u),W):u.slice()):null},e.Canvas.prototype.drawTextBlob=function(a,u,p,b){e.Md(this.Kd),this._drawTextBlob(a,u,p,b)},e.Canvas.prototype.drawVertices=function(a,u,p){e.Md(this.Kd),this._drawVertices(a,u,p)},e.Canvas.prototype.getDeviceClipBounds=function(a){this._getDeviceClipBounds(ni);var u=xi.toTypedArray();return a?a.set(u):a=u.slice(),a},e.Canvas.prototype.getLocalToDevice=function(){this._getLocalToDevice(Be);for(var a=Be,u=Array(16),p=0;16>p;p++)u[p]=e.HEAPF32[a/4+p];return u},e.Canvas.prototype.getTotalMatrix=function(){this._getTotalMatrix(Ae);for(var a=Array(9),u=0;9>u;u++)a[u]=e.HEAPF32[Ae/4+u];return a},e.Canvas.prototype.makeSurface=function(a){return a=this._makeSurface(a),a.Kd=this.Kd,a},e.Canvas.prototype.readPixels=function(a,u,p,b,_){return e.Md(this.Kd),o(this,a,u,p,b,_)},e.Canvas.prototype.saveLayer=function(a,u,p,b){return u=nt(u),this._saveLayer(a||null,u,p||null,b||0)},e.Canvas.prototype.writePixels=function(a,u,p,b,_,N,W,Z){if(a.byteLength%(u*p))throw"pixels length must be a multiple of the srcWidth * srcHeight";e.Md(this.Kd);var Q=a.byteLength/(u*p);N=N||e.AlphaType.Unpremul,W=W||e.ColorType.RGBA_8888,Z=Z||e.ColorSpace.SRGB;var pt=Q*u;return Q=A(a,"HEAPU8"),u=this._writePixels({width:u,height:p,colorType:W,alphaType:N,colorSpace:Z},Q,pt,b,_),v(Q,a),u},e.ColorFilter.MakeBlend=function(a,u,p){return a=F(a),p=p||e.ColorSpace.SRGB,e.ColorFilter._MakeBlend(a,u,p)},e.ColorFilter.MakeMatrix=function(a){if(!a||a.length!==20)throw"invalid color matrix";var u=A(a,"HEAPF32"),p=e.ColorFilter._makeMatrix(u);return v(u,a),p},e.ContourMeasure.prototype.getPosTan=function(a,u){return this._getPosTan(a,Ft),a=se.toTypedArray(),u?(u.set(a),u):a.slice()},e.ImageFilter.prototype.getOutputBounds=function(a,u,p){return a=nt(a,Ft),u=D(u),this._getOutputBounds(a,u,ni),u=xi.toTypedArray(),p?(p.set(u),p):u.slice()},e.ImageFilter.MakeDropShadow=function(a,u,p,b,_,N){return _=F(_,xe),e.ImageFilter._MakeDropShadow(a,u,p,b,_,N)},e.ImageFilter.MakeDropShadowOnly=function(a,u,p,b,_,N){return _=F(_,xe),e.ImageFilter._MakeDropShadowOnly(a,u,p,b,_,N)},e.ImageFilter.MakeImage=function(a,u,p,b){if(p=nt(p,Ft),b=nt(b,Ce),"B"in u&&"C"in u)return e.ImageFilter._MakeImageCubic(a,u.B,u.C,p,b);const _=u.filter;let N=e.MipmapMode.None;return"mipmap"in u&&(N=u.mipmap),e.ImageFilter._MakeImageOptions(a,_,N,p,b)},e.ImageFilter.MakeMatrixTransform=function(a,u,p){if(a=D(a),"B"in u&&"C"in u)return e.ImageFilter._MakeMatrixTransformCubic(a,u.B,u.C,p);const b=u.filter;let _=e.MipmapMode.None;return"mipmap"in u&&(_=u.mipmap),e.ImageFilter._MakeMatrixTransformOptions(a,b,_,p)},e.Paint.prototype.getColor=function(){return this._getColor(xe),st(xe)},e.Paint.prototype.setColor=function(a,u){u=u||null,a=F(a),this._setColor(a,u)},e.Paint.prototype.setColorComponents=function(a,u,p,b,_){_=_||null,a=J(a,u,p,b),this._setColor(a,_)},e.Path.prototype.getPoint=function(a,u){return this._getPoint(a,Ft),a=se.toTypedArray(),u?(u[0]=a[0],u[1]=a[1],u):a.slice(0,2)},e.Picture.prototype.makeShader=function(a,u,p,b,_){return b=D(b),_=nt(_),this._makeShader(a,u,p,b,_)},e.Picture.prototype.cullRect=function(a){this._cullRect(Ft);var u=se.toTypedArray();return a?(a.set(u),a):u.slice()},e.PictureRecorder.prototype.beginRecording=function(a,u){return a=nt(a),this._beginRecording(a,!!u)},e.Surface.prototype.getCanvas=function(){var a=this._getCanvas();return a.Kd=this.Kd,a},e.Surface.prototype.makeImageSnapshot=function(a){return e.Md(this.Kd),a=A(a,"HEAP32",ni),this._makeImageSnapshot(a)},e.Surface.prototype.makeSurface=function(a){return e.Md(this.Kd),a=this._makeSurface(a),a.Kd=this.Kd,a},e.Surface.prototype.Gf=function(a,u){return this.He||(this.He=this.getCanvas()),requestAnimationFrame(function(){e.Md(this.Kd),a(this.He),this.flush(u)}.bind(this))},e.Surface.prototype.requestAnimationFrame||(e.Surface.prototype.requestAnimationFrame=e.Surface.prototype.Gf),e.Surface.prototype.Cf=function(a,u){this.He||(this.He=this.getCanvas()),requestAnimationFrame(function(){e.Md(this.Kd),a(this.He),this.flush(u),this.dispose()}.bind(this))},e.Surface.prototype.drawOnce||(e.Surface.prototype.drawOnce=e.Surface.prototype.Cf),e.PathEffect.MakeDash=function(a,u){if(u||(u=0),!a.length||a.length%2===1)throw"Intervals array must have even length";var p=A(a,"HEAPF32");return u=e.PathEffect._MakeDash(p,a.length,u),v(p,a),u},e.PathEffect.MakeLine2D=function(a,u){return u=D(u),e.PathEffect._MakeLine2D(a,u)},e.PathEffect.MakePath2D=function(a,u){return a=D(a),e.PathEffect._MakePath2D(a,u)},e.Shader.MakeColor=function(a,u){return u=u||null,a=F(a),e.Shader._MakeColor(a,u)},e.Shader.Blend=e.Shader.MakeBlend,e.Shader.Color=e.Shader.MakeColor,e.Shader.MakeLinearGradient=function(a,u,p,b,_,N,W,Z){Z=Z||null;var Q=O(p),pt=A(b,"HEAPF32");W=W||0,N=D(N);var yt=se.toTypedArray();return yt.set(a),yt.set(u,2),a=e.Shader._MakeLinearGradient(Ft,Q.be,Q.colorType,pt,Q.count,_,W,N,Z),v(Q.be,p),b&&v(pt,b),a},e.Shader.MakeRadialGradient=function(a,u,p,b,_,N,W,Z){Z=Z||null;var Q=O(p),pt=A(b,"HEAPF32");return W=W||0,N=D(N),a=e.Shader._MakeRadialGradient(a[0],a[1],u,Q.be,Q.colorType,pt,Q.count,_,W,N,Z),v(Q.be,p),b&&v(pt,b),a},e.Shader.MakeSweepGradient=function(a,u,p,b,_,N,W,Z,Q,pt){pt=pt||null;var yt=O(p),S=A(b,"HEAPF32");return W=W||0,Z=Z||0,Q=Q||360,N=D(N),a=e.Shader._MakeSweepGradient(a,u,yt.be,yt.colorType,S,yt.count,_,Z,Q,W,N,pt),v(yt.be,p),b&&v(S,b),a},e.Shader.MakeTwoPointConicalGradient=function(a,u,p,b,_,N,W,Z,Q,pt){pt=pt||null;var yt=O(_),S=A(N,"HEAPF32");Q=Q||0,Z=D(Z);var k=se.toTypedArray();return k.set(a),k.set(p,2),a=e.Shader._MakeTwoPointConicalGradient(Ft,u,b,yt.be,yt.colorType,S,yt.count,W,Q,Z,pt),v(yt.be,_),N&&v(S,N),a},e.Vertices.prototype.bounds=function(a){this._bounds(Ft);var u=se.toTypedArray();return a?(a.set(u),a):u.slice()},e.Td&&e.Td.forEach(function(a){a()})},e.computeTonalColors=function(o){var a=A(o.ambient,"HEAPF32"),u=A(o.spot,"HEAPF32");this._computeTonalColors(a,u);var p={ambient:st(a),spot:st(u)};return v(a,o.ambient),v(u,o.spot),p},e.LTRBRect=function(o,a,u,p){return Float32Array.of(o,a,u,p)},e.XYWHRect=function(o,a,u,p){return Float32Array.of(o,a,o+u,a+p)},e.LTRBiRect=function(o,a,u,p){return Int32Array.of(o,a,u,p)},e.XYWHiRect=function(o,a,u,p){return Int32Array.of(o,a,o+u,a+p)},e.RRectXY=function(o,a,u){return Float32Array.of(o[0],o[1],o[2],o[3],a,u,a,u,a,u,a,u)},e.MakeAnimatedImageFromEncoded=function(o){o=new Uint8Array(o);var a=e._malloc(o.byteLength);return e.HEAPU8.set(o,a),(o=e._decodeAnimatedImage(a,o.byteLength))?o:null},e.MakeImageFromEncoded=function(o){o=new Uint8Array(o);var a=e._malloc(o.byteLength);return e.HEAPU8.set(o,a),(o=e._decodeImage(a,o.byteLength))?o:null};var si=null;e.MakeImageFromCanvasImageSource=function(o){var a=o.width,u=o.height;si||(si=document.createElement("canvas")),si.width=a,si.height=u;var p=si.getContext("2d",{willReadFrequently:!0});return p.drawImage(o,0,0),o=p.getImageData(0,0,a,u),e.MakeImage({width:a,height:u,alphaType:e.AlphaType.Unpremul,colorType:e.ColorType.RGBA_8888,colorSpace:e.ColorSpace.SRGB},o.data,4*a)},e.MakeImage=function(o,a,u){var p=e._malloc(a.length);return e.HEAPU8.set(a,p),e._MakeImage(o,p,a.length,u)},e.MakeVertices=function(o,a,u,p,b,_){var N=b&&b.length||0,W=0;return u&&u.length&&(W|=1),p&&p.length&&(W|=2),_===void 0||_||(W|=4),o=new e._VerticesBuilder(o,a.length/2,N,W),A(a,"HEAPF32",o.positions()),o.texCoords()&&A(u,"HEAPF32",o.texCoords()),o.colors()&&A(m(p),"HEAPU32",o.colors()),o.indices()&&A(b,"HEAPU16",o.indices()),o.detach()},e.Matrix={},e.Matrix.identity=function(){return s(3)},e.Matrix.invert=function(o){var a=o[0]*o[4]*o[8]+o[1]*o[5]*o[6]+o[2]*o[3]*o[7]-o[2]*o[4]*o[6]-o[1]*o[3]*o[8]-o[0]*o[5]*o[7];return a?[(o[4]*o[8]-o[5]*o[7])/a,(o[2]*o[7]-o[1]*o[8])/a,(o[1]*o[5]-o[2]*o[4])/a,(o[5]*o[6]-o[3]*o[8])/a,(o[0]*o[8]-o[2]*o[6])/a,(o[2]*o[3]-o[0]*o[5])/a,(o[3]*o[7]-o[4]*o[6])/a,(o[1]*o[6]-o[0]*o[7])/a,(o[0]*o[4]-o[1]*o[3])/a]:null},e.Matrix.mapPoints=function(o,a){for(var u=0;u<a.length;u+=2){var p=a[u],b=a[u+1],_=o[6]*p+o[7]*b+o[8],N=o[3]*p+o[4]*b+o[5];a[u]=(o[0]*p+o[1]*b+o[2])/_,a[u+1]=N/_}return a},e.Matrix.multiply=function(){return ri(3,arguments)},e.Matrix.rotated=function(o,a,u){a=a||0,u=u||0;var p=Math.sin(o);return o=Math.cos(o),[o,-p,kt(p,u,1-o,a),p,o,kt(-p,a,1-o,u),0,0,1]},e.Matrix.scaled=function(o,a,u,p){u=u||0,p=p||0;var b=r([o,a],s(3),3,0,1);return r([u-o*u,p-a*p],b,3,2,0)},e.Matrix.skewed=function(o,a,u,p){u=u||0,p=p||0;var b=r([o,a],s(3),3,1,-1);return r([-o*u,-a*p],b,3,2,0)},e.Matrix.translated=function(o,a){return r(arguments,s(3),3,2,0)},e.Vector={},e.Vector.dot=function(o,a){return o.map(function(u,p){return u*a[p]}).reduce(function(u,p){return u+p})},e.Vector.lengthSquared=function(o){return e.Vector.dot(o,o)},e.Vector.length=function(o){return Math.sqrt(e.Vector.lengthSquared(o))},e.Vector.mulScalar=function(o,a){return o.map(function(u){return u*a})},e.Vector.add=function(o,a){return o.map(function(u,p){return u+a[p]})},e.Vector.sub=function(o,a){return o.map(function(u,p){return u-a[p]})},e.Vector.dist=function(o,a){return e.Vector.length(e.Vector.sub(o,a))},e.Vector.normalize=function(o){return e.Vector.mulScalar(o,1/e.Vector.length(o))},e.Vector.cross=function(o,a){return[o[1]*a[2]-o[2]*a[1],o[2]*a[0]-o[0]*a[2],o[0]*a[1]-o[1]*a[0]]},e.M44={},e.M44.identity=function(){return s(4)},e.M44.translated=function(o){return r(o,s(4),4,3,0)},e.M44.scaled=function(o){return r(o,s(4),4,0,1)},e.M44.rotated=function(o,a){return e.M44.rotatedUnitSinCos(e.Vector.normalize(o),Math.sin(a),Math.cos(a))},e.M44.rotatedUnitSinCos=function(o,a,u){var p=o[0],b=o[1];o=o[2];var _=1-u;return[_*p*p+u,_*p*b-a*o,_*p*o+a*b,0,_*p*b+a*o,_*b*b+u,_*b*o-a*p,0,_*p*o-a*b,_*b*o+a*p,_*o*o+u,0,0,0,0,1]},e.M44.lookat=function(o,a,u){a=e.Vector.normalize(e.Vector.sub(a,o)),u=e.Vector.normalize(u),u=e.Vector.normalize(e.Vector.cross(a,u));var p=e.M44.identity();return r(u,p,4,0,0),r(e.Vector.cross(u,a),p,4,1,0),r(e.Vector.mulScalar(a,-1),p,4,2,0),r(o,p,4,3,0),o=e.M44.invert(p),o===null?e.M44.identity():o},e.M44.perspective=function(o,a,u){var p=1/(a-o);return u/=2,u=Math.cos(u)/Math.sin(u),[u,0,0,0,0,u,0,0,0,0,(a+o)*p,2*a*o*p,0,0,-1,1]},e.M44.rc=function(o,a,u){return o[4*a+u]},e.M44.multiply=function(){return ri(4,arguments)},e.M44.invert=function(o){var a=o[0],u=o[4],p=o[8],b=o[12],_=o[1],N=o[5],W=o[9],Z=o[13],Q=o[2],pt=o[6],yt=o[10],S=o[14],k=o[3],ot=o[7],St=o[11];o=o[15];var Mt=a*N-u*_,Jt=a*W-p*_,Xt=a*Z-b*_,zt=u*W-p*N,L=u*Z-b*N,f=p*Z-b*W,w=Q*ot-pt*k,M=Q*St-yt*k,R=Q*o-S*k,I=pt*St-yt*ot,z=pt*o-S*ot,V=yt*o-S*St,Ct=Mt*V-Jt*z+Xt*I+zt*R-L*M+f*w,Et=1/Ct;return Ct===0||Et===1/0?null:(Mt*=Et,Jt*=Et,Xt*=Et,zt*=Et,L*=Et,f*=Et,w*=Et,M*=Et,R*=Et,I*=Et,z*=Et,V*=Et,a=[N*V-W*z+Z*I,W*R-_*V-Z*M,_*z-N*R+Z*w,N*M-_*I-W*w,p*z-u*V-b*I,a*V-p*R+b*M,u*R-a*z-b*w,a*I-u*M+p*w,ot*f-St*L+o*zt,St*Xt-k*f-o*Jt,k*L-ot*Xt+o*Mt,ot*Jt-k*zt-St*Mt,yt*L-pt*f-S*zt,Q*f-yt*Xt+S*Jt,pt*Xt-Q*L-S*Mt,Q*zt-pt*Jt+yt*Mt],a.every(function(ue){return!isNaN(ue)&&ue!==1/0&&ue!==-1/0})?a:null)},e.M44.transpose=function(o){return[o[0],o[4],o[8],o[12],o[1],o[5],o[9],o[13],o[2],o[6],o[10],o[14],o[3],o[7],o[11],o[15]]},e.M44.mustInvert=function(o){if(o=e.M44.invert(o),o===null)throw"Matrix not invertible";return o},e.M44.setupCamera=function(o,a,u){var p=e.M44.lookat(u.eye,u.coa,u.up);return u=e.M44.perspective(u.near,u.far,u.angle),a=[(o[2]-o[0])/2,(o[3]-o[1])/2,a],o=e.M44.multiply(e.M44.translated([(o[0]+o[2])/2,(o[1]+o[3])/2,0]),e.M44.scaled(a)),e.M44.multiply(o,u,p,e.M44.mustInvert(o))},e.ColorMatrix={},e.ColorMatrix.identity=function(){var o=new Float32Array(20);return o[0]=1,o[6]=1,o[12]=1,o[18]=1,o},e.ColorMatrix.scaled=function(o,a,u,p){var b=new Float32Array(20);return b[0]=o,b[6]=a,b[12]=u,b[18]=p,b};var Hs=[[6,7,11,12],[0,10,2,12],[0,1,5,6]];e.ColorMatrix.rotated=function(o,a,u){var p=e.ColorMatrix.identity();return o=Hs[o],p[o[0]]=u,p[o[1]]=a,p[o[2]]=-a,p[o[3]]=u,p},e.ColorMatrix.postTranslate=function(o,a,u,p,b){return o[4]+=a,o[9]+=u,o[14]+=p,o[19]+=b,o},e.ColorMatrix.concat=function(o,a){for(var u=new Float32Array(20),p=0,b=0;20>b;b+=5){for(var _=0;4>_;_++)u[p++]=o[b]*a[_]+o[b+1]*a[_+5]+o[b+2]*a[_+10]+o[b+3]*a[_+15];u[p++]=o[b]*a[4]+o[b+1]*a[9]+o[b+2]*a[14]+o[b+3]*a[19]+o[b+4]}return u},function(o){o.Td=o.Td||[],o.Td.push(function(){function a(S){return S&&(S.dir=S.dir===0?o.TextDirection.RTL:o.TextDirection.LTR),S}function u(S){if(!S||!S.length)return[];for(var k=[],ot=0;ot<S.length;ot+=5){var St=o.LTRBRect(S[ot],S[ot+1],S[ot+2],S[ot+3]),Mt=o.TextDirection.LTR;S[ot+4]===0&&(Mt=o.TextDirection.RTL),k.push({rect:St,dir:Mt})}return o._free(S.byteOffset),k}function p(S){return S=S||{},S.weight===void 0&&(S.weight=o.FontWeight.Normal),S.width=S.width||o.FontWidth.Normal,S.slant=S.slant||o.FontSlant.Upright,S}function b(S){if(!S||!S.length)return ft;for(var k=[],ot=0;ot<S.length;ot++){var St=_(S[ot]);k.push(St)}return A(k,"HEAPU32")}function _(S){if(Z[S])return Z[S];var k=ie(S)+1,ot=o._malloc(k);return ee(S,ht,ot,k),Z[S]=ot}function N(S){if(S._colorPtr=F(S.color),S._foregroundColorPtr=ft,S._backgroundColorPtr=ft,S._decorationColorPtr=ft,S.foregroundColor&&(S._foregroundColorPtr=F(S.foregroundColor,Q)),S.backgroundColor&&(S._backgroundColorPtr=F(S.backgroundColor,pt)),S.decorationColor&&(S._decorationColorPtr=F(S.decorationColor,yt)),Array.isArray(S.fontFamilies)&&S.fontFamilies.length?(S._fontFamiliesPtr=b(S.fontFamilies),S._fontFamiliesLen=S.fontFamilies.length):(S._fontFamiliesPtr=ft,S._fontFamiliesLen=0),S.locale){var k=S.locale;S._localePtr=_(k),S._localeLen=ie(k)+1}else S._localePtr=ft,S._localeLen=0;if(Array.isArray(S.shadows)&&S.shadows.length){k=S.shadows;var ot=k.map(function(L){return L.color||o.BLACK}),St=k.map(function(L){return L.blurRadius||0});S._shadowLen=k.length;for(var Mt=o._malloc(8*k.length),Jt=Mt/4,Xt=0;Xt<k.length;Xt++){var zt=k[Xt].offset||[0,0];o.HEAPF32[Jt]=zt[0],o.HEAPF32[Jt+1]=zt[1],Jt+=2}S._shadowColorsPtr=O(ot).be,S._shadowOffsetsPtr=Mt,S._shadowBlurRadiiPtr=A(St,"HEAPF32")}else S._shadowLen=0,S._shadowColorsPtr=ft,S._shadowOffsetsPtr=ft,S._shadowBlurRadiiPtr=ft;Array.isArray(S.fontFeatures)&&S.fontFeatures.length?(k=S.fontFeatures,ot=k.map(function(L){return L.name}),St=k.map(function(L){return L.value}),S._fontFeatureLen=k.length,S._fontFeatureNamesPtr=b(ot),S._fontFeatureValuesPtr=A(St,"HEAPU32")):(S._fontFeatureLen=0,S._fontFeatureNamesPtr=ft,S._fontFeatureValuesPtr=ft),Array.isArray(S.fontVariations)&&S.fontVariations.length?(k=S.fontVariations,ot=k.map(function(L){return L.axis}),St=k.map(function(L){return L.value}),S._fontVariationLen=k.length,S._fontVariationAxesPtr=b(ot),S._fontVariationValuesPtr=A(St,"HEAPF32")):(S._fontVariationLen=0,S._fontVariationAxesPtr=ft,S._fontVariationValuesPtr=ft)}function W(S){o._free(S._fontFamiliesPtr),o._free(S._shadowColorsPtr),o._free(S._shadowOffsetsPtr),o._free(S._shadowBlurRadiiPtr),o._free(S._fontFeatureNamesPtr),o._free(S._fontFeatureValuesPtr),o._free(S._fontVariationAxesPtr),o._free(S._fontVariationValuesPtr)}o.Paragraph.prototype.getRectsForRange=function(S,k,ot,St){return S=this._getRectsForRange(S,k,ot,St),u(S)},o.Paragraph.prototype.getRectsForPlaceholders=function(){var S=this._getRectsForPlaceholders();return u(S)},o.Paragraph.prototype.getGlyphInfoAt=function(S){return a(this._getGlyphInfoAt(S))},o.Paragraph.prototype.getClosestGlyphInfoAtCoordinate=function(S,k){return a(this._getClosestGlyphInfoAtCoordinate(S,k))},o.TypefaceFontProvider.prototype.registerFont=function(S,k){if(S=o.Typeface.MakeFreeTypeFaceFromData(S),!S)return null;k=_(k),this._registerFont(S,k)},o.ParagraphStyle=function(S){if(S.disableHinting=S.disableHinting||!1,S.ellipsis){var k=S.ellipsis;S._ellipsisPtr=_(k),S._ellipsisLen=ie(k)+1}else S._ellipsisPtr=ft,S._ellipsisLen=0;return S.heightMultiplier==null&&(S.heightMultiplier=-1),S.maxLines=S.maxLines||0,S.replaceTabCharacters=S.replaceTabCharacters||!1,k=(k=S.strutStyle)||{},k.strutEnabled=k.strutEnabled||!1,k.strutEnabled&&Array.isArray(k.fontFamilies)&&k.fontFamilies.length?(k._fontFamiliesPtr=b(k.fontFamilies),k._fontFamiliesLen=k.fontFamilies.length):(k._fontFamiliesPtr=ft,k._fontFamiliesLen=0),k.fontStyle=p(k.fontStyle),k.fontSize==null&&(k.fontSize=-1),k.heightMultiplier==null&&(k.heightMultiplier=-1),k.halfLeading=k.halfLeading||!1,k.leading=k.leading||0,k.forceStrutHeight=k.forceStrutHeight||!1,S.strutStyle=k,S.textAlign=S.textAlign||o.TextAlign.Start,S.textDirection=S.textDirection||o.TextDirection.LTR,S.textHeightBehavior=S.textHeightBehavior||o.TextHeightBehavior.All,S.textStyle=o.TextStyle(S.textStyle),S.applyRoundingHack=S.applyRoundingHack!==!1,S},o.TextStyle=function(S){return S.color||(S.color=o.BLACK),S.decoration=S.decoration||0,S.decorationThickness=S.decorationThickness||0,S.decorationStyle=S.decorationStyle||o.DecorationStyle.Solid,S.textBaseline=S.textBaseline||o.TextBaseline.Alphabetic,S.fontSize==null&&(S.fontSize=-1),S.letterSpacing=S.letterSpacing||0,S.wordSpacing=S.wordSpacing||0,S.heightMultiplier==null&&(S.heightMultiplier=-1),S.halfLeading=S.halfLeading||!1,S.fontStyle=p(S.fontStyle),S};var Z={},Q=o._malloc(16),pt=o._malloc(16),yt=o._malloc(16);o.ParagraphBuilder.Make=function(S,k){return N(S.textStyle),k=o.ParagraphBuilder._Make(S,k),W(S.textStyle),k},o.ParagraphBuilder.MakeFromFontProvider=function(S,k){return N(S.textStyle),k=o.ParagraphBuilder._MakeFromFontProvider(S,k),W(S.textStyle),k},o.ParagraphBuilder.MakeFromFontCollection=function(S,k){return N(S.textStyle),k=o.ParagraphBuilder._MakeFromFontCollection(S,k),W(S.textStyle),k},o.ParagraphBuilder.ShapeText=function(S,k,ot){let St=0;for(const Mt of k)St+=Mt.length;if(St!==S.length)throw"Accumulated block lengths must equal text.length";return o.ParagraphBuilder._ShapeText(S,k,ot)},o.ParagraphBuilder.prototype.pushStyle=function(S){N(S),this._pushStyle(S),W(S)},o.ParagraphBuilder.prototype.pushPaintStyle=function(S,k,ot){N(S),this._pushPaintStyle(S,k,ot),W(S)},o.ParagraphBuilder.prototype.addPlaceholder=function(S,k,ot,St,Mt){ot=ot||o.PlaceholderAlignment.Baseline,St=St||o.TextBaseline.Alphabetic,this._addPlaceholder(S||0,k||0,ot,St,Mt||0)},o.ParagraphBuilder.prototype.setWordsUtf8=function(S){var k=A(S,"HEAPU32");this._setWordsUtf8(k,S&&S.length||0),v(k,S)},o.ParagraphBuilder.prototype.setWordsUtf16=function(S){var k=A(S,"HEAPU32");this._setWordsUtf16(k,S&&S.length||0),v(k,S)},o.ParagraphBuilder.prototype.setGraphemeBreaksUtf8=function(S){var k=A(S,"HEAPU32");this._setGraphemeBreaksUtf8(k,S&&S.length||0),v(k,S)},o.ParagraphBuilder.prototype.setGraphemeBreaksUtf16=function(S){var k=A(S,"HEAPU32");this._setGraphemeBreaksUtf16(k,S&&S.length||0),v(k,S)},o.ParagraphBuilder.prototype.setLineBreaksUtf8=function(S){var k=A(S,"HEAPU32");this._setLineBreaksUtf8(k,S&&S.length||0),v(k,S)},o.ParagraphBuilder.prototype.setLineBreaksUtf16=function(S){var k=A(S,"HEAPU32");this._setLineBreaksUtf16(k,S&&S.length||0),v(k,S)}})}(h),e.Td=e.Td||[],e.Td.push(function(){e.Path.prototype.op=function(o,a){return this._op(o,a)?this:null},e.Path.prototype.simplify=function(){return this._simplify()?this:null}}),e.Td=e.Td||[],e.Td.push(function(){e.Canvas.prototype.drawText=function(o,a,u,p,b){var _=ie(o),N=e._malloc(_+1);ee(o,ht,N,_+1),this._drawSimpleText(N,_,a,u,b,p),e._free(N)},e.Canvas.prototype.drawGlyphs=function(o,a,u,p,b,_){if(!(2*o.length<=a.length))throw"Not enough positions for the array of gyphs";e.Md(this.Kd);const N=A(o,"HEAPU16"),W=A(a,"HEAPF32");this._drawGlyphs(o.length,N,W,u,p,b,_),v(W,a),v(N,o)},e.Font.prototype.getGlyphBounds=function(o,a,u){var p=A(o,"HEAPU16"),b=e._malloc(16*o.length);return this._getGlyphWidthBounds(p,o.length,ft,b,a||null),a=new Float32Array(e.HEAPU8.buffer,b,4*o.length),v(p,o),u?(u.set(a),e._free(b),u):(o=Float32Array.from(a),e._free(b),o)},e.Font.prototype.getGlyphIDs=function(o,a,u){a||(a=o.length);var p=ie(o)+1,b=e._malloc(p);return ee(o,ht,b,p),o=e._malloc(2*a),a=this._getGlyphIDs(b,p-1,a,o),e._free(b),0>a?(e._free(o),null):(b=new Uint16Array(e.HEAPU8.buffer,o,a),u?(u.set(b),e._free(o),u):(u=Uint16Array.from(b),e._free(o),u))},e.Font.prototype.getGlyphIntercepts=function(o,a,u,p){var b=A(o,"HEAPU16"),_=A(a,"HEAPF32");return this._getGlyphIntercepts(b,o.length,!(o&&o._ck),_,a.length,!(a&&a._ck),u,p)},e.Font.prototype.getGlyphWidths=function(o,a,u){var p=A(o,"HEAPU16"),b=e._malloc(4*o.length);return this._getGlyphWidthBounds(p,o.length,b,ft,a||null),a=new Float32Array(e.HEAPU8.buffer,b,o.length),v(p,o),u?(u.set(a),e._free(b),u):(o=Float32Array.from(a),e._free(b),o)},e.FontMgr.FromData=function(){if(!arguments.length)return null;var o=arguments;if(o.length===1&&Array.isArray(o[0])&&(o=arguments[0]),!o.length)return null;for(var a=[],u=[],p=0;p<o.length;p++){var b=new Uint8Array(o[p]),_=A(b,"HEAPU8");a.push(_),u.push(b.byteLength)}return a=A(a,"HEAPU32"),u=A(u,"HEAPU32"),o=e.FontMgr._fromData(a,u,o.length),e._free(a),e._free(u),o},e.Typeface.MakeFreeTypeFaceFromData=function(o){o=new Uint8Array(o);var a=A(o,"HEAPU8");return(o=e.Typeface._MakeFreeTypeFaceFromData(a,o.byteLength))?o:null},e.Typeface.prototype.getGlyphIDs=function(o,a,u){a||(a=o.length);var p=ie(o)+1,b=e._malloc(p);return ee(o,ht,b,p),o=e._malloc(2*a),a=this._getGlyphIDs(b,p-1,a,o),e._free(b),0>a?(e._free(o),null):(b=new Uint16Array(e.HEAPU8.buffer,o,a),u?(u.set(b),e._free(o),u):(u=Uint16Array.from(b),e._free(o),u))},e.TextBlob.MakeOnPath=function(o,a,u,p){if(o&&o.length&&a&&a.countPoints()){if(a.countPoints()===1)return this.MakeFromText(o,u);p||(p=0);var b=u.getGlyphIDs(o);b=u.getGlyphWidths(b);var _=[];a=new e.ContourMeasureIter(a,!1,1);for(var N=a.next(),W=new Float32Array(4),Z=0;Z<o.length&&N;Z++){var Q=b[Z];if(p+=Q/2,p>N.length()){if(N.delete(),N=a.next(),!N){o=o.substring(0,Z);break}p=Q/2}N.getPosTan(p,W);var pt=W[2],yt=W[3];_.push(pt,yt,W[0]-Q/2*pt,W[1]-Q/2*yt),p+=Q/2}return o=this.MakeFromRSXform(o,_,u),N&&N.delete(),a.delete(),o}},e.TextBlob.MakeFromRSXform=function(o,a,u){var p=ie(o)+1,b=e._malloc(p);return ee(o,ht,b,p),o=A(a,"HEAPF32"),u=e.TextBlob._MakeFromRSXform(b,p-1,o,u),e._free(b),u||null},e.TextBlob.MakeFromRSXformGlyphs=function(o,a,u){var p=A(o,"HEAPU16");return a=A(a,"HEAPF32"),u=e.TextBlob._MakeFromRSXformGlyphs(p,2*o.length,a,u),v(p,o),u||null},e.TextBlob.MakeFromGlyphs=function(o,a){var u=A(o,"HEAPU16");return a=e.TextBlob._MakeFromGlyphs(u,2*o.length,a),v(u,o),a||null},e.TextBlob.MakeFromText=function(o,a){var u=ie(o)+1,p=e._malloc(u);return ee(o,ht,p,u),o=e.TextBlob._MakeFromText(p,u-1,a),e._free(p),o||null},e.MallocGlyphIDs=function(o){return e.Malloc(Uint16Array,o)}}),e.Td=e.Td||[],e.Td.push(function(){e.MakePicture=function(o){o=new Uint8Array(o);var a=e._malloc(o.byteLength);return e.HEAPU8.set(o,a),(o=e._MakePicture(a,o.byteLength))?o:null}}),e.Td=e.Td||[],e.Td.push(function(){e.RuntimeEffect.Make=function(o,a){return e.RuntimeEffect._Make(o,{onError:a||function(u){console.log("RuntimeEffect error",u)}})},e.RuntimeEffect.MakeForBlender=function(o,a){return e.RuntimeEffect._MakeForBlender(o,{onError:a||function(u){console.log("RuntimeEffect error",u)}})},e.RuntimeEffect.prototype.makeShader=function(o,a){var u=!o._ck,p=A(o,"HEAPF32");return a=D(a),this._makeShader(p,4*o.length,u,a)},e.RuntimeEffect.prototype.makeShaderWithChildren=function(o,a,u){var p=!o._ck,b=A(o,"HEAPF32");u=D(u);for(var _=[],N=0;N<a.length;N++)_.push(a[N].Jd.Rd);return a=A(_,"HEAPU32"),this._makeShaderWithChildren(b,4*o.length,p,a,_.length,u)},e.RuntimeEffect.prototype.makeBlender=function(o){var a=!o._ck,u=A(o,"HEAPF32");return this._makeBlender(u,4*o.length,a)}}),function(){function o(L){for(var f=0;f<L.length;f++)if(L[f]!==void 0&&!Number.isFinite(L[f]))return!1;return!0}function a(L){var f=e.getColorComponents(L);L=f[0];var w=f[1],M=f[2];return f=f[3],f===1?(L=L.toString(16).toLowerCase(),w=w.toString(16).toLowerCase(),M=M.toString(16).toLowerCase(),L=L.length===1?"0"+L:L,w=w.length===1?"0"+w:w,M=M.length===1?"0"+M:M,"#"+L+w+M):(f=f===0||f===1?f:f.toFixed(8),"rgba("+L+", "+w+", "+M+", "+f+")")}function u(L){return e.parseColorString(L,Jt)}function p(L){if(L=Xt.exec(L),!L)return null;var f=parseFloat(L[4]),w=16;switch(L[5]){case"em":case"rem":w=16*f;break;case"pt":w=4*f/3;break;case"px":w=f;break;case"pc":w=16*f;break;case"in":w=96*f;break;case"cm":w=96*f/2.54;break;case"mm":w=3.7795275590551185*f;break;case"q":w=.9448818897637796*f;break;case"%":w=.21333333333333335*f}return{style:L[1],variant:L[2],weight:L[3],sizePx:w,family:L[6].trim()}}function b(L){this.Ld=L,this.Od=new e.Paint,this.Od.setAntiAlias(!0),this.Od.setStrokeMiter(10),this.Od.setStrokeCap(e.StrokeCap.Butt),this.Od.setStrokeJoin(e.StrokeJoin.Miter),this.Re="10px monospace",this.me=new e.Font(null,10),this.me.setSubpixel(!0),this.ae=this.ge=e.BLACK,this.ve=0,this.Je=e.TRANSPARENT,this.xe=this.we=0,this.Ke=this.ie=1,this.Ie=0,this.ue=[],this.Nd=e.BlendMode.SrcOver,this.Od.setStrokeWidth(this.Ke),this.Od.setBlendMode(this.Nd),this.Qd=new e.Path,this.Sd=e.Matrix.identity(),this.lf=[],this.Be=[],this.le=function(){this.Qd.delete(),this.Od.delete(),this.me.delete(),this.Be.forEach(function(f){f.le()})},Object.defineProperty(this,"currentTransform",{enumerable:!0,get:function(){return{a:this.Sd[0],c:this.Sd[1],e:this.Sd[2],b:this.Sd[3],d:this.Sd[4],f:this.Sd[5]}},set:function(f){f.a&&this.setTransform(f.a,f.b,f.c,f.d,f.e,f.f)}}),Object.defineProperty(this,"fillStyle",{enumerable:!0,get:function(){return l(this.ae)?a(this.ae):this.ae},set:function(f){typeof f=="string"?this.ae=u(f):f.te&&(this.ae=f)}}),Object.defineProperty(this,"font",{enumerable:!0,get:function(){return this.Re},set:function(f){var w=p(f),M=w.family;w.typeface=zt[M]?zt[M][(w.style||"normal")+"|"+(w.variant||"normal")+"|"+(w.weight||"normal")]||zt[M]["*"]:null,w&&(this.me.setSize(w.sizePx),this.me.setTypeface(w.typeface),this.Re=f)}}),Object.defineProperty(this,"globalAlpha",{enumerable:!0,get:function(){return this.ie},set:function(f){!isFinite(f)||0>f||1<f||(this.ie=f)}}),Object.defineProperty(this,"globalCompositeOperation",{enumerable:!0,get:function(){switch(this.Nd){case e.BlendMode.SrcOver:return"source-over";case e.BlendMode.DstOver:return"destination-over";case e.BlendMode.Src:return"copy";case e.BlendMode.Dst:return"destination";case e.BlendMode.Clear:return"clear";case e.BlendMode.SrcIn:return"source-in";case e.BlendMode.DstIn:return"destination-in";case e.BlendMode.SrcOut:return"source-out";case e.BlendMode.DstOut:return"destination-out";case e.BlendMode.SrcATop:return"source-atop";case e.BlendMode.DstATop:return"destination-atop";case e.BlendMode.Xor:return"xor";case e.BlendMode.Plus:return"lighter";case e.BlendMode.Multiply:return"multiply";case e.BlendMode.Screen:return"screen";case e.BlendMode.Overlay:return"overlay";case e.BlendMode.Darken:return"darken";case e.BlendMode.Lighten:return"lighten";case e.BlendMode.ColorDodge:return"color-dodge";case e.BlendMode.ColorBurn:return"color-burn";case e.BlendMode.HardLight:return"hard-light";case e.BlendMode.SoftLight:return"soft-light";case e.BlendMode.Difference:return"difference";case e.BlendMode.Exclusion:return"exclusion";case e.BlendMode.Hue:return"hue";case e.BlendMode.Saturation:return"saturation";case e.BlendMode.Color:return"color";case e.BlendMode.Luminosity:return"luminosity"}},set:function(f){switch(f){case"source-over":this.Nd=e.BlendMode.SrcOver;break;case"destination-over":this.Nd=e.BlendMode.DstOver;break;case"copy":this.Nd=e.BlendMode.Src;break;case"destination":this.Nd=e.BlendMode.Dst;break;case"clear":this.Nd=e.BlendMode.Clear;break;case"source-in":this.Nd=e.BlendMode.SrcIn;break;case"destination-in":this.Nd=e.BlendMode.DstIn;break;case"source-out":this.Nd=e.BlendMode.SrcOut;break;case"destination-out":this.Nd=e.BlendMode.DstOut;break;case"source-atop":this.Nd=e.BlendMode.SrcATop;break;case"destination-atop":this.Nd=e.BlendMode.DstATop;break;case"xor":this.Nd=e.BlendMode.Xor;break;case"lighter":this.Nd=e.BlendMode.Plus;break;case"plus-lighter":this.Nd=e.BlendMode.Plus;break;case"plus-darker":throw"plus-darker is not supported";case"multiply":this.Nd=e.BlendMode.Multiply;break;case"screen":this.Nd=e.BlendMode.Screen;break;case"overlay":this.Nd=e.BlendMode.Overlay;break;case"darken":this.Nd=e.BlendMode.Darken;break;case"lighten":this.Nd=e.BlendMode.Lighten;break;case"color-dodge":this.Nd=e.BlendMode.ColorDodge;break;case"color-burn":this.Nd=e.BlendMode.ColorBurn;break;case"hard-light":this.Nd=e.BlendMode.HardLight;break;case"soft-light":this.Nd=e.BlendMode.SoftLight;break;case"difference":this.Nd=e.BlendMode.Difference;break;case"exclusion":this.Nd=e.BlendMode.Exclusion;break;case"hue":this.Nd=e.BlendMode.Hue;break;case"saturation":this.Nd=e.BlendMode.Saturation;break;case"color":this.Nd=e.BlendMode.Color;break;case"luminosity":this.Nd=e.BlendMode.Luminosity;break;default:return}this.Od.setBlendMode(this.Nd)}}),Object.defineProperty(this,"imageSmoothingEnabled",{enumerable:!0,get:function(){return!0},set:function(){}}),Object.defineProperty(this,"imageSmoothingQuality",{enumerable:!0,get:function(){return"high"},set:function(){}}),Object.defineProperty(this,"lineCap",{enumerable:!0,get:function(){switch(this.Od.getStrokeCap()){case e.StrokeCap.Butt:return"butt";case e.StrokeCap.Round:return"round";case e.StrokeCap.Square:return"square"}},set:function(f){switch(f){case"butt":this.Od.setStrokeCap(e.StrokeCap.Butt);break;case"round":this.Od.setStrokeCap(e.StrokeCap.Round);break;case"square":this.Od.setStrokeCap(e.StrokeCap.Square)}}}),Object.defineProperty(this,"lineDashOffset",{enumerable:!0,get:function(){return this.Ie},set:function(f){isFinite(f)&&(this.Ie=f)}}),Object.defineProperty(this,"lineJoin",{enumerable:!0,get:function(){switch(this.Od.getStrokeJoin()){case e.StrokeJoin.Miter:return"miter";case e.StrokeJoin.Round:return"round";case e.StrokeJoin.Bevel:return"bevel"}},set:function(f){switch(f){case"miter":this.Od.setStrokeJoin(e.StrokeJoin.Miter);break;case"round":this.Od.setStrokeJoin(e.StrokeJoin.Round);break;case"bevel":this.Od.setStrokeJoin(e.StrokeJoin.Bevel)}}}),Object.defineProperty(this,"lineWidth",{enumerable:!0,get:function(){return this.Od.getStrokeWidth()},set:function(f){0>=f||!f||(this.Ke=f,this.Od.setStrokeWidth(f))}}),Object.defineProperty(this,"miterLimit",{enumerable:!0,get:function(){return this.Od.getStrokeMiter()},set:function(f){0>=f||!f||this.Od.setStrokeMiter(f)}}),Object.defineProperty(this,"shadowBlur",{enumerable:!0,get:function(){return this.ve},set:function(f){0>f||!isFinite(f)||(this.ve=f)}}),Object.defineProperty(this,"shadowColor",{enumerable:!0,get:function(){return a(this.Je)},set:function(f){this.Je=u(f)}}),Object.defineProperty(this,"shadowOffsetX",{enumerable:!0,get:function(){return this.we},set:function(f){isFinite(f)&&(this.we=f)}}),Object.defineProperty(this,"shadowOffsetY",{enumerable:!0,get:function(){return this.xe},set:function(f){isFinite(f)&&(this.xe=f)}}),Object.defineProperty(this,"strokeStyle",{enumerable:!0,get:function(){return a(this.ge)},set:function(f){typeof f=="string"?this.ge=u(f):f.te&&(this.ge=f)}}),this.arc=function(f,w,M,R,I,z){S(this.Qd,f,w,M,M,0,R,I,z)},this.arcTo=function(f,w,M,R,I){Q(this.Qd,f,w,M,R,I)},this.beginPath=function(){this.Qd.delete(),this.Qd=new e.Path},this.bezierCurveTo=function(f,w,M,R,I,z){var V=this.Qd;o([f,w,M,R,I,z])&&(V.isEmpty()&&V.moveTo(f,w),V.cubicTo(f,w,M,R,I,z))},this.clearRect=function(f,w,M,R){this.Od.setStyle(e.PaintStyle.Fill),this.Od.setBlendMode(e.BlendMode.Clear),this.Ld.drawRect(e.XYWHRect(f,w,M,R),this.Od),this.Od.setBlendMode(this.Nd)},this.clip=function(f,w){typeof f=="string"?(w=f,f=this.Qd):f&&f.af&&(f=f.Ud),f||(f=this.Qd),f=f.copy(),w&&w.toLowerCase()==="evenodd"?f.setFillType(e.FillType.EvenOdd):f.setFillType(e.FillType.Winding),this.Ld.clipPath(f,e.ClipOp.Intersect,!0),f.delete()},this.closePath=function(){pt(this.Qd)},this.createImageData=function(){if(arguments.length===1){var f=arguments[0];return new W(new Uint8ClampedArray(4*f.width*f.height),f.width,f.height)}if(arguments.length===2){f=arguments[0];var w=arguments[1];return new W(new Uint8ClampedArray(4*f*w),f,w)}throw"createImageData expects 1 or 2 arguments, got "+arguments.length},this.createLinearGradient=function(f,w,M,R){if(o(arguments)){var I=new Z(f,w,M,R);return this.Be.push(I),I}},this.createPattern=function(f,w){return f=new St(f,w),this.Be.push(f),f},this.createRadialGradient=function(f,w,M,R,I,z){if(o(arguments)){var V=new Mt(f,w,M,R,I,z);return this.Be.push(V),V}},this.drawImage=function(f){f instanceof N&&(f=f.tf());var w=this.Qe();if(arguments.length===3||arguments.length===5)var M=e.XYWHRect(arguments[1],arguments[2],arguments[3]||f.width(),arguments[4]||f.height()),R=e.XYWHRect(0,0,f.width(),f.height());else if(arguments.length===9)M=e.XYWHRect(arguments[5],arguments[6],arguments[7],arguments[8]),R=e.XYWHRect(arguments[1],arguments[2],arguments[3],arguments[4]);else throw"invalid number of args for drawImage, need 3, 5, or 9; got "+arguments.length;this.Ld.drawImageRect(f,R,M,w,!1),w.dispose()},this.ellipse=function(f,w,M,R,I,z,V,Ct){S(this.Qd,f,w,M,R,I,z,V,Ct)},this.Qe=function(){var f=this.Od.copy();if(f.setStyle(e.PaintStyle.Fill),l(this.ae)){var w=e.multiplyByAlpha(this.ae,this.ie);f.setColor(w)}else w=this.ae.te(this.Sd),f.setColor(e.Color(0,0,0,this.ie)),f.setShader(w);return f.dispose=function(){this.delete()},f},this.fill=function(f,w){if(typeof f=="string"?(w=f,f=this.Qd):f&&f.af&&(f=f.Ud),w==="evenodd")this.Qd.setFillType(e.FillType.EvenOdd);else{if(w!=="nonzero"&&w)throw"invalid fill rule";this.Qd.setFillType(e.FillType.Winding)}f||(f=this.Qd),w=this.Qe();var M=this.ye(w);M&&(this.Ld.save(),this.re(),this.Ld.drawPath(f,M),this.Ld.restore(),M.dispose()),this.Ld.drawPath(f,w),w.dispose()},this.fillRect=function(f,w,M,R){var I=this.Qe(),z=this.ye(I);z&&(this.Ld.save(),this.re(),this.Ld.drawRect(e.XYWHRect(f,w,M,R),z),this.Ld.restore(),z.dispose()),this.Ld.drawRect(e.XYWHRect(f,w,M,R),I),I.dispose()},this.fillText=function(f,w,M){var R=this.Qe();f=e.TextBlob.MakeFromText(f,this.me);var I=this.ye(R);I&&(this.Ld.save(),this.re(),this.Ld.drawTextBlob(f,w,M,I),this.Ld.restore(),I.dispose()),this.Ld.drawTextBlob(f,w,M,R),f.delete(),R.dispose()},this.getImageData=function(f,w,M,R){return(f=this.Ld.readPixels(f,w,{width:M,height:R,colorType:e.ColorType.RGBA_8888,alphaType:e.AlphaType.Unpremul,colorSpace:e.ColorSpace.SRGB}))?new W(new Uint8ClampedArray(f.buffer),M,R):null},this.getLineDash=function(){return this.ue.slice()},this.mf=function(f){var w=e.Matrix.invert(this.Sd);return e.Matrix.mapPoints(w,f),f},this.isPointInPath=function(f,w,M){var R=arguments;if(R.length===3)var I=this.Qd;else if(R.length===4)I=R[0],f=R[1],w=R[2],M=R[3];else throw"invalid arg count, need 3 or 4, got "+R.length;return!isFinite(f)||!isFinite(w)||(M=M||"nonzero",M!=="nonzero"&&M!=="evenodd")?!1:(R=this.mf([f,w]),f=R[0],w=R[1],I.setFillType(M==="nonzero"?e.FillType.Winding:e.FillType.EvenOdd),I.contains(f,w))},this.isPointInStroke=function(f,w){var M=arguments;if(M.length===2)var R=this.Qd;else if(M.length===3)R=M[0],f=M[1],w=M[2];else throw"invalid arg count, need 2 or 3, got "+M.length;return!isFinite(f)||!isFinite(w)?!1:(M=this.mf([f,w]),f=M[0],w=M[1],R=R.copy(),R.setFillType(e.FillType.Winding),R.stroke({width:this.lineWidth,miter_limit:this.miterLimit,cap:this.Od.getStrokeCap(),join:this.Od.getStrokeJoin(),precision:.3}),M=R.contains(f,w),R.delete(),M)},this.lineTo=function(f,w){k(this.Qd,f,w)},this.measureText=function(f){f=this.me.getGlyphIDs(f),f=this.me.getGlyphWidths(f);let w=0;for(const M of f)w+=M;return{width:w}},this.moveTo=function(f,w){var M=this.Qd;o([f,w])&&M.moveTo(f,w)},this.putImageData=function(f,w,M,R,I,z,V){if(o([w,M,R,I,z,V])){if(R===void 0)this.Ld.writePixels(f.data,f.width,f.height,w,M);else if(R=R||0,I=I||0,z=z||f.width,V=V||f.height,0>z&&(R+=z,z=Math.abs(z)),0>V&&(I+=V,V=Math.abs(V)),0>R&&(z+=R,R=0),0>I&&(V+=I,I=0),!(0>=z||0>=V)){f=e.MakeImage({width:f.width,height:f.height,alphaType:e.AlphaType.Unpremul,colorType:e.ColorType.RGBA_8888,colorSpace:e.ColorSpace.SRGB},f.data,4*f.width);var Ct=e.XYWHRect(R,I,z,V);w=e.XYWHRect(w+R,M+I,z,V),M=e.Matrix.invert(this.Sd),this.Ld.save(),this.Ld.concat(M),this.Ld.drawImageRect(f,Ct,w,null,!1),this.Ld.restore(),f.delete()}}},this.quadraticCurveTo=function(f,w,M,R){var I=this.Qd;o([f,w,M,R])&&(I.isEmpty()&&I.moveTo(f,w),I.quadTo(f,w,M,R))},this.rect=function(f,w,M,R){var I=this.Qd;f=e.XYWHRect(f,w,M,R),o(f)&&I.addRect(f)},this.resetTransform=function(){this.Qd.transform(this.Sd);var f=e.Matrix.invert(this.Sd);this.Ld.concat(f),this.Sd=this.Ld.getTotalMatrix()},this.restore=function(){var f=this.lf.pop();if(f){var w=e.Matrix.multiply(this.Sd,e.Matrix.invert(f.Jf));this.Qd.transform(w),this.Od.delete(),this.Od=f.ag,this.ue=f.Zf,this.Ke=f.mg,this.ge=f.lg,this.ae=f.fs,this.we=f.jg,this.xe=f.kg,this.ve=f.sb,this.Je=f.ig,this.ie=f.ga,this.Nd=f.Qf,this.Ie=f.$f,this.Re=f.Pf,this.Ld.restore(),this.Sd=this.Ld.getTotalMatrix()}},this.rotate=function(f){if(isFinite(f)){var w=e.Matrix.rotated(-f);this.Qd.transform(w),this.Ld.rotate(f/Math.PI*180,0,0),this.Sd=this.Ld.getTotalMatrix()}},this.save=function(){if(this.ae.se){var f=this.ae.se();this.Be.push(f)}else f=this.ae;if(this.ge.se){var w=this.ge.se();this.Be.push(w)}else w=this.ge;this.lf.push({Jf:this.Sd.slice(),Zf:this.ue.slice(),mg:this.Ke,lg:w,fs:f,jg:this.we,kg:this.xe,sb:this.ve,ig:this.Je,ga:this.ie,$f:this.Ie,Qf:this.Nd,ag:this.Od.copy(),Pf:this.Re}),this.Ld.save()},this.scale=function(f,w){if(o(arguments)){var M=e.Matrix.scaled(1/f,1/w);this.Qd.transform(M),this.Ld.scale(f,w),this.Sd=this.Ld.getTotalMatrix()}},this.setLineDash=function(f){for(var w=0;w<f.length;w++)if(!isFinite(f[w])||0>f[w])return;f.length%2===1&&Array.prototype.push.apply(f,f),this.ue=f},this.setTransform=function(f,w,M,R,I,z){o(arguments)&&(this.resetTransform(),this.transform(f,w,M,R,I,z))},this.re=function(){var f=e.Matrix.invert(this.Sd);this.Ld.concat(f),this.Ld.concat(e.Matrix.translated(this.we,this.xe)),this.Ld.concat(this.Sd)},this.ye=function(f){var w=e.multiplyByAlpha(this.Je,this.ie);if(!e.getColorComponents(w)[3]||!(this.ve||this.xe||this.we))return null;f=f.copy(),f.setColor(w);var M=e.MaskFilter.MakeBlur(e.BlurStyle.Normal,this.ve/2,!1);return f.setMaskFilter(M),f.dispose=function(){M.delete(),this.delete()},f},this.cf=function(){var f=this.Od.copy();if(f.setStyle(e.PaintStyle.Stroke),l(this.ge)){var w=e.multiplyByAlpha(this.ge,this.ie);f.setColor(w)}else w=this.ge.te(this.Sd),f.setColor(e.Color(0,0,0,this.ie)),f.setShader(w);if(f.setStrokeWidth(this.Ke),this.ue.length){var M=e.PathEffect.MakeDash(this.ue,this.Ie);f.setPathEffect(M)}return f.dispose=function(){M&&M.delete(),this.delete()},f},this.stroke=function(f){f=f?f.Ud:this.Qd;var w=this.cf(),M=this.ye(w);M&&(this.Ld.save(),this.re(),this.Ld.drawPath(f,M),this.Ld.restore(),M.dispose()),this.Ld.drawPath(f,w),w.dispose()},this.strokeRect=function(f,w,M,R){var I=this.cf(),z=this.ye(I);z&&(this.Ld.save(),this.re(),this.Ld.drawRect(e.XYWHRect(f,w,M,R),z),this.Ld.restore(),z.dispose()),this.Ld.drawRect(e.XYWHRect(f,w,M,R),I),I.dispose()},this.strokeText=function(f,w,M){var R=this.cf();f=e.TextBlob.MakeFromText(f,this.me);var I=this.ye(R);I&&(this.Ld.save(),this.re(),this.Ld.drawTextBlob(f,w,M,I),this.Ld.restore(),I.dispose()),this.Ld.drawTextBlob(f,w,M,R),f.delete(),R.dispose()},this.translate=function(f,w){if(o(arguments)){var M=e.Matrix.translated(-f,-w);this.Qd.transform(M),this.Ld.translate(f,w),this.Sd=this.Ld.getTotalMatrix()}},this.transform=function(f,w,M,R,I,z){f=[f,M,I,w,R,z,0,0,1],w=e.Matrix.invert(f),this.Qd.transform(w),this.Ld.concat(f),this.Sd=this.Ld.getTotalMatrix()},this.addHitRegion=function(){},this.clearHitRegions=function(){},this.drawFocusIfNeeded=function(){},this.removeHitRegion=function(){},this.scrollPathIntoView=function(){},Object.defineProperty(this,"canvas",{value:null,writable:!1})}function _(L){this.df=L,this.Kd=new b(L.getCanvas()),this.Se=[],this.decodeImage=function(f){if(f=e.MakeImageFromEncoded(f),!f)throw"Invalid input";return this.Se.push(f),new N(f)},this.loadFont=function(f,w){if(f=e.Typeface.MakeFreeTypeFaceFromData(f),!f)return null;this.Se.push(f);var M=(w.style||"normal")+"|"+(w.variant||"normal")+"|"+(w.weight||"normal");w=w.family,zt[w]||(zt[w]={"*":f}),zt[w][M]=f},this.makePath2D=function(f){return f=new ot(f),this.Se.push(f.Ud),f},this.getContext=function(f){return f==="2d"?this.Kd:null},this.toDataURL=function(f,w){this.df.flush();var M=this.df.makeImageSnapshot();if(M){f=f||"image/png";var R=e.ImageFormat.PNG;if(f==="image/jpeg"&&(R=e.ImageFormat.JPEG),w=M.encodeToBytes(R,w||.92)){if(M.delete(),f="data:"+f+";base64,",typeof Buffer<"u")w=Buffer.from(w).toString("base64");else{M=0,R=w.length;for(var I="",z;M<R;)z=w.slice(M,Math.min(M+32768,R)),I+=String.fromCharCode.apply(null,z),M+=32768;w=btoa(I)}return f+w}}},this.dispose=function(){this.Kd.le(),this.Se.forEach(function(f){f.delete()}),this.df.dispose()}}function N(L){this.width=L.width(),this.height=L.height(),this.naturalWidth=this.width,this.naturalHeight=this.height,this.tf=function(){return L}}function W(L,f,w){if(!f||w===0)throw"invalid dimensions, width and height must be non-zero";if(L.length%4)throw"arr must be a multiple of 4";w=w||L.length/(4*f),Object.defineProperty(this,"data",{value:L,writable:!1}),Object.defineProperty(this,"height",{value:w,writable:!1}),Object.defineProperty(this,"width",{value:f,writable:!1})}function Z(L,f,w,M){this.Wd=null,this.ce=[],this.Zd=[],this.addColorStop=function(R,I){if(0>R||1<R||!isFinite(R))throw"offset must be between 0 and 1 inclusively";I=u(I);var z=this.Zd.indexOf(R);if(z!==-1)this.ce[z]=I;else{for(z=0;z<this.Zd.length&&!(this.Zd[z]>R);z++);this.Zd.splice(z,0,R),this.ce.splice(z,0,I)}},this.se=function(){var R=new Z(L,f,w,M);return R.ce=this.ce.slice(),R.Zd=this.Zd.slice(),R},this.le=function(){this.Wd&&(this.Wd.delete(),this.Wd=null)},this.te=function(R){var I=[L,f,w,M];e.Matrix.mapPoints(R,I),R=I[0];var z=I[1],V=I[2];return I=I[3],this.le(),this.Wd=e.Shader.MakeLinearGradient([R,z],[V,I],this.ce,this.Zd,e.TileMode.Clamp)}}function Q(L,f,w,M,R,I){if(o([f,w,M,R,I])){if(0>I)throw"radii cannot be negative";L.isEmpty()&&L.moveTo(f,w),L.arcToTangent(f,w,M,R,I)}}function pt(L){if(!L.isEmpty()){var f=L.getBounds();(f[3]-f[1]||f[2]-f[0])&&L.close()}}function yt(L,f,w,M,R,I,z){z=(z-I)/Math.PI*180,I=I/Math.PI*180,f=e.LTRBRect(f-M,w-R,f+M,w+R),1e-5>Math.abs(Math.abs(z)-360)?(w=z/2,L.arcToOval(f,I,w,!1),L.arcToOval(f,I+w,w,!1)):L.arcToOval(f,I,z,!1)}function S(L,f,w,M,R,I,z,V,Ct){if(o([f,w,M,R,I,z,V])){if(0>M||0>R)throw"radii cannot be negative";var Et=2*Math.PI,ue=z%Et;0>ue&&(ue+=Et);var ai=ue-z;z=ue,V+=ai,!Ct&&V-z>=Et?V=z+Et:Ct&&z-V>=Et?V=z-Et:!Ct&&z>V?V=z+(Et-(z-V)%Et):Ct&&z<V&&(V=z-(Et-(V-z)%Et)),I?(Ct=e.Matrix.rotated(I,f,w),I=e.Matrix.rotated(-I,f,w),L.transform(I),yt(L,f,w,M,R,z,V),L.transform(Ct)):yt(L,f,w,M,R,z,V)}}function k(L,f,w){o([f,w])&&(L.isEmpty()&&L.moveTo(f,w),L.lineTo(f,w))}function ot(L){this.Ud=null,this.Ud=typeof L=="string"?e.Path.MakeFromSVGString(L):L&&L.af?L.Ud.copy():new e.Path,this.af=function(){return this.Ud},this.addPath=function(f,w){w||(w={a:1,c:0,e:0,b:0,d:1,f:0}),this.Ud.addPath(f.Ud,[w.a,w.c,w.e,w.b,w.d,w.f])},this.arc=function(f,w,M,R,I,z){S(this.Ud,f,w,M,M,0,R,I,z)},this.arcTo=function(f,w,M,R,I){Q(this.Ud,f,w,M,R,I)},this.bezierCurveTo=function(f,w,M,R,I,z){var V=this.Ud;o([f,w,M,R,I,z])&&(V.isEmpty()&&V.moveTo(f,w),V.cubicTo(f,w,M,R,I,z))},this.closePath=function(){pt(this.Ud)},this.ellipse=function(f,w,M,R,I,z,V,Ct){S(this.Ud,f,w,M,R,I,z,V,Ct)},this.lineTo=function(f,w){k(this.Ud,f,w)},this.moveTo=function(f,w){var M=this.Ud;o([f,w])&&M.moveTo(f,w)},this.quadraticCurveTo=function(f,w,M,R){var I=this.Ud;o([f,w,M,R])&&(I.isEmpty()&&I.moveTo(f,w),I.quadTo(f,w,M,R))},this.rect=function(f,w,M,R){var I=this.Ud;f=e.XYWHRect(f,w,M,R),o(f)&&I.addRect(f)}}function St(L,f){switch(this.Wd=null,L instanceof N&&(L=L.tf()),this.Ef=L,this._transform=e.Matrix.identity(),f===""&&(f="repeat"),f){case"repeat-x":this.ze=e.TileMode.Repeat,this.Ae=e.TileMode.Decal;break;case"repeat-y":this.ze=e.TileMode.Decal,this.Ae=e.TileMode.Repeat;break;case"repeat":this.Ae=this.ze=e.TileMode.Repeat;break;case"no-repeat":this.Ae=this.ze=e.TileMode.Decal;break;default:throw"invalid repetition mode "+f}this.setTransform=function(w){w=[w.a,w.c,w.e,w.b,w.d,w.f,0,0,1],o(w)&&(this._transform=w)},this.se=function(){var w=new St;return w.ze=this.ze,w.Ae=this.Ae,w},this.le=function(){this.Wd&&(this.Wd.delete(),this.Wd=null)},this.te=function(){return this.le(),this.Wd=this.Ef.makeShaderCubic(this.ze,this.Ae,.3333333333333333,.3333333333333333,this._transform)}}function Mt(L,f,w,M,R,I){this.Wd=null,this.ce=[],this.Zd=[],this.addColorStop=function(z,V){if(0>z||1<z||!isFinite(z))throw"offset must be between 0 and 1 inclusively";V=u(V);var Ct=this.Zd.indexOf(z);if(Ct!==-1)this.ce[Ct]=V;else{for(Ct=0;Ct<this.Zd.length&&!(this.Zd[Ct]>z);Ct++);this.Zd.splice(Ct,0,z),this.ce.splice(Ct,0,V)}},this.se=function(){var z=new Mt(L,f,w,M,R,I);return z.ce=this.ce.slice(),z.Zd=this.Zd.slice(),z},this.le=function(){this.Wd&&(this.Wd.delete(),this.Wd=null)},this.te=function(z){var V=[L,f,M,R];e.Matrix.mapPoints(z,V);var Ct=V[0],Et=V[1],ue=V[2];V=V[3];var ai=(Math.abs(z[0])+Math.abs(z[4]))/2;return z=w*ai,ai*=I,this.le(),this.Wd=e.Shader.MakeTwoPointConicalGradient([Ct,Et],z,[ue,V],ai,this.ce,this.Zd,e.TileMode.Clamp)}}e._testing={};var Jt={aliceblue:Float32Array.of(.941,.973,1,1),antiquewhite:Float32Array.of(.98,.922,.843,1),aqua:Float32Array.of(0,1,1,1),aquamarine:Float32Array.of(.498,1,.831,1),azure:Float32Array.of(.941,1,1,1),beige:Float32Array.of(.961,.961,.863,1),bisque:Float32Array.of(1,.894,.769,1),black:Float32Array.of(0,0,0,1),blanchedalmond:Float32Array.of(1,.922,.804,1),blue:Float32Array.of(0,0,1,1),blueviolet:Float32Array.of(.541,.169,.886,1),brown:Float32Array.of(.647,.165,.165,1),burlywood:Float32Array.of(.871,.722,.529,1),cadetblue:Float32Array.of(.373,.62,.627,1),chartreuse:Float32Array.of(.498,1,0,1),chocolate:Float32Array.of(.824,.412,.118,1),coral:Float32Array.of(1,.498,.314,1),cornflowerblue:Float32Array.of(.392,.584,.929,1),cornsilk:Float32Array.of(1,.973,.863,1),crimson:Float32Array.of(.863,.078,.235,1),cyan:Float32Array.of(0,1,1,1),darkblue:Float32Array.of(0,0,.545,1),darkcyan:Float32Array.of(0,.545,.545,1),darkgoldenrod:Float32Array.of(.722,.525,.043,1),darkgray:Float32Array.of(.663,.663,.663,1),darkgreen:Float32Array.of(0,.392,0,1),darkgrey:Float32Array.of(.663,.663,.663,1),darkkhaki:Float32Array.of(.741,.718,.42,1),darkmagenta:Float32Array.of(.545,0,.545,1),darkolivegreen:Float32Array.of(.333,.42,.184,1),darkorange:Float32Array.of(1,.549,0,1),darkorchid:Float32Array.of(.6,.196,.8,1),darkred:Float32Array.of(.545,0,0,1),darksalmon:Float32Array.of(.914,.588,.478,1),darkseagreen:Float32Array.of(.561,.737,.561,1),darkslateblue:Float32Array.of(.282,.239,.545,1),darkslategray:Float32Array.of(.184,.31,.31,1),darkslategrey:Float32Array.of(.184,.31,.31,1),darkturquoise:Float32Array.of(0,.808,.82,1),darkviolet:Float32Array.of(.58,0,.827,1),deeppink:Float32Array.of(1,.078,.576,1),deepskyblue:Float32Array.of(0,.749,1,1),dimgray:Float32Array.of(.412,.412,.412,1),dimgrey:Float32Array.of(.412,.412,.412,1),dodgerblue:Float32Array.of(.118,.565,1,1),firebrick:Float32Array.of(.698,.133,.133,1),floralwhite:Float32Array.of(1,.98,.941,1),forestgreen:Float32Array.of(.133,.545,.133,1),fuchsia:Float32Array.of(1,0,1,1),gainsboro:Float32Array.of(.863,.863,.863,1),ghostwhite:Float32Array.of(.973,.973,1,1),gold:Float32Array.of(1,.843,0,1),goldenrod:Float32Array.of(.855,.647,.125,1),gray:Float32Array.of(.502,.502,.502,1),green:Float32Array.of(0,.502,0,1),greenyellow:Float32Array.of(.678,1,.184,1),grey:Float32Array.of(.502,.502,.502,1),honeydew:Float32Array.of(.941,1,.941,1),hotpink:Float32Array.of(1,.412,.706,1),indianred:Float32Array.of(.804,.361,.361,1),indigo:Float32Array.of(.294,0,.51,1),ivory:Float32Array.of(1,1,.941,1),khaki:Float32Array.of(.941,.902,.549,1),lavender:Float32Array.of(.902,.902,.98,1),lavenderblush:Float32Array.of(1,.941,.961,1),lawngreen:Float32Array.of(.486,.988,0,1),lemonchiffon:Float32Array.of(1,.98,.804,1),lightblue:Float32Array.of(.678,.847,.902,1),lightcoral:Float32Array.of(.941,.502,.502,1),lightcyan:Float32Array.of(.878,1,1,1),lightgoldenrodyellow:Float32Array.of(.98,.98,.824,1),lightgray:Float32Array.of(.827,.827,.827,1),lightgreen:Float32Array.of(.565,.933,.565,1),lightgrey:Float32Array.of(.827,.827,.827,1),lightpink:Float32Array.of(1,.714,.757,1),lightsalmon:Float32Array.of(1,.627,.478,1),lightseagreen:Float32Array.of(.125,.698,.667,1),lightskyblue:Float32Array.of(.529,.808,.98,1),lightslategray:Float32Array.of(.467,.533,.6,1),lightslategrey:Float32Array.of(.467,.533,.6,1),lightsteelblue:Float32Array.of(.69,.769,.871,1),lightyellow:Float32Array.of(1,1,.878,1),lime:Float32Array.of(0,1,0,1),limegreen:Float32Array.of(.196,.804,.196,1),linen:Float32Array.of(.98,.941,.902,1),magenta:Float32Array.of(1,0,1,1),maroon:Float32Array.of(.502,0,0,1),mediumaquamarine:Float32Array.of(.4,.804,.667,1),mediumblue:Float32Array.of(0,0,.804,1),mediumorchid:Float32Array.of(.729,.333,.827,1),mediumpurple:Float32Array.of(.576,.439,.859,1),mediumseagreen:Float32Array.of(.235,.702,.443,1),mediumslateblue:Float32Array.of(.482,.408,.933,1),mediumspringgreen:Float32Array.of(0,.98,.604,1),mediumturquoise:Float32Array.of(.282,.82,.8,1),mediumvioletred:Float32Array.of(.78,.082,.522,1),midnightblue:Float32Array.of(.098,.098,.439,1),mintcream:Float32Array.of(.961,1,.98,1),mistyrose:Float32Array.of(1,.894,.882,1),moccasin:Float32Array.of(1,.894,.71,1),navajowhite:Float32Array.of(1,.871,.678,1),navy:Float32Array.of(0,0,.502,1),oldlace:Float32Array.of(.992,.961,.902,1),olive:Float32Array.of(.502,.502,0,1),olivedrab:Float32Array.of(.42,.557,.137,1),orange:Float32Array.of(1,.647,0,1),orangered:Float32Array.of(1,.271,0,1),orchid:Float32Array.of(.855,.439,.839,1),palegoldenrod:Float32Array.of(.933,.91,.667,1),palegreen:Float32Array.of(.596,.984,.596,1),paleturquoise:Float32Array.of(.686,.933,.933,1),palevioletred:Float32Array.of(.859,.439,.576,1),papayawhip:Float32Array.of(1,.937,.835,1),peachpuff:Float32Array.of(1,.855,.725,1),peru:Float32Array.of(.804,.522,.247,1),pink:Float32Array.of(1,.753,.796,1),plum:Float32Array.of(.867,.627,.867,1),powderblue:Float32Array.of(.69,.878,.902,1),purple:Float32Array.of(.502,0,.502,1),rebeccapurple:Float32Array.of(.4,.2,.6,1),red:Float32Array.of(1,0,0,1),rosybrown:Float32Array.of(.737,.561,.561,1),royalblue:Float32Array.of(.255,.412,.882,1),saddlebrown:Float32Array.of(.545,.271,.075,1),salmon:Float32Array.of(.98,.502,.447,1),sandybrown:Float32Array.of(.957,.643,.376,1),seagreen:Float32Array.of(.18,.545,.341,1),seashell:Float32Array.of(1,.961,.933,1),sienna:Float32Array.of(.627,.322,.176,1),silver:Float32Array.of(.753,.753,.753,1),skyblue:Float32Array.of(.529,.808,.922,1),slateblue:Float32Array.of(.416,.353,.804,1),slategray:Float32Array.of(.439,.502,.565,1),slategrey:Float32Array.of(.439,.502,.565,1),snow:Float32Array.of(1,.98,.98,1),springgreen:Float32Array.of(0,1,.498,1),steelblue:Float32Array.of(.275,.51,.706,1),tan:Float32Array.of(.824,.706,.549,1),teal:Float32Array.of(0,.502,.502,1),thistle:Float32Array.of(.847,.749,.847,1),tomato:Float32Array.of(1,.388,.278,1),transparent:Float32Array.of(0,0,0,0),turquoise:Float32Array.of(.251,.878,.816,1),violet:Float32Array.of(.933,.51,.933,1),wheat:Float32Array.of(.961,.871,.702,1),white:Float32Array.of(1,1,1,1),whitesmoke:Float32Array.of(.961,.961,.961,1),yellow:Float32Array.of(1,1,0,1),yellowgreen:Float32Array.of(.604,.804,.196,1)};e._testing.parseColor=u,e._testing.colorToString=a;var Xt=RegExp("(italic|oblique|normal|)\\s*(small-caps|normal|)\\s*(bold|bolder|lighter|[1-9]00|normal|)\\s*([\\d\\.]+)(px|pt|pc|in|cm|mm|%|em|ex|ch|rem|q)(.+)"),zt={"Noto Mono":{"*":null},monospace:{"*":null}};e._testing.parseFontString=p,e.MakeCanvas=function(L,f){return(L=e.MakeSurface(L,f))?new _(L):null},e.ImageData=function(){if(arguments.length===2){var L=arguments[0],f=arguments[1];return new W(new Uint8ClampedArray(4*L*f),L,f)}if(arguments.length===3){var w=arguments[0];if(w.prototype.constructor!==Uint8ClampedArray)throw"bytes must be given as a Uint8ClampedArray";if(L=arguments[1],f=arguments[2],w%4)throw"bytes must be given in a multiple of 4";if(w%L)throw"bytes must divide evenly by width";if(f&&f!==w/(4*L))throw"invalid height given";return new W(w,L,w/(4*L))}throw"invalid number of arguments - takes 2 or 3, saw "+arguments.length}}()}(h);var B=Object.assign({},h),$="./this.program",it=(e,r)=>{throw r},ct=typeof window=="object",ut=typeof importScripts=="function",bt=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",wt="",Ht,fe,pe;if(bt){var ve=ia,U=oa;wt=ut?U.dirname(wt)+"/":__dirname+"/",Ht=(e,r)=>(e=e.startsWith("file://")?new URL(e):U.normalize(e),ve.readFileSync(e,r?void 0:"utf8")),pe=e=>(e=Ht(e,!0),e.buffer||(e=new Uint8Array(e)),e),fe=(e,r,s,l=!0)=>{e=e.startsWith("file://")?new URL(e):U.normalize(e),ve.readFile(e,l?void 0:"utf8",(d,m)=>{d?s(d):r(l?m.buffer:m)})},!h.thisProgram&&1<process.argv.length&&($=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),it=(e,r)=>{throw process.exitCode=e,r},h.inspect=()=>"[Emscripten Module object]"}else(ct||ut)&&(ut?wt=self.location.href:typeof document<"u"&&document.currentScript&&(wt=document.currentScript.src),n&&(wt=n),wt.indexOf("blob:")!==0?wt=wt.substr(0,wt.replace(/[?#].*/,"").lastIndexOf("/")+1):wt="",Ht=e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.send(null),r.responseText},ut&&(pe=e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),fe=(e,r,s)=>{var l=new XMLHttpRequest;l.open("GET",e,!0),l.responseType="arraybuffer",l.onload=()=>{l.status==200||l.status==0&&l.response?r(l.response):s()},l.onerror=s,l.send(null)});var at=h.print||console.log.bind(console),we=h.printErr||console.error.bind(console);Object.assign(h,B),B=null,h.thisProgram&&($=h.thisProgram),h.quit&&(it=h.quit);var je;h.wasmBinary&&(je=h.wasmBinary);var Kn=h.noExitRuntime||!0;typeof WebAssembly!="object"&&zi("no native wasm support detected");var ci,dt,Di=!1,oe,ht,Se,ke,G,Pt,tt,yr;function vr(){var e=ci.buffer;h.HEAP8=oe=new Int8Array(e),h.HEAP16=Se=new Int16Array(e),h.HEAP32=G=new Int32Array(e),h.HEAPU8=ht=new Uint8Array(e),h.HEAPU16=ke=new Uint16Array(e),h.HEAPU32=Pt=new Uint32Array(e),h.HEAPF32=tt=new Float32Array(e),h.HEAPF64=yr=new Float64Array(e)}var Rt,wr=[],Sr=[],br=[];function Vn(){var e=h.preRun.shift();wr.unshift(e)}var Ee=0,He=null;function zi(e){throw h.onAbort&&h.onAbort(e),e="Aborted("+e+")",we(e),Di=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),T(e),e}function Pr(e){return e.startsWith("data:application/octet-stream;base64,")}var Oe;if(Oe="canvaskit.wasm",!Pr(Oe)){var Ar=Oe;Oe=h.locateFile?h.locateFile(Ar,wt):wt+Ar}function Cr(e){if(e==Oe&&je)return new Uint8Array(je);if(pe)return pe(e);throw"both async and sync fetching of the wasm failed"}function qn(e){if(!je&&(ct||ut)){if(typeof fetch=="function"&&!e.startsWith("file://"))return fetch(e,{credentials:"same-origin"}).then(r=>{if(!r.ok)throw"failed to load wasm binary file at '"+e+"'";return r.arrayBuffer()}).catch(()=>Cr(e));if(fe)return new Promise((r,s)=>{fe(e,l=>r(new Uint8Array(l)),s)})}return Promise.resolve().then(()=>Cr(e))}function Er(e,r,s){return qn(e).then(l=>WebAssembly.instantiate(l,r)).then(l=>l).then(s,l=>{we("failed to asynchronously prepare wasm: "+l),zi(l)})}function Yn(e,r){var s=Oe;return je||typeof WebAssembly.instantiateStreaming!="function"||Pr(s)||s.startsWith("file://")||bt||typeof fetch!="function"?Er(s,e,r):fetch(s,{credentials:"same-origin"}).then(l=>WebAssembly.instantiateStreaming(l,e).then(r,function(d){return we("wasm streaming compile failed: "+d),we("falling back to ArrayBuffer instantiation"),Er(s,e,r)}))}function Jn(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}var Bi=e=>{for(;0<e.length;)e.shift()(h)},_r=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,_e=(e,r,s)=>{var l=r+s;for(s=r;e[s]&&!(s>=l);)++s;if(16<s-r&&e.buffer&&_r)return _r.decode(e.subarray(r,s));for(l="";r<s;){var d=e[r++];if(d&128){var m=e[r++]&63;if((d&224)==192)l+=String.fromCharCode((d&31)<<6|m);else{var P=e[r++]&63;d=(d&240)==224?(d&15)<<12|m<<6|P:(d&7)<<18|m<<12|P<<6|e[r++]&63,65536>d?l+=String.fromCharCode(d):(d-=65536,l+=String.fromCharCode(55296|d>>10,56320|d&1023))}}else l+=String.fromCharCode(d)}return l},ui={};function Ui(e){for(;e.length;){var r=e.pop();e.pop()(r)}}function Ke(e){return this.fromWireType(G[e>>2])}var Ie={},Te={},di={},Tr=void 0;function fi(e){throw new Tr(e)}function te(e,r,s){function l(y){y=s(y),y.length!==e.length&&fi("Mismatched type converter count");for(var v=0;v<e.length;++v)le(e[v],y[v])}e.forEach(function(y){di[y]=r});var d=Array(r.length),m=[],P=0;r.forEach((y,v)=>{Te.hasOwnProperty(y)?d[v]=Te[y]:(m.push(y),Ie.hasOwnProperty(y)||(Ie[y]=[]),Ie[y].push(()=>{d[v]=Te[y],++P,P===m.length&&l(d)}))}),m.length===0&&l(d)}function pi(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${e}`)}}var Fr=void 0;function Tt(e){for(var r="";ht[e];)r+=Fr[ht[e++]];return r}var Le=void 0;function mt(e){throw new Le(e)}function Xn(e,r,s={}){var l=r.name;if(e||mt(`type "${l}" must have a positive integer typeid pointer`),Te.hasOwnProperty(e)){if(s.Wf)return;mt(`Cannot register type '${l}' twice`)}Te[e]=r,delete di[e],Ie.hasOwnProperty(e)&&(r=Ie[e],delete Ie[e],r.forEach(d=>d()))}function le(e,r,s={}){if(!("argPackAdvance"in r))throw new TypeError("registerType registeredInstance requires argPackAdvance");Xn(e,r,s)}function $i(e){mt(e.Jd.Vd.Pd.name+" instance already deleted")}var Wi=!1;function Mr(){}function xr(e){--e.count.value,e.count.value===0&&(e.Yd?e.ee.ke(e.Yd):e.Vd.Pd.ke(e.Rd))}function Rr(e,r,s){return r===s?e:s.$d===void 0?null:(e=Rr(e,r,s.$d),e===null?null:s.Mf(e))}var Nr={},Ve=[];function Gi(){for(;Ve.length;){var e=Ve.pop();e.Jd.Ee=!1,e.delete()}}var qe=void 0,Ye={};function Qn(e,r){for(r===void 0&&mt("ptr should not be undefined");e.$d;)r=e.Oe(r),e=e.$d;return Ye[r]}function mi(e,r){return r.Vd&&r.Rd||fi("makeClassHandle requires ptr and ptrType"),!!r.ee!=!!r.Yd&&fi("Both smartPtrType and smartPtr must be specified"),r.count={value:1},Je(Object.create(e,{Jd:{value:r}}))}function Je(e){return typeof FinalizationRegistry>"u"?(Je=r=>r,e):(Wi=new FinalizationRegistry(r=>{xr(r.Jd)}),Je=r=>{var s=r.Jd;return s.Yd&&Wi.register(r,{Jd:s},r),r},Mr=r=>{Wi.unregister(r)},Je(e))}function be(){}function kr(e){if(e===void 0)return"_unknown";e=e.replace(/[^a-zA-Z0-9_]/g,"$");var r=e.charCodeAt(0);return 48<=r&&57>=r?`_${e}`:e}function ji(e,r){return e=kr(e),{[e]:function(){return r.apply(this,arguments)}}[e]}function Hi(e,r,s){if(e[r].Xd===void 0){var l=e[r];e[r]=function(){return e[r].Xd.hasOwnProperty(arguments.length)||mt(`Function '${s}' called with an invalid number of arguments (${arguments.length}) - expects one of (${e[r].Xd})!`),e[r].Xd[arguments.length].apply(this,arguments)},e[r].Xd=[],e[r].Xd[l.Ce]=l}}function Ki(e,r,s){h.hasOwnProperty(e)?((s===void 0||h[e].Xd!==void 0&&h[e].Xd[s]!==void 0)&&mt(`Cannot register public name '${e}' twice`),Hi(h,e,e),h.hasOwnProperty(s)&&mt(`Cannot register multiple overloads of a function with the same number of arguments (${s})!`),h[e].Xd[s]=r):(h[e]=r,s!==void 0&&(h[e].tg=s))}function Zn(e,r,s,l,d,m,P,y){this.name=e,this.constructor=r,this.Fe=s,this.ke=l,this.$d=d,this.Rf=m,this.Oe=P,this.Mf=y,this.cg=[]}function Vi(e,r,s){for(;r!==s;)r.Oe||mt(`Expected null or instance of ${s.name}, got an instance of ${r.name}`),e=r.Oe(e),r=r.$d;return e}function ts(e,r){return r===null?(this.gf&&mt(`null is not a valid ${this.name}`),0):(r.Jd||mt(`Cannot pass "${Yi(r)}" as a ${this.name}`),r.Jd.Rd||mt(`Cannot pass deleted object as a pointer of type ${this.name}`),Vi(r.Jd.Rd,r.Jd.Vd.Pd,this.Pd))}function es(e,r){if(r===null){if(this.gf&&mt(`null is not a valid ${this.name}`),this.Ve){var s=this.hf();return e!==null&&e.push(this.ke,s),s}return 0}if(r.Jd||mt(`Cannot pass "${Yi(r)}" as a ${this.name}`),r.Jd.Rd||mt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.Ue&&r.Jd.Vd.Ue&&mt(`Cannot convert argument of type ${r.Jd.ee?r.Jd.ee.name:r.Jd.Vd.name} to parameter type ${this.name}`),s=Vi(r.Jd.Rd,r.Jd.Vd.Pd,this.Pd),this.Ve)switch(r.Jd.Yd===void 0&&mt("Passing raw pointer to smart pointer is illegal"),this.hg){case 0:r.Jd.ee===this?s=r.Jd.Yd:mt(`Cannot convert argument of type ${r.Jd.ee?r.Jd.ee.name:r.Jd.Vd.name} to parameter type ${this.name}`);break;case 1:s=r.Jd.Yd;break;case 2:if(r.Jd.ee===this)s=r.Jd.Yd;else{var l=r.clone();s=this.dg(s,qt(function(){l.delete()})),e!==null&&e.push(this.ke,s)}break;default:mt("Unsupporting sharing policy")}return s}function is(e,r){return r===null?(this.gf&&mt(`null is not a valid ${this.name}`),0):(r.Jd||mt(`Cannot pass "${Yi(r)}" as a ${this.name}`),r.Jd.Rd||mt(`Cannot pass deleted object as a pointer of type ${this.name}`),r.Jd.Vd.Ue&&mt(`Cannot convert argument of type ${r.Jd.Vd.name} to parameter type ${this.name}`),Vi(r.Jd.Rd,r.Jd.Vd.Pd,this.Pd))}function he(e,r,s,l,d,m,P,y,v,A,O){this.name=e,this.Pd=r,this.gf=s,this.Ue=l,this.Ve=d,this.bg=m,this.hg=P,this.vf=y,this.hf=v,this.dg=A,this.ke=O,d||r.$d!==void 0?this.toWireType=es:(this.toWireType=l?ts:is,this.de=null)}function Or(e,r,s){h.hasOwnProperty(e)||fi("Replacing nonexistant public symbol"),h[e].Xd!==void 0&&s!==void 0?h[e].Xd[s]=r:(h[e]=r,h[e].Ce=s)}var rs=(e,r)=>{var s=[];return function(){if(s.length=0,Object.assign(s,arguments),e.includes("j")){var l=h["dynCall_"+e];l=s&&s.length?l.apply(null,[r].concat(s)):l.call(null,r)}else l=Rt.get(r).apply(null,s);return l}};function Ot(e,r){e=Tt(e);var s=e.includes("j")?rs(e,r):Rt.get(r);return typeof s!="function"&&mt(`unknown function pointer with signature ${e}: ${r}`),s}var Ir=void 0;function Lr(e){e=nn(e);var r=Tt(e);return me(e),r}function Xe(e,r){function s(m){d[m]||Te[m]||(di[m]?di[m].forEach(s):(l.push(m),d[m]=!0))}var l=[],d={};throw r.forEach(s),new Ir(`${e}: `+l.map(Lr).join([", "]))}function gi(e,r,s,l,d){var m=r.length;2>m&&mt("argTypes array size mismatch! Must at least get return value and 'this' types!");var P=r[1]!==null&&s!==null,y=!1;for(s=1;s<r.length;++s)if(r[s]!==null&&r[s].de===void 0){y=!0;break}var v=r[0].name!=="void",A=m-2,O=Array(A),D=[],K=[];return function(){if(arguments.length!==A&&mt(`function ${e} called with ${arguments.length} arguments, expected ${A} args!`),K.length=0,D.length=P?2:1,D[0]=d,P){var F=r[1].toWireType(K,this);D[1]=F}for(var J=0;J<A;++J)O[J]=r[J+2].toWireType(K,arguments[J]),D.push(O[J]);if(J=l.apply(null,D),y)Ui(K);else for(var st=P?1:2;st<r.length;st++){var nt=st===1?F:O[st-2];r[st].de!==null&&r[st].de(nt)}return F=v?r[0].fromWireType(J):void 0,F}}function yi(e,r){for(var s=[],l=0;l<e;l++)s.push(Pt[r+4*l>>2]);return s}function Dr(){this.je=[void 0],this.sf=[]}var Kt=new Dr;function qi(e){e>=Kt.Ge&&--Kt.get(e).wf===0&&Kt.Bf(e)}var Vt=e=>(e||mt("Cannot use deleted val. handle = "+e),Kt.get(e).value),qt=e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Kt.Af({wf:1,value:e})}};function ns(e,r,s){switch(r){case 0:return function(l){return this.fromWireType((s?oe:ht)[l])};case 1:return function(l){return this.fromWireType((s?Se:ke)[l>>1])};case 2:return function(l){return this.fromWireType((s?G:Pt)[l>>2])};default:throw new TypeError("Unknown integer type: "+e)}}function Qe(e,r){var s=Te[e];return s===void 0&&mt(r+" has unknown type "+Lr(e)),s}function Yi(e){if(e===null)return"null";var r=typeof e;return r==="object"||r==="array"||r==="function"?e.toString():""+e}function ss(e,r){switch(r){case 2:return function(s){return this.fromWireType(tt[s>>2])};case 3:return function(s){return this.fromWireType(yr[s>>3])};default:throw new TypeError("Unknown float type: "+e)}}function as(e,r,s){switch(r){case 0:return s?function(l){return oe[l]}:function(l){return ht[l]};case 1:return s?function(l){return Se[l>>1]}:function(l){return ke[l>>1]};case 2:return s?function(l){return G[l>>2]}:function(l){return Pt[l>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var ee=(e,r,s,l)=>{if(!(0<l))return 0;var d=s;l=s+l-1;for(var m=0;m<e.length;++m){var P=e.charCodeAt(m);if(55296<=P&&57343>=P){var y=e.charCodeAt(++m);P=65536+((P&1023)<<10)|y&1023}if(127>=P){if(s>=l)break;r[s++]=P}else{if(2047>=P){if(s+1>=l)break;r[s++]=192|P>>6}else{if(65535>=P){if(s+2>=l)break;r[s++]=224|P>>12}else{if(s+3>=l)break;r[s++]=240|P>>18,r[s++]=128|P>>12&63}r[s++]=128|P>>6&63}r[s++]=128|P&63}}return r[s]=0,s-d},ie=e=>{for(var r=0,s=0;s<e.length;++s){var l=e.charCodeAt(s);127>=l?r++:2047>=l?r+=2:55296<=l&&57343>=l?(r+=4,++s):r+=3}return r},zr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,os=(e,r)=>{for(var s=e>>1,l=s+r/2;!(s>=l)&&ke[s];)++s;if(s<<=1,32<s-e&&zr)return zr.decode(ht.subarray(e,s));for(s="",l=0;!(l>=r/2);++l){var d=Se[e+2*l>>1];if(d==0)break;s+=String.fromCharCode(d)}return s},ls=(e,r,s)=>{if(s===void 0&&(s=2147483647),2>s)return 0;s-=2;var l=r;s=s<2*e.length?s/2:e.length;for(var d=0;d<s;++d)Se[r>>1]=e.charCodeAt(d),r+=2;return Se[r>>1]=0,r-l},hs=e=>2*e.length,cs=(e,r)=>{for(var s=0,l="";!(s>=r/4);){var d=G[e+4*s>>2];if(d==0)break;++s,65536<=d?(d-=65536,l+=String.fromCharCode(55296|d>>10,56320|d&1023)):l+=String.fromCharCode(d)}return l},us=(e,r,s)=>{if(s===void 0&&(s=2147483647),4>s)return 0;var l=r;s=l+s-4;for(var d=0;d<e.length;++d){var m=e.charCodeAt(d);if(55296<=m&&57343>=m){var P=e.charCodeAt(++d);m=65536+((m&1023)<<10)|P&1023}if(G[r>>2]=m,r+=4,r+4>s)break}return G[r>>2]=0,r-l},ds=e=>{for(var r=0,s=0;s<e.length;++s){var l=e.charCodeAt(s);55296<=l&&57343>=l&&++s,r+=4}return r},fs={};function vi(e){var r=fs[e];return r===void 0?Tt(e):r}var wi=[];function Br(){function e(r){r.$$$embind_global$$$=r;var s=typeof $$$embind_global$$$=="object"&&r.$$$embind_global$$$==r;return s||delete r.$$$embind_global$$$,s}if(typeof globalThis=="object")return globalThis;if(typeof $$$embind_global$$$=="object"||(typeof hr=="object"&&e(hr)?$$$embind_global$$$=hr:typeof self=="object"&&e(self)&&($$$embind_global$$$=self),typeof $$$embind_global$$$=="object"))return $$$embind_global$$$;throw Error("unable to get global object.")}function ps(e){var r=wi.length;return wi.push(e),r}function ms(e,r){for(var s=Array(e),l=0;l<e;++l)s[l]=Qe(Pt[r+4*l>>2],"parameter "+l);return s}var Ur=[];function gs(e){var r=Array(e+1);return function(s,l,d){r[0]=s;for(var m=0;m<e;++m){var P=Qe(Pt[l+4*m>>2],"parameter "+m);r[m+1]=P.readValueFromPointer(d),d+=P.argPackAdvance}return s=new(s.bind.apply(s,r)),qt(s)}}var $r={};function ys(e){var r=e.getExtension("ANGLE_instanced_arrays");r&&(e.vertexAttribDivisor=function(s,l){r.vertexAttribDivisorANGLE(s,l)},e.drawArraysInstanced=function(s,l,d,m){r.drawArraysInstancedANGLE(s,l,d,m)},e.drawElementsInstanced=function(s,l,d,m,P){r.drawElementsInstancedANGLE(s,l,d,m,P)})}function vs(e){var r=e.getExtension("OES_vertex_array_object");r&&(e.createVertexArray=function(){return r.createVertexArrayOES()},e.deleteVertexArray=function(s){r.deleteVertexArrayOES(s)},e.bindVertexArray=function(s){r.bindVertexArrayOES(s)},e.isVertexArray=function(s){return r.isVertexArrayOES(s)})}function ws(e){var r=e.getExtension("WEBGL_draw_buffers");r&&(e.drawBuffers=function(s,l){r.drawBuffersWEBGL(s,l)})}var Wr=1,Si=[],re=[],bi=[],Ze=[],Yt=[],ne=[],Pi=[],ce=[],Fe=[],Me=[],Gr={},jr={},Hr=4;function At(e){Ai||(Ai=e)}function De(e){for(var r=Wr++,s=e.length;s<r;s++)e[s]=null;return r}function Ss(e,r){e.Ge||(e.Ge=e.getContext,e.getContext=function(l,d){return d=e.Ge(l,d),l=="webgl"==d instanceof WebGLRenderingContext?d:null});var s=1<r.majorVersion?e.getContext("webgl2",r):e.getContext("webgl",r);return s?bs(s,r):0}function bs(e,r){var s=De(ce),l={handle:s,attributes:r,version:r.majorVersion,fe:e};return e.canvas&&(e.canvas.zf=l),ce[s]=l,(typeof r.Nf>"u"||r.Nf)&&Ps(l),s}function Kr(e){return rt=ce[e],h.rg=E=rt&&rt.fe,!(e&&!E)}function Ps(e){if(e||(e=rt),!e.Xf){e.Xf=!0;var r=e.fe;ys(r),vs(r),ws(r),r.pf=r.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"),r.uf=r.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"),2<=e.version&&(r.qf=r.getExtension("EXT_disjoint_timer_query_webgl2")),(2>e.version||!r.qf)&&(r.qf=r.getExtension("EXT_disjoint_timer_query")),r.sg=r.getExtension("WEBGL_multi_draw"),(r.getSupportedExtensions()||[]).forEach(function(s){s.includes("lose_context")||s.includes("debug")||r.getExtension(s)})}}var rt,Ai,Ji={},Vr=()=>{if(!Xi){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:$||"./this.program"},r;for(r in Ji)Ji[r]===void 0?delete e[r]:e[r]=Ji[r];var s=[];for(r in e)s.push(`${r}=${e[r]}`);Xi=s}return Xi},Xi,As=[null,[],[]];function qr(e){E.bindVertexArray(Pi[e])}function Yr(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2];E.deleteVertexArray(Pi[l]),Pi[l]=null}}var Ci=[];function Jr(e,r,s,l){E.drawElements(e,r,s,l)}function ze(e,r,s,l){for(var d=0;d<e;d++){var m=E[s](),P=m&&De(l);m?(m.name=P,l[P]=m):At(1282),G[r+4*d>>2]=P}}function Xr(e,r){ze(e,r,"createVertexArray",Pi)}function Qr(e,r,s){if(r){var l=void 0;switch(e){case 36346:l=1;break;case 36344:s!=0&&s!=1&&At(1280);return;case 34814:case 36345:l=0;break;case 34466:var d=E.getParameter(34467);l=d?d.length:0;break;case 33309:if(2>rt.version){At(1282);return}l=2*(E.getSupportedExtensions()||[]).length;break;case 33307:case 33308:if(2>rt.version){At(1280);return}l=e==33307?3:0}if(l===void 0)switch(d=E.getParameter(e),typeof d){case"number":l=d;break;case"boolean":l=d?1:0;break;case"string":At(1280);return;case"object":if(d===null)switch(e){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:l=0;break;default:At(1280);return}else{if(d instanceof Float32Array||d instanceof Uint32Array||d instanceof Int32Array||d instanceof Array){for(e=0;e<d.length;++e)switch(s){case 0:G[r+4*e>>2]=d[e];break;case 2:tt[r+4*e>>2]=d[e];break;case 4:oe[r+e>>0]=d[e]?1:0}return}try{l=d.name|0}catch(m){At(1280),we("GL_INVALID_ENUM in glGet"+s+"v: Unknown object returned from WebGL getParameter("+e+")! (error: "+m+")");return}}break;default:At(1280),we("GL_INVALID_ENUM in glGet"+s+"v: Native code calling glGet"+s+"v("+e+") and it returns "+d+" of type "+typeof d+"!");return}switch(s){case 1:s=l,Pt[r>>2]=s,Pt[r+4>>2]=(s-Pt[r>>2])/4294967296;break;case 0:G[r>>2]=l;break;case 2:tt[r>>2]=l;break;case 4:oe[r>>0]=l?1:0}}else At(1281)}var ti=e=>{var r=ie(e)+1,s=Fi(r);return s&&ee(e,ht,s,r),s};function Zr(e){return e.slice(-1)=="]"&&e.lastIndexOf("[")}function Ei(e){return e-=5120,e==0?oe:e==1?ht:e==2?Se:e==4?G:e==6?tt:e==5||e==28922||e==28520||e==30779||e==30782?Pt:ke}function Qi(e,r,s,l,d){e=Ei(e);var m=31-Math.clz32(e.BYTES_PER_ELEMENT),P=Hr;return e.subarray(d>>m,d+l*(s*({5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4}[r-6402]||1)*(1<<m)+P-1&-P)>>m)}function vt(e){var r=E.Kf;if(r){var s=r.Ne[e];return typeof s=="number"&&(r.Ne[e]=s=E.getUniformLocation(r,r.xf[e]+(0<s?"["+s+"]":""))),s}At(1282)}var Pe=[],ei=[],_i=e=>e%4===0&&(e%100!==0||e%400===0),tn=[31,29,31,30,31,30,31,31,30,31,30,31],en=[31,28,31,30,31,30,31,31,30,31,30,31];function Cs(e){var r=Array(ie(e)+1);return ee(e,r,0,r.length),r}var Es=(e,r,s,l)=>{function d(F,J,st){for(F=typeof F=="number"?F.toString():F||"";F.length<J;)F=st[0]+F;return F}function m(F,J){return d(F,J,"0")}function P(F,J){function st($t){return 0>$t?-1:0<$t?1:0}var nt;return(nt=st(F.getFullYear()-J.getFullYear()))===0&&(nt=st(F.getMonth()-J.getMonth()))===0&&(nt=st(F.getDate()-J.getDate())),nt}function y(F){switch(F.getDay()){case 0:return new Date(F.getFullYear()-1,11,29);case 1:return F;case 2:return new Date(F.getFullYear(),0,3);case 3:return new Date(F.getFullYear(),0,2);case 4:return new Date(F.getFullYear(),0,1);case 5:return new Date(F.getFullYear()-1,11,31);case 6:return new Date(F.getFullYear()-1,11,30)}}function v(F){var J=F.oe;for(F=new Date(new Date(F.pe+1900,0,1).getTime());0<J;){var st=F.getMonth(),nt=(_i(F.getFullYear())?tn:en)[st];if(J>nt-F.getDate())J-=nt-F.getDate()+1,F.setDate(1),11>st?F.setMonth(st+1):(F.setMonth(0),F.setFullYear(F.getFullYear()+1));else{F.setDate(F.getDate()+J);break}}return st=new Date(F.getFullYear()+1,0,4),J=y(new Date(F.getFullYear(),0,4)),st=y(st),0>=P(J,F)?0>=P(st,F)?F.getFullYear()+1:F.getFullYear():F.getFullYear()-1}var A=G[l+40>>2];l={pg:G[l>>2],og:G[l+4>>2],Ze:G[l+8>>2],jf:G[l+12>>2],$e:G[l+16>>2],pe:G[l+20>>2],he:G[l+24>>2],oe:G[l+28>>2],vg:G[l+32>>2],ng:G[l+36>>2],qg:A&&A?_e(ht,A):""},s=s?_e(ht,s):"",A={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var O in A)s=s.replace(new RegExp(O,"g"),A[O]);var D="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),K="January February March April May June July August September October November December".split(" ");A={"%a":F=>D[F.he].substring(0,3),"%A":F=>D[F.he],"%b":F=>K[F.$e].substring(0,3),"%B":F=>K[F.$e],"%C":F=>m((F.pe+1900)/100|0,2),"%d":F=>m(F.jf,2),"%e":F=>d(F.jf,2," "),"%g":F=>v(F).toString().substring(2),"%G":F=>v(F),"%H":F=>m(F.Ze,2),"%I":F=>(F=F.Ze,F==0?F=12:12<F&&(F-=12),m(F,2)),"%j":F=>{for(var J=0,st=0;st<=F.$e-1;J+=(_i(F.pe+1900)?tn:en)[st++]);return m(F.jf+J,3)},"%m":F=>m(F.$e+1,2),"%M":F=>m(F.og,2),"%n":()=>`
2
2
  `,"%p":F=>0<=F.Ze&&12>F.Ze?"AM":"PM","%S":F=>m(F.pg,2),"%t":()=>" ","%u":F=>F.he||7,"%U":F=>m(Math.floor((F.oe+7-F.he)/7),2),"%V":F=>{var J=Math.floor((F.oe+7-(F.he+6)%7)/7);if(2>=(F.he+371-F.oe-2)%7&&J++,J)J==53&&(st=(F.he+371-F.oe)%7,st==4||st==3&&_i(F.pe)||(J=1));else{J=52;var st=(F.he+7-F.oe-1)%7;(st==4||st==5&&_i(F.pe%400-1))&&J++}return m(J,2)},"%w":F=>F.he,"%W":F=>m(Math.floor((F.oe+7-(F.he+6)%7)/7),2),"%y":F=>(F.pe+1900).toString().substring(2),"%Y":F=>F.pe+1900,"%z":F=>{F=F.ng;var J=0<=F;return F=Math.abs(F)/60,(J?"+":"-")+("0000"+(F/60*100+F%60)).slice(-4)},"%Z":F=>F.qg,"%%":()=>"%"},s=s.replace(/%%/g,"\0\0");for(O in A)s.includes(O)&&(s=s.replace(new RegExp(O,"g"),A[O](l)));return s=s.replace(/\0\0/g,"%"),O=Cs(s),O.length>r?0:(oe.set(O,e),O.length-1)};Tr=h.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}};for(var rn=Array(256),Ti=0;256>Ti;++Ti)rn[Ti]=String.fromCharCode(Ti);Fr=rn,Le=h.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},be.prototype.isAliasOf=function(e){if(!(this instanceof be&&e instanceof be))return!1;var r=this.Jd.Vd.Pd,s=this.Jd.Rd,l=e.Jd.Vd.Pd;for(e=e.Jd.Rd;r.$d;)s=r.Oe(s),r=r.$d;for(;l.$d;)e=l.Oe(e),l=l.$d;return r===l&&s===e},be.prototype.clone=function(){if(this.Jd.Rd||$i(this),this.Jd.Me)return this.Jd.count.value+=1,this;var e=Je,r=Object,s=r.create,l=Object.getPrototypeOf(this),d=this.Jd;return e=e(s.call(r,l,{Jd:{value:{count:d.count,Ee:d.Ee,Me:d.Me,Rd:d.Rd,Vd:d.Vd,Yd:d.Yd,ee:d.ee}}})),e.Jd.count.value+=1,e.Jd.Ee=!1,e},be.prototype.delete=function(){this.Jd.Rd||$i(this),this.Jd.Ee&&!this.Jd.Me&&mt("Object already scheduled for deletion"),Mr(this),xr(this.Jd),this.Jd.Me||(this.Jd.Yd=void 0,this.Jd.Rd=void 0)},be.prototype.isDeleted=function(){return!this.Jd.Rd},be.prototype.deleteLater=function(){return this.Jd.Rd||$i(this),this.Jd.Ee&&!this.Jd.Me&&mt("Object already scheduled for deletion"),Ve.push(this),Ve.length===1&&qe&&qe(Gi),this.Jd.Ee=!0,this},h.getInheritedInstanceCount=function(){return Object.keys(Ye).length},h.getLiveInheritedInstances=function(){var e=[],r;for(r in Ye)Ye.hasOwnProperty(r)&&e.push(Ye[r]);return e},h.flushPendingDeletes=Gi,h.setDelayFunction=function(e){qe=e,Ve.length&&qe&&qe(Gi)},he.prototype.Sf=function(e){return this.vf&&(e=this.vf(e)),e},he.prototype.nf=function(e){this.ke&&this.ke(e)},he.prototype.argPackAdvance=8,he.prototype.readValueFromPointer=Ke,he.prototype.deleteObject=function(e){e!==null&&e.delete()},he.prototype.fromWireType=function(e){function r(){return this.Ve?mi(this.Pd.Fe,{Vd:this.bg,Rd:s,ee:this,Yd:e}):mi(this.Pd.Fe,{Vd:this,Rd:e})}var s=this.Sf(e);if(!s)return this.nf(e),null;var l=Qn(this.Pd,s);if(l!==void 0)return l.Jd.count.value===0?(l.Jd.Rd=s,l.Jd.Yd=e,l.clone()):(l=l.clone(),this.nf(e),l);if(l=this.Pd.Rf(s),l=Nr[l],!l)return r.call(this);l=this.Ue?l.If:l.pointerType;var d=Rr(s,this.Pd,l.Pd);return d===null?r.call(this):this.Ve?mi(l.Pd.Fe,{Vd:l,Rd:d,ee:this,Yd:e}):mi(l.Pd.Fe,{Vd:l,Rd:d})},Ir=h.UnboundTypeError=function(e,r){var s=ji(r,function(l){this.name=r,this.message=l,l=Error(l).stack,l!==void 0&&(this.stack=this.toString()+`
3
- `+l.replace(/^Error(:[^\n]*)?\n/,""))});return s.prototype=Object.create(e.prototype),s.prototype.constructor=s,s.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},s}(Error,"UnboundTypeError"),Object.assign(Dr.prototype,{get(e){return this.je[e]},has(e){return this.je[e]!==void 0},Af(e){var r=this.sf.pop()||this.je.length;return this.je[r]=e,r},Bf(e){this.je[e]=void 0,this.sf.push(e)}}),Kt.je.push({value:void 0},{value:null},{value:!0},{value:!1}),Kt.Ge=Kt.je.length,h.count_emval_handles=function(){for(var e=0,r=Kt.Ge;r<Kt.je.length;++r)Kt.je[r]!==void 0&&++e;return e};for(var E,jt=0;32>jt;++jt)Ci.push(Array(jt));var _s=new Float32Array(288);for(jt=0;288>jt;++jt)Pe[jt]=_s.subarray(0,jt+1);var Ts=new Int32Array(288);for(jt=0;288>jt;++jt)ei[jt]=Ts.subarray(0,jt+1);var Fs={T:function(){return 0},Bb:()=>{},Db:function(){return 0},yb:()=>{},zb:()=>{},U:function(){},Ab:()=>{},C:function(e){var r=ui[e];delete ui[e];var s=r.hf,l=r.ke,d=r.rf,m=d.map(P=>P.Vf).concat(d.map(P=>P.fg));te([e],m,P=>{var y={};return d.forEach((v,A)=>{var O=P[A],D=v.Tf,K=v.Uf,F=P[A+d.length],J=v.eg,st=v.gg;y[v.Of]={read:nt=>O.fromWireType(D(K,nt)),write:(nt,$t)=>{var kt=[];J(st,nt,F.toWireType(kt,$t)),Ui(kt)}}}),[{name:r.name,fromWireType:function(v){var A={},O;for(O in y)A[O]=y[O].read(v);return l(v),A},toWireType:function(v,A){for(var O in y)if(!(O in A))throw new TypeError(`Missing field: "${O}"`);var D=s();for(O in y)y[O].write(D,A[O]);return v!==null&&v.push(l,D),D},argPackAdvance:8,readValueFromPointer:Ke,de:l}]})},qb:function(){},Hb:function(e,r,s,l,d){var m=pi(s);r=Tt(r),le(e,{name:r,fromWireType:function(P){return!!P},toWireType:function(P,y){return y?l:d},argPackAdvance:8,readValueFromPointer:function(P){if(s===1)var y=oe;else if(s===2)y=Se;else if(s===4)y=G;else throw new TypeError("Unknown boolean type size: "+r);return this.fromWireType(y[P>>m])},de:null})},m:function(e,r,s,l,d,m,P,y,v,A,O,D,K){O=Tt(O),m=Ot(d,m),y&&(y=Ot(P,y)),A&&(A=Ot(v,A)),K=Ot(D,K);var F=kr(O);Ki(F,function(){Xe(`Cannot construct ${O} due to unbound types`,[l])}),te([e,r,s],l?[l]:[],function(J){if(J=J[0],l)var st=J.Pd,nt=st.Fe;else nt=be.prototype;J=ji(F,function(){if(Object.getPrototypeOf(this)!==$t)throw new Le("Use 'new' to construct "+O);if(kt.ne===void 0)throw new Le(O+" has no accessible constructor");var ri=kt.ne[arguments.length];if(ri===void 0)throw new Le(`Tried to invoke ctor of ${O} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(kt.ne).toString()}) parameters instead!`);return ri.apply(this,arguments)});var $t=Object.create(nt,{constructor:{value:J}});J.prototype=$t;var kt=new Zn(O,J,$t,K,st,m,y,A);kt.$d&&(kt.$d.Pe===void 0&&(kt.$d.Pe=[]),kt.$d.Pe.push(kt)),st=new he(O,kt,!0,!1,!1),nt=new he(O+"*",kt,!1,!1,!1);var ii=new he(O+" const*",kt,!1,!0,!1);return Nr[e]={pointerType:nt,If:ii},Or(F,J),[st,nt,ii]})},f:function(e,r,s,l,d,m,P){var y=yi(s,l);r=Tt(r),m=Ot(d,m),te([],[e],function(v){function A(){Xe(`Cannot call ${O} due to unbound types`,y)}v=v[0];var O=`${v.name}.${r}`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]);var D=v.Pd.constructor;return D[r]===void 0?(A.Ce=s-1,D[r]=A):(Hi(D,r,O),D[r].Xd[s-1]=A),te([],y,function(K){if(K=[K[0],null].concat(K.slice(1)),K=gi(O,K,null,m,P),D[r].Xd===void 0?(K.Ce=s-1,D[r]=K):D[r].Xd[s-1]=K,v.Pd.Pe)for(const F of v.Pd.Pe)F.constructor.hasOwnProperty(r)||(F.constructor[r]=K);return[]}),[]})},A:function(e,r,s,l,d,m){var P=yi(r,s);d=Ot(l,d),te([],[e],function(y){y=y[0];var v=`constructor ${y.name}`;if(y.Pd.ne===void 0&&(y.Pd.ne=[]),y.Pd.ne[r-1]!==void 0)throw new Le(`Cannot register multiple constructors with identical number of parameters (${r-1}) for class '${y.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return y.Pd.ne[r-1]=()=>{Xe(`Cannot construct ${y.name} due to unbound types`,P)},te([],P,function(A){return A.splice(1,0,null),y.Pd.ne[r-1]=gi(v,A,null,d,m),[]}),[]})},b:function(e,r,s,l,d,m,P,y){var v=yi(s,l);r=Tt(r),m=Ot(d,m),te([],[e],function(A){function O(){Xe(`Cannot call ${D} due to unbound types`,v)}A=A[0];var D=`${A.name}.${r}`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),y&&A.Pd.cg.push(r);var K=A.Pd.Fe,F=K[r];return F===void 0||F.Xd===void 0&&F.className!==A.name&&F.Ce===s-2?(O.Ce=s-2,O.className=A.name,K[r]=O):(Hi(K,r,D),K[r].Xd[s-2]=O),te([],v,function(J){return J=gi(D,J,A,m,P),K[r].Xd===void 0?(J.Ce=s-2,K[r]=J):K[r].Xd[s-2]=J,[]}),[]})},t:function(e,r,s){e=Tt(e),te([],[r],function(l){return l=l[0],h[e]=l.fromWireType(s),[]})},Gb:function(e,r){r=Tt(r),le(e,{name:r,fromWireType:function(s){var l=Vt(s);return qi(s),l},toWireType:function(s,l){return qt(l)},argPackAdvance:8,readValueFromPointer:Ke,de:null})},l:function(e,r,s,l){function d(){}s=pi(s),r=Tt(r),d.values={},le(e,{name:r,constructor:d,fromWireType:function(m){return this.constructor.values[m]},toWireType:function(m,P){return P.value},argPackAdvance:8,readValueFromPointer:ns(r,s,l),de:null}),Ki(r,d)},c:function(e,r,s){var l=Qe(e,"enum");r=Tt(r),e=l.constructor,l=Object.create(l.constructor.prototype,{value:{value:s},constructor:{value:ji(`${l.name}_${r}`,function(){})}}),e.values[s]=l,e[r]=l},W:function(e,r,s){s=pi(s),r=Tt(r),le(e,{name:r,fromWireType:function(l){return l},toWireType:function(l,d){return d},argPackAdvance:8,readValueFromPointer:ss(r,s),de:null})},y:function(e,r,s,l,d,m){var P=yi(r,s);e=Tt(e),d=Ot(l,d),Ki(e,function(){Xe(`Cannot call ${e} due to unbound types`,P)},r-1),te([],P,function(y){return y=[y[0],null].concat(y.slice(1)),Or(e,gi(e,y,null,d,m),r-1),[]})},E:function(e,r,s,l,d){r=Tt(r),d===-1&&(d=4294967295),d=pi(s);var m=y=>y;if(l===0){var P=32-8*s;m=y=>y<<P>>>P}s=r.includes("unsigned")?function(y,v){return v>>>0}:function(y,v){return v},le(e,{name:r,fromWireType:m,toWireType:s,argPackAdvance:8,readValueFromPointer:as(r,d,l!==0),de:null})},s:function(e,r,s){function l(m){m>>=2;var P=Pt;return new d(P.buffer,P[m+1],P[m])}var d=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][r];s=Tt(s),le(e,{name:s,fromWireType:l,argPackAdvance:8,readValueFromPointer:l},{Wf:!0})},q:function(e,r,s,l,d,m,P,y,v,A,O,D){s=Tt(s),m=Ot(d,m),y=Ot(P,y),A=Ot(v,A),D=Ot(O,D),te([e],[r],function(K){return K=K[0],[new he(s,K.Pd,!1,!1,!0,K,l,m,y,A,D)]})},V:function(e,r){r=Tt(r);var s=r==="std::string";le(e,{name:r,fromWireType:function(l){var d=Pt[l>>2],m=l+4;if(s)for(var P=m,y=0;y<=d;++y){var v=m+y;if(y==d||ht[v]==0){if(P=P?_e(ht,P,v-P):"",A===void 0)var A=P;else A+="\0",A+=P;P=v+1}}else{for(A=Array(d),y=0;y<d;++y)A[y]=String.fromCharCode(ht[m+y]);A=A.join("")}return me(l),A},toWireType:function(l,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var m=typeof d=="string";m||d instanceof Uint8Array||d instanceof Uint8ClampedArray||d instanceof Int8Array||mt("Cannot pass non-string to std::string");var P=s&&m?ie(d):d.length,y=Fi(4+P+1),v=y+4;if(Pt[y>>2]=P,s&&m)ee(d,ht,v,P+1);else if(m)for(m=0;m<P;++m){var A=d.charCodeAt(m);255<A&&(me(v),mt("String has UTF-16 code units that do not fit in 8 bits")),ht[v+m]=A}else for(m=0;m<P;++m)ht[v+m]=d[m];return l!==null&&l.push(me,y),y},argPackAdvance:8,readValueFromPointer:Ke,de:function(l){me(l)}})},N:function(e,r,s){if(s=Tt(s),r===2)var l=os,d=ls,m=hs,P=()=>ke,y=1;else r===4&&(l=cs,d=us,m=ds,P=()=>Pt,y=2);le(e,{name:s,fromWireType:function(v){for(var A=Pt[v>>2],O=P(),D,K=v+4,F=0;F<=A;++F){var J=v+4+F*r;(F==A||O[J>>y]==0)&&(K=l(K,J-K),D===void 0?D=K:(D+="\0",D+=K),K=J+r)}return me(v),D},toWireType:function(v,A){typeof A!="string"&&mt(`Cannot pass non-string to C++ string type ${s}`);var O=m(A),D=Fi(4+O+r);return Pt[D>>2]=O>>y,d(A,D+4,O+r),v!==null&&v.push(me,D),D},argPackAdvance:8,readValueFromPointer:Ke,de:function(v){me(v)}})},D:function(e,r,s,l,d,m){ui[e]={name:Tt(r),hf:Ot(s,l),ke:Ot(d,m),rf:[]}},e:function(e,r,s,l,d,m,P,y,v,A){ui[e].rf.push({Of:Tt(r),Vf:s,Tf:Ot(l,d),Uf:m,fg:P,eg:Ot(y,v),gg:A})},Ib:function(e,r){r=Tt(r),le(e,{Yf:!0,name:r,argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},Fb:()=>!0,ub:()=>{throw 1/0},F:function(e,r,s){e=Vt(e),r=Qe(r,"emval::as");var l=[],d=qt(l);return Pt[s>>2]=d,r.toWireType(l,e)},Z:function(e,r,s,l,d){e=wi[e],r=Vt(r),s=vi(s);var m=[];return Pt[l>>2]=qt(m),e(r,s,m,d)},w:function(e,r,s,l){e=wi[e],r=Vt(r),s=vi(s),e(r,s,null,l)},d:qi,K:function(e){return e===0?qt(Br()):(e=vi(e),qt(Br()[e]))},u:function(e,r){var s=ms(e,r),l=s[0];r=l.name+"_$"+s.slice(1).map(function(P){return P.name}).join("_")+"$";var d=Ur[r];if(d!==void 0)return d;var m=Array(e-1);return d=ps((P,y,v,A)=>{for(var O=0,D=0;D<e-1;++D)m[D]=s[D+1].readValueFromPointer(A+O),O+=s[D+1].argPackAdvance;for(P=P[y].apply(P,m),D=0;D<e-1;++D)s[D+1].Lf&&s[D+1].Lf(m[D]);if(!l.Yf)return l.toWireType(v,P)}),Ur[r]=d},z:function(e,r){return e=Vt(e),r=Vt(r),qt(e[r])},p:function(e){4<e&&(Kt.get(e).wf+=1)},J:function(e,r,s,l){e=Vt(e);var d=$r[r];return d||(d=gs(r),$r[r]=d),d(e,s,l)},H:function(){return qt([])},g:function(e){return qt(vi(e))},G:function(){return qt({})},kb:function(e){return e=Vt(e),!e},B:function(e){var r=Vt(e);Ui(r),qi(e)},i:function(e,r,s){e=Vt(e),r=Vt(r),s=Vt(s),e[r]=s},h:function(e,r){return e=Qe(e,"_emval_take_value"),e=e.readValueFromPointer(r),qt(e)},nb:function(){return-52},ob:function(){},a:()=>{zi("")},Eb:()=>performance.now(),vb:e=>{var r=ht.length;if(e>>>=0,2147483648<e)return!1;for(var s=1;4>=s;s*=2){var l=r*(1+.2/s);l=Math.min(l,e+100663296);var d=Math;l=Math.max(e,l);t:{d=d.min.call(d,2147483648,l+(65536-l%65536)%65536)-ci.buffer.byteLength+65535>>>16;try{ci.grow(d),vr();var m=1;break t}catch{}m=void 0}if(m)return!0}return!1},lb:function(){return rt?rt.handle:0},wb:(e,r)=>{var s=0;return Vr().forEach(function(l,d){var m=r+s;for(d=Pt[e+4*d>>2]=m,m=0;m<l.length;++m)oe[d++>>0]=l.charCodeAt(m);oe[d>>0]=0,s+=l.length+1}),0},xb:(e,r)=>{var s=Vr();Pt[e>>2]=s.length;var l=0;return s.forEach(function(d){l+=d.length+1}),Pt[r>>2]=l,0},Jb:e=>{Kn||(h.onExit&&h.onExit(e),Di=!0),it(e,new Jn(e))},M:()=>52,mb:function(){return 52},Cb:()=>52,pb:function(){return 70},S:(e,r,s,l)=>{for(var d=0,m=0;m<s;m++){var P=Pt[r>>2],y=Pt[r+4>>2];r+=8;for(var v=0;v<y;v++){var A=ht[P+v],O=As[e];A===0||A===10?((e===1?at:we)(_e(O,0)),O.length=0):O.push(A)}d+=y}return Pt[l>>2]=d,0},aa:function(e){E.activeTexture(e)},ba:function(e,r){E.attachShader(re[e],ne[r])},ca:function(e,r,s){E.bindAttribLocation(re[e],r,s?_e(ht,s):"")},da:function(e,r){e==35051?E.ef=r:e==35052&&(E.De=r),E.bindBuffer(e,Si[r])},$:function(e,r){E.bindFramebuffer(e,bi[r])},fc:function(e,r){E.bindRenderbuffer(e,Ze[r])},Rb:function(e,r){E.bindSampler(e,Fe[r])},ea:function(e,r){E.bindTexture(e,Yt[r])},zc:qr,Cc:qr,fa:function(e,r,s,l){E.blendColor(e,r,s,l)},ga:function(e){E.blendEquation(e)},ha:function(e,r){E.blendFunc(e,r)},$b:function(e,r,s,l,d,m,P,y,v,A){E.blitFramebuffer(e,r,s,l,d,m,P,y,v,A)},ia:function(e,r,s,l){2<=rt.version?s&&r?E.bufferData(e,ht,l,s,r):E.bufferData(e,r,l):E.bufferData(e,s?ht.subarray(s,s+r):r,l)},ja:function(e,r,s,l){2<=rt.version?s&&E.bufferSubData(e,r,ht,l,s):E.bufferSubData(e,r,ht.subarray(l,l+s))},gc:function(e){return E.checkFramebufferStatus(e)},Q:function(e){E.clear(e)},_:function(e,r,s,l){E.clearColor(e,r,s,l)},R:function(e){E.clearStencil(e)},sb:function(e,r,s,l){return E.clientWaitSync(Me[e],r,(s>>>0)+4294967296*l)},ka:function(e,r,s,l){E.colorMask(!!e,!!r,!!s,!!l)},la:function(e){E.compileShader(ne[e])},ma:function(e,r,s,l,d,m,P,y){2<=rt.version?E.De||!P?E.compressedTexImage2D(e,r,s,l,d,m,P,y):E.compressedTexImage2D(e,r,s,l,d,m,ht,y,P):E.compressedTexImage2D(e,r,s,l,d,m,y?ht.subarray(y,y+P):null)},na:function(e,r,s,l,d,m,P,y,v){2<=rt.version?E.De||!y?E.compressedTexSubImage2D(e,r,s,l,d,m,P,y,v):E.compressedTexSubImage2D(e,r,s,l,d,m,P,ht,v,y):E.compressedTexSubImage2D(e,r,s,l,d,m,P,v?ht.subarray(v,v+y):null)},Zb:function(e,r,s,l,d){E.copyBufferSubData(e,r,s,l,d)},oa:function(e,r,s,l,d,m,P,y){E.copyTexSubImage2D(e,r,s,l,d,m,P,y)},pa:function(){var e=De(re),r=E.createProgram();return r.name=e,r.Ye=r.We=r.Xe=0,r.kf=1,re[e]=r,e},qa:function(e){var r=De(ne);return ne[r]=E.createShader(e),r},ra:function(e){E.cullFace(e)},sa:function(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2],d=Si[l];d&&(E.deleteBuffer(d),d.name=0,Si[l]=null,l==E.ef&&(E.ef=0),l==E.De&&(E.De=0))}},hc:function(e,r){for(var s=0;s<e;++s){var l=G[r+4*s>>2],d=bi[l];d&&(E.deleteFramebuffer(d),d.name=0,bi[l]=null)}},ta:function(e){if(e){var r=re[e];r?(E.deleteProgram(r),r.name=0,re[e]=null):At(1281)}},ic:function(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2],d=Ze[l];d&&(E.deleteRenderbuffer(d),d.name=0,Ze[l]=null)}},Sb:function(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2],d=Fe[l];d&&(E.deleteSampler(d),d.name=0,Fe[l]=null)}},ua:function(e){if(e){var r=ne[e];r?(E.deleteShader(r),ne[e]=null):At(1281)}},_b:function(e){if(e){var r=Me[e];r?(E.deleteSync(r),r.name=0,Me[e]=null):At(1281)}},va:function(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2],d=Yt[l];d&&(E.deleteTexture(d),d.name=0,Yt[l]=null)}},Ac:Yr,Dc:Yr,wa:function(e){E.depthMask(!!e)},xa:function(e){E.disable(e)},ya:function(e){E.disableVertexAttribArray(e)},za:function(e,r,s){E.drawArrays(e,r,s)},xc:function(e,r,s,l){E.drawArraysInstanced(e,r,s,l)},vc:function(e,r,s,l,d){E.pf.drawArraysInstancedBaseInstanceWEBGL(e,r,s,l,d)},tc:function(e,r){for(var s=Ci[e],l=0;l<e;l++)s[l]=G[r+4*l>>2];E.drawBuffers(s)},Aa:Jr,yc:function(e,r,s,l,d){E.drawElementsInstanced(e,r,s,l,d)},wc:function(e,r,s,l,d,m,P){E.pf.drawElementsInstancedBaseVertexBaseInstanceWEBGL(e,r,s,l,d,m,P)},nc:function(e,r,s,l,d,m){Jr(e,l,d,m)},Ba:function(e){E.enable(e)},Ca:function(e){E.enableVertexAttribArray(e)},Xb:function(e,r){return(e=E.fenceSync(e,r))?(r=De(Me),e.name=r,Me[r]=e,r):0},Da:function(){E.finish()},Ea:function(){E.flush()},jc:function(e,r,s,l){E.framebufferRenderbuffer(e,r,s,Ze[l])},kc:function(e,r,s,l,d){E.framebufferTexture2D(e,r,s,Yt[l],d)},Fa:function(e){E.frontFace(e)},Ga:function(e,r){ze(e,r,"createBuffer",Si)},lc:function(e,r){ze(e,r,"createFramebuffer",bi)},mc:function(e,r){ze(e,r,"createRenderbuffer",Ze)},Tb:function(e,r){ze(e,r,"createSampler",Fe)},Ha:function(e,r){ze(e,r,"createTexture",Yt)},Bc:Xr,Ec:Xr,bc:function(e){E.generateMipmap(e)},Ia:function(e,r,s){s?G[s>>2]=E.getBufferParameter(e,r):At(1281)},Ja:function(){var e=E.getError()||Ai;return Ai=0,e},Ka:function(e,r){Qr(e,r,2)},cc:function(e,r,s,l){e=E.getFramebufferAttachmentParameter(e,r,s),(e instanceof WebGLRenderbuffer||e instanceof WebGLTexture)&&(e=e.name|0),G[l>>2]=e},L:function(e,r){Qr(e,r,0)},La:function(e,r,s,l){e=E.getProgramInfoLog(re[e]),e===null&&(e="(unknown error)"),r=0<r&&l?ee(e,ht,l,r):0,s&&(G[s>>2]=r)},Ma:function(e,r,s){if(s)if(e>=Wr)At(1281);else if(e=re[e],r==35716)e=E.getProgramInfoLog(e),e===null&&(e="(unknown error)"),G[s>>2]=e.length+1;else if(r==35719){if(!e.Ye)for(r=0;r<E.getProgramParameter(e,35718);++r)e.Ye=Math.max(e.Ye,E.getActiveUniform(e,r).name.length+1);G[s>>2]=e.Ye}else if(r==35722){if(!e.We)for(r=0;r<E.getProgramParameter(e,35721);++r)e.We=Math.max(e.We,E.getActiveAttrib(e,r).name.length+1);G[s>>2]=e.We}else if(r==35381){if(!e.Xe)for(r=0;r<E.getProgramParameter(e,35382);++r)e.Xe=Math.max(e.Xe,E.getActiveUniformBlockName(e,r).length+1);G[s>>2]=e.Xe}else G[s>>2]=E.getProgramParameter(e,r);else At(1281)},dc:function(e,r,s){s?G[s>>2]=E.getRenderbufferParameter(e,r):At(1281)},Na:function(e,r,s,l){e=E.getShaderInfoLog(ne[e]),e===null&&(e="(unknown error)"),r=0<r&&l?ee(e,ht,l,r):0,s&&(G[s>>2]=r)},Ob:function(e,r,s,l){e=E.getShaderPrecisionFormat(e,r),G[s>>2]=e.rangeMin,G[s+4>>2]=e.rangeMax,G[l>>2]=e.precision},Oa:function(e,r,s){s?r==35716?(e=E.getShaderInfoLog(ne[e]),e===null&&(e="(unknown error)"),G[s>>2]=e?e.length+1:0):r==35720?(e=E.getShaderSource(ne[e]),G[s>>2]=e?e.length+1:0):G[s>>2]=E.getShaderParameter(ne[e],r):At(1281)},P:function(e){var r=Gr[e];if(!r){switch(e){case 7939:r=E.getSupportedExtensions()||[],r=r.concat(r.map(function(l){return"GL_"+l})),r=ti(r.join(" "));break;case 7936:case 7937:case 37445:case 37446:(r=E.getParameter(e))||At(1280),r=r&&ti(r);break;case 7938:r=E.getParameter(7938),r=2<=rt.version?"OpenGL ES 3.0 ("+r+")":"OpenGL ES 2.0 ("+r+")",r=ti(r);break;case 35724:r=E.getParameter(35724);var s=r.match(/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/);s!==null&&(s[1].length==3&&(s[1]+="0"),r="OpenGL ES GLSL ES "+s[1]+" ("+r+")"),r=ti(r);break;default:At(1280)}Gr[e]=r}return r},jb:function(e,r){if(2>rt.version)return At(1282),0;var s=jr[e];if(s)return 0>r||r>=s.length?(At(1281),0):s[r];switch(e){case 7939:return s=E.getSupportedExtensions()||[],s=s.concat(s.map(function(l){return"GL_"+l})),s=s.map(function(l){return ti(l)}),s=jr[e]=s,0>r||r>=s.length?(At(1281),0):s[r];default:return At(1280),0}},Pa:function(e,r){if(r=r?_e(ht,r):"",e=re[e]){var s=e,l=s.Ne,d=s.yf,m;if(!l)for(s.Ne=l={},s.xf={},m=0;m<E.getProgramParameter(s,35718);++m){var P=E.getActiveUniform(s,m),y=P.name;P=P.size;var v=Zr(y);v=0<v?y.slice(0,v):y;var A=s.kf;for(s.kf+=P,d[v]=[P,A],y=0;y<P;++y)l[A]=y,s.xf[A++]=v}if(s=e.Ne,l=0,d=r,m=Zr(r),0<m&&(l=parseInt(r.slice(m+1))>>>0,d=r.slice(0,m)),(d=e.yf[d])&&l<d[0]&&(l+=d[1],s[l]=s[l]||E.getUniformLocation(e,r)))return l}else At(1281);return-1},Pb:function(e,r,s){for(var l=Ci[r],d=0;d<r;d++)l[d]=G[s+4*d>>2];E.invalidateFramebuffer(e,l)},Qb:function(e,r,s,l,d,m,P){for(var y=Ci[r],v=0;v<r;v++)y[v]=G[s+4*v>>2];E.invalidateSubFramebuffer(e,y,l,d,m,P)},Yb:function(e){return E.isSync(Me[e])},Qa:function(e){return(e=Yt[e])?E.isTexture(e):0},Ra:function(e){E.lineWidth(e)},Sa:function(e){e=re[e],E.linkProgram(e),e.Ne=0,e.yf={}},rc:function(e,r,s,l,d,m){E.uf.multiDrawArraysInstancedBaseInstanceWEBGL(e,G,r>>2,G,s>>2,G,l>>2,Pt,d>>2,m)},sc:function(e,r,s,l,d,m,P,y){E.uf.multiDrawElementsInstancedBaseVertexBaseInstanceWEBGL(e,G,r>>2,s,G,l>>2,G,d>>2,G,m>>2,Pt,P>>2,y)},Ta:function(e,r){e==3317&&(Hr=r),E.pixelStorei(e,r)},uc:function(e){E.readBuffer(e)},Ua:function(e,r,s,l,d,m,P){if(2<=rt.version)if(E.ef)E.readPixels(e,r,s,l,d,m,P);else{var y=Ei(m);E.readPixels(e,r,s,l,d,m,y,P>>31-Math.clz32(y.BYTES_PER_ELEMENT))}else(P=Qi(m,d,s,l,P))?E.readPixels(e,r,s,l,d,m,P):At(1280)},ec:function(e,r,s,l){E.renderbufferStorage(e,r,s,l)},ac:function(e,r,s,l,d){E.renderbufferStorageMultisample(e,r,s,l,d)},Ub:function(e,r,s){E.samplerParameterf(Fe[e],r,s)},Vb:function(e,r,s){E.samplerParameteri(Fe[e],r,s)},Wb:function(e,r,s){E.samplerParameteri(Fe[e],r,G[s>>2])},Va:function(e,r,s,l){E.scissor(e,r,s,l)},Wa:function(e,r,s,l){for(var d="",m=0;m<r;++m){var P=l?G[l+4*m>>2]:-1,y=G[s+4*m>>2];P=y?_e(ht,y,0>P?void 0:P):"",d+=P}E.shaderSource(ne[e],d)},Xa:function(e,r,s){E.stencilFunc(e,r,s)},Ya:function(e,r,s,l){E.stencilFuncSeparate(e,r,s,l)},Za:function(e){E.stencilMask(e)},_a:function(e,r){E.stencilMaskSeparate(e,r)},$a:function(e,r,s){E.stencilOp(e,r,s)},ab:function(e,r,s,l){E.stencilOpSeparate(e,r,s,l)},bb:function(e,r,s,l,d,m,P,y,v){if(2<=rt.version)if(E.De)E.texImage2D(e,r,s,l,d,m,P,y,v);else if(v){var A=Ei(y);E.texImage2D(e,r,s,l,d,m,P,y,A,v>>31-Math.clz32(A.BYTES_PER_ELEMENT))}else E.texImage2D(e,r,s,l,d,m,P,y,null);else E.texImage2D(e,r,s,l,d,m,P,y,v?Qi(y,P,l,d,v):null)},cb:function(e,r,s){E.texParameterf(e,r,s)},db:function(e,r,s){E.texParameterf(e,r,tt[s>>2])},eb:function(e,r,s){E.texParameteri(e,r,s)},fb:function(e,r,s){E.texParameteri(e,r,G[s>>2])},oc:function(e,r,s,l,d){E.texStorage2D(e,r,s,l,d)},gb:function(e,r,s,l,d,m,P,y,v){if(2<=rt.version)if(E.De)E.texSubImage2D(e,r,s,l,d,m,P,y,v);else if(v){var A=Ei(y);E.texSubImage2D(e,r,s,l,d,m,P,y,A,v>>31-Math.clz32(A.BYTES_PER_ELEMENT))}else E.texSubImage2D(e,r,s,l,d,m,P,y,null);else A=null,v&&(A=Qi(y,P,d,m,v)),E.texSubImage2D(e,r,s,l,d,m,P,y,A)},hb:function(e,r){E.uniform1f(vt(e),r)},ib:function(e,r,s){if(2<=rt.version)r&&E.uniform1fv(vt(e),tt,s>>2,r);else{if(288>=r)for(var l=Pe[r-1],d=0;d<r;++d)l[d]=tt[s+4*d>>2];else l=tt.subarray(s>>2,s+4*r>>2);E.uniform1fv(vt(e),l)}},Zc:function(e,r){E.uniform1i(vt(e),r)},_c:function(e,r,s){if(2<=rt.version)r&&E.uniform1iv(vt(e),G,s>>2,r);else{if(288>=r)for(var l=ei[r-1],d=0;d<r;++d)l[d]=G[s+4*d>>2];else l=G.subarray(s>>2,s+4*r>>2);E.uniform1iv(vt(e),l)}},$c:function(e,r,s){E.uniform2f(vt(e),r,s)},ad:function(e,r,s){if(2<=rt.version)r&&E.uniform2fv(vt(e),tt,s>>2,2*r);else{if(144>=r)for(var l=Pe[2*r-1],d=0;d<2*r;d+=2)l[d]=tt[s+4*d>>2],l[d+1]=tt[s+(4*d+4)>>2];else l=tt.subarray(s>>2,s+8*r>>2);E.uniform2fv(vt(e),l)}},Yc:function(e,r,s){E.uniform2i(vt(e),r,s)},Xc:function(e,r,s){if(2<=rt.version)r&&E.uniform2iv(vt(e),G,s>>2,2*r);else{if(144>=r)for(var l=ei[2*r-1],d=0;d<2*r;d+=2)l[d]=G[s+4*d>>2],l[d+1]=G[s+(4*d+4)>>2];else l=G.subarray(s>>2,s+8*r>>2);E.uniform2iv(vt(e),l)}},Wc:function(e,r,s,l){E.uniform3f(vt(e),r,s,l)},Vc:function(e,r,s){if(2<=rt.version)r&&E.uniform3fv(vt(e),tt,s>>2,3*r);else{if(96>=r)for(var l=Pe[3*r-1],d=0;d<3*r;d+=3)l[d]=tt[s+4*d>>2],l[d+1]=tt[s+(4*d+4)>>2],l[d+2]=tt[s+(4*d+8)>>2];else l=tt.subarray(s>>2,s+12*r>>2);E.uniform3fv(vt(e),l)}},Uc:function(e,r,s,l){E.uniform3i(vt(e),r,s,l)},Tc:function(e,r,s){if(2<=rt.version)r&&E.uniform3iv(vt(e),G,s>>2,3*r);else{if(96>=r)for(var l=ei[3*r-1],d=0;d<3*r;d+=3)l[d]=G[s+4*d>>2],l[d+1]=G[s+(4*d+4)>>2],l[d+2]=G[s+(4*d+8)>>2];else l=G.subarray(s>>2,s+12*r>>2);E.uniform3iv(vt(e),l)}},Sc:function(e,r,s,l,d){E.uniform4f(vt(e),r,s,l,d)},Rc:function(e,r,s){if(2<=rt.version)r&&E.uniform4fv(vt(e),tt,s>>2,4*r);else{if(72>=r){var l=Pe[4*r-1],d=tt;s>>=2;for(var m=0;m<4*r;m+=4){var P=s+m;l[m]=d[P],l[m+1]=d[P+1],l[m+2]=d[P+2],l[m+3]=d[P+3]}}else l=tt.subarray(s>>2,s+16*r>>2);E.uniform4fv(vt(e),l)}},Fc:function(e,r,s,l,d){E.uniform4i(vt(e),r,s,l,d)},Gc:function(e,r,s){if(2<=rt.version)r&&E.uniform4iv(vt(e),G,s>>2,4*r);else{if(72>=r)for(var l=ei[4*r-1],d=0;d<4*r;d+=4)l[d]=G[s+4*d>>2],l[d+1]=G[s+(4*d+4)>>2],l[d+2]=G[s+(4*d+8)>>2],l[d+3]=G[s+(4*d+12)>>2];else l=G.subarray(s>>2,s+16*r>>2);E.uniform4iv(vt(e),l)}},Hc:function(e,r,s,l){if(2<=rt.version)r&&E.uniformMatrix2fv(vt(e),!!s,tt,l>>2,4*r);else{if(72>=r)for(var d=Pe[4*r-1],m=0;m<4*r;m+=4)d[m]=tt[l+4*m>>2],d[m+1]=tt[l+(4*m+4)>>2],d[m+2]=tt[l+(4*m+8)>>2],d[m+3]=tt[l+(4*m+12)>>2];else d=tt.subarray(l>>2,l+16*r>>2);E.uniformMatrix2fv(vt(e),!!s,d)}},Ic:function(e,r,s,l){if(2<=rt.version)r&&E.uniformMatrix3fv(vt(e),!!s,tt,l>>2,9*r);else{if(32>=r)for(var d=Pe[9*r-1],m=0;m<9*r;m+=9)d[m]=tt[l+4*m>>2],d[m+1]=tt[l+(4*m+4)>>2],d[m+2]=tt[l+(4*m+8)>>2],d[m+3]=tt[l+(4*m+12)>>2],d[m+4]=tt[l+(4*m+16)>>2],d[m+5]=tt[l+(4*m+20)>>2],d[m+6]=tt[l+(4*m+24)>>2],d[m+7]=tt[l+(4*m+28)>>2],d[m+8]=tt[l+(4*m+32)>>2];else d=tt.subarray(l>>2,l+36*r>>2);E.uniformMatrix3fv(vt(e),!!s,d)}},Jc:function(e,r,s,l){if(2<=rt.version)r&&E.uniformMatrix4fv(vt(e),!!s,tt,l>>2,16*r);else{if(18>=r){var d=Pe[16*r-1],m=tt;l>>=2;for(var P=0;P<16*r;P+=16){var y=l+P;d[P]=m[y],d[P+1]=m[y+1],d[P+2]=m[y+2],d[P+3]=m[y+3],d[P+4]=m[y+4],d[P+5]=m[y+5],d[P+6]=m[y+6],d[P+7]=m[y+7],d[P+8]=m[y+8],d[P+9]=m[y+9],d[P+10]=m[y+10],d[P+11]=m[y+11],d[P+12]=m[y+12],d[P+13]=m[y+13],d[P+14]=m[y+14],d[P+15]=m[y+15]}}else d=tt.subarray(l>>2,l+64*r>>2);E.uniformMatrix4fv(vt(e),!!s,d)}},Kc:function(e){e=re[e],E.useProgram(e),E.Kf=e},Lc:function(e,r){E.vertexAttrib1f(e,r)},Mc:function(e,r){E.vertexAttrib2f(e,tt[r>>2],tt[r+4>>2])},Nc:function(e,r){E.vertexAttrib3f(e,tt[r>>2],tt[r+4>>2],tt[r+8>>2])},Oc:function(e,r){E.vertexAttrib4f(e,tt[r>>2],tt[r+4>>2],tt[r+8>>2],tt[r+12>>2])},pc:function(e,r){E.vertexAttribDivisor(e,r)},qc:function(e,r,s,l,d){E.vertexAttribIPointer(e,r,s,l,d)},Pc:function(e,r,s,l,d,m){E.vertexAttribPointer(e,r,s,!!l,d,m)},Qc:function(e,r,s,l){E.viewport(e,r,s,l)},rb:function(e,r,s,l){E.waitSync(Me[e],r,(s>>>0)+4294967296*l)},j:xs,n:Ds,k:Ms,I:Bs,Lb:Us,Y:$s,X:Gs,O:Os,o:Ls,x:ks,r:Ns,v:Is,Kb:Ws,Mb:zs,Nb:Rs,tb:(e,r,s,l)=>Es(e,r,s,l)};(function(){function e(s){if(dt=s=s.exports,ci=dt.bd,vr(),Rt=dt.dd,Sr.unshift(dt.cd),Ee--,h.monitorRunDependencies&&h.monitorRunDependencies(Ee),Ee==0&&He){var l=He;He=null,l()}return s}var r={a:Fs};if(Ee++,h.monitorRunDependencies&&h.monitorRunDependencies(Ee),h.instantiateWasm)try{return h.instantiateWasm(r,e)}catch(s){we("Module.instantiateWasm callback failed with error: "+s),T(s)}return Yn(r,function(s){e(s.instance)}).catch(T),{}})();var me=h._free=e=>(me=h._free=dt.ed)(e),Fi=h._malloc=e=>(Fi=h._malloc=dt.fd)(e),nn=e=>(nn=dt.gd)(e);h.__embind_initialize_bindings=()=>(h.__embind_initialize_bindings=dt.hd)();var It=(e,r)=>(It=dt.id)(e,r),Lt=()=>(Lt=dt.jd)(),Dt=e=>(Dt=dt.kd)(e);h.dynCall_viji=(e,r,s,l,d)=>(h.dynCall_viji=dt.ld)(e,r,s,l,d),h.dynCall_vijiii=(e,r,s,l,d,m,P)=>(h.dynCall_vijiii=dt.md)(e,r,s,l,d,m,P),h.dynCall_viiiiij=(e,r,s,l,d,m,P,y)=>(h.dynCall_viiiiij=dt.nd)(e,r,s,l,d,m,P,y),h.dynCall_jiiiijiiiii=(e,r,s,l,d,m,P,y,v,A,O,D)=>(h.dynCall_jiiiijiiiii=dt.od)(e,r,s,l,d,m,P,y,v,A,O,D),h.dynCall_viiij=(e,r,s,l,d,m)=>(h.dynCall_viiij=dt.pd)(e,r,s,l,d,m),h.dynCall_jii=(e,r,s)=>(h.dynCall_jii=dt.qd)(e,r,s),h.dynCall_vij=(e,r,s,l)=>(h.dynCall_vij=dt.rd)(e,r,s,l),h.dynCall_iiij=(e,r,s,l,d)=>(h.dynCall_iiij=dt.sd)(e,r,s,l,d),h.dynCall_iiiij=(e,r,s,l,d,m)=>(h.dynCall_iiiij=dt.td)(e,r,s,l,d,m),h.dynCall_viij=(e,r,s,l,d)=>(h.dynCall_viij=dt.ud)(e,r,s,l,d),h.dynCall_ji=(e,r)=>(h.dynCall_ji=dt.vd)(e,r),h.dynCall_iij=(e,r,s,l)=>(h.dynCall_iij=dt.wd)(e,r,s,l),h.dynCall_jiiiiii=(e,r,s,l,d,m,P)=>(h.dynCall_jiiiiii=dt.xd)(e,r,s,l,d,m,P),h.dynCall_jiiiiji=(e,r,s,l,d,m,P,y)=>(h.dynCall_jiiiiji=dt.yd)(e,r,s,l,d,m,P,y),h.dynCall_iijj=(e,r,s,l,d,m)=>(h.dynCall_iijj=dt.zd)(e,r,s,l,d,m),h.dynCall_iiiji=(e,r,s,l,d,m)=>(h.dynCall_iiiji=dt.Ad)(e,r,s,l,d,m),h.dynCall_iiji=(e,r,s,l,d)=>(h.dynCall_iiji=dt.Bd)(e,r,s,l,d),h.dynCall_iijjiii=(e,r,s,l,d,m,P,y,v)=>(h.dynCall_iijjiii=dt.Cd)(e,r,s,l,d,m,P,y,v),h.dynCall_vijjjii=(e,r,s,l,d,m,P,y,v,A)=>(h.dynCall_vijjjii=dt.Dd)(e,r,s,l,d,m,P,y,v,A),h.dynCall_jiji=(e,r,s,l,d)=>(h.dynCall_jiji=dt.Ed)(e,r,s,l,d),h.dynCall_viijii=(e,r,s,l,d,m,P)=>(h.dynCall_viijii=dt.Fd)(e,r,s,l,d,m,P),h.dynCall_iiiiij=(e,r,s,l,d,m,P)=>(h.dynCall_iiiiij=dt.Gd)(e,r,s,l,d,m,P),h.dynCall_iiiiijj=(e,r,s,l,d,m,P,y,v)=>(h.dynCall_iiiiijj=dt.Hd)(e,r,s,l,d,m,P,y,v),h.dynCall_iiiiiijj=(e,r,s,l,d,m,P,y,v,A)=>(h.dynCall_iiiiiijj=dt.Id)(e,r,s,l,d,m,P,y,v,A);function Ms(e,r,s,l){var d=Lt();try{return Rt.get(e)(r,s,l)}catch(m){if(Dt(d),m!==m+0)throw m;It(1,0)}}function xs(e,r){var s=Lt();try{return Rt.get(e)(r)}catch(l){if(Dt(s),l!==l+0)throw l;It(1,0)}}function Rs(e,r,s,l,d,m,P,y,v,A){var O=Lt();try{Rt.get(e)(r,s,l,d,m,P,y,v,A)}catch(D){if(Dt(O),D!==D+0)throw D;It(1,0)}}function Ns(e,r,s,l){var d=Lt();try{Rt.get(e)(r,s,l)}catch(m){if(Dt(d),m!==m+0)throw m;It(1,0)}}function ks(e,r,s){var l=Lt();try{Rt.get(e)(r,s)}catch(d){if(Dt(l),d!==d+0)throw d;It(1,0)}}function Os(e){var r=Lt();try{Rt.get(e)()}catch(s){if(Dt(r),s!==s+0)throw s;It(1,0)}}function Is(e,r,s,l,d){var m=Lt();try{Rt.get(e)(r,s,l,d)}catch(P){if(Dt(m),P!==P+0)throw P;It(1,0)}}function Ls(e,r){var s=Lt();try{Rt.get(e)(r)}catch(l){if(Dt(s),l!==l+0)throw l;It(1,0)}}function Ds(e,r,s){var l=Lt();try{return Rt.get(e)(r,s)}catch(d){if(Dt(l),d!==d+0)throw d;It(1,0)}}function zs(e,r,s,l,d,m,P){var y=Lt();try{Rt.get(e)(r,s,l,d,m,P)}catch(v){if(Dt(y),v!==v+0)throw v;It(1,0)}}function Bs(e,r,s,l,d){var m=Lt();try{return Rt.get(e)(r,s,l,d)}catch(P){if(Dt(m),P!==P+0)throw P;It(1,0)}}function Us(e,r,s,l,d,m){var P=Lt();try{return Rt.get(e)(r,s,l,d,m)}catch(y){if(Dt(P),y!==y+0)throw y;It(1,0)}}function $s(e,r,s,l,d,m,P){var y=Lt();try{return Rt.get(e)(r,s,l,d,m,P)}catch(v){if(Dt(y),v!==v+0)throw v;It(1,0)}}function Ws(e,r,s,l,d,m){var P=Lt();try{Rt.get(e)(r,s,l,d,m)}catch(y){if(Dt(P),y!==y+0)throw y;It(1,0)}}function Gs(e,r,s,l,d,m,P,y,v,A){var O=Lt();try{return Rt.get(e)(r,s,l,d,m,P,y,v,A)}catch(D){if(Dt(O),D!==D+0)throw D;It(1,0)}}var Mi;He=function e(){Mi||sn(),Mi||(He=e)};function sn(){function e(){if(!Mi&&(Mi=!0,h.calledRun=!0,!Di)){if(Bi(Sr),C(h),h.onRuntimeInitialized&&h.onRuntimeInitialized(),h.postRun)for(typeof h.postRun=="function"&&(h.postRun=[h.postRun]);h.postRun.length;){var r=h.postRun.shift();br.unshift(r)}Bi(br)}}if(!(0<Ee)){if(h.preRun)for(typeof h.preRun=="function"&&(h.preRun=[h.preRun]);h.preRun.length;)Vn();Bi(wr),0<Ee||(h.setStatus?(h.setStatus("Running..."),setTimeout(function(){setTimeout(function(){h.setStatus("")},1),e()},1)):e())}}if(h.preInit)for(typeof h.preInit=="function"&&(h.preInit=[h.preInit]);0<h.preInit.length;)h.preInit.pop()();return sn(),c.ready}})();g.exports=i}(cr)),cr.exports}var ha=la(),ca=Zs(ha);class We{static slide(t){let i=Re.linear;return typeof t.easing=="string"?i=Re.fromTypeAsString(t.easing):t.easing!==void 0&&(i=t.easing),new Bn(t.direction,t.duration,i)}static none(){return new zn}}class zn extends We{constructor(){super(),this.type=ge.None,this.duration=NaN,this.easing=Re.none}}class Bn extends We{constructor(t,i,n){super(),this.type=ge.Slide,this.direction=t,this.duration=i,this.easing=n}}const ge={Slide:"Slide",None:"None"},ye={Up:"Up",Down:"Down",Right:"Right",Left:"Left"};class Un{constructor(t,i){this.scene=t,this.transition=i}}const $n={type:"object",description:"Information about the user's device.",properties:{userAgent:{type:"string",description:"The user agent string returned by navigator.userAgent."},devicePixelRatio:{type:"number",description:"Ratio of physical pixels to CSS pixels."},screen:{type:"object",description:"Screen information returned by window.screen.",properties:{availHeight:{type:"number",description:"Height of screen, in pixels, excluding UI features."},availWidth:{type:"number",description:"Width of screen, in pixels, excluding UI features."},colorDepth:{type:"number",description:"Color depth of screen."},height:{type:"number",description:"Height of screen, in pixels"},width:{type:"number",description:"Width of screen, in pixels."},orientation:{type:"object",description:"Information about the device's orientation.",properties:{type:{type:"string",description:"The orientation type (ScreenOrientation.type)."},angle:{type:"number",description:"The orientation angle (ScreenOrientation.angle)."}}},pixelDepth:{type:"number",description:"Pixel depth of screen."}}},webGlRenderer:{type:"string",description:"WebGL driver vendor and renderer. Taken from WEBGL_debug_renderer_info."}}};class mr{static getRendererString(){const t=document.createElement("canvas");t.id="webgl-renderer-info-canvas",t.height=0,t.width=0,t.hidden=!0,document.body.appendChild(t);const i=t.getContext("webgl");let n="no webgl context";if(!i)return n;const c=i.getExtension("WEBGL_debug_renderer_info");return c!=null?n=String(i.getParameter(c.UNMASKED_VENDOR_WEBGL))+", "+String(i.getParameter(c.UNMASKED_RENDERER_WEBGL)):n="no debug renderer info",t.remove(),n}static dispose(){const t=document.getElementById("webgl-renderer-info-canvas");t&&t.remove()}}class Wn{constructor(t,i){this.sounds={},this.game=t,this.baseUrls=i}get audioContext(){if(!this._audioContext){if(!navigator.userActivation.hasBeenActive)throw new Error("AudioContext cannot be created until user has interacted with the page");this._audioContext=new AudioContext}return this._audioContext}initializeSounds(t){return t?this.loadSounds(t):Promise.resolve()}loadSounds(t){return t.length===0?Promise.resolve():(t.forEach(i=>{let n=i.url;Y.urlHasScheme(i.url)||(n=Y.getUrlFromManifest(this.game,`${this.baseUrls.assets}/${i.url}`));const c={soundName:i.soundName,data:void 0,audioBuffer:void 0,url:n,status:i.lazy?Ut.Deferred:Ut.WillFetch};this.sounds[i.soundName]&&console.warn(`A sound named ${i.soundName} has already been loaded. It will be replaced.`),this.sounds[i.soundName]=c}),this.fetchSounds())}async fetchSounds(){const t=Object.values(this.sounds).map(i=>i.status===Ut.WillFetch?(i.status=Ut.Fetching,fetch(i.url).then(n=>{if(!n.ok)throw i.status=Ut.Error,new Error(`cannot fetch sound ${i.soundName} at url ${i.url}: ${n.statusText}`);return n.arrayBuffer().then(c=>{i.data=c,i.status=Ut.Fetched,console.log(`\u26AA sound fetched. name: ${i.soundName}, bytes: ${c.byteLength}`)})})):Promise.resolve());await Promise.all(t)}fetchDeferredSound(t){return t.status=Ut.WillFetch,this.fetchSounds()}hasSoundsToDecode(){return Object.values(this.sounds).filter(t=>t.status===Ut.Fetched).length>0}decodeFetchedSounds(){const i=Object.values(this.sounds).filter(n=>n.status===Ut.Fetched).map(n=>this.decodeSound(n));return Promise.all(i)}async decodeSound(t){if(!t.data)throw new Error(`data is undefined for sound ${t.soundName} (url ${t.url})`);try{t.status=Ut.Decoding;const i=await this.audioContext.decodeAudioData(t.data);t.audioBuffer=i,t.status=Ut.Ready,console.log(`\u26AA sound decoded. name: ${t.soundName}, duration (seconds): ${i.duration}`)}catch{throw t.status=Ut.Error,new Error(`error decoding sound ${t.soundName} (url: ${t.url})`)}}getSound(t){const i=this.sounds[t];if(!i)throw new Error(`getSound(): sound ${t} not found`);return i}dispose(){}getSoundNames(){return Object.keys(this.sounds)}}class ua{constructor(t){this.game=t.game,this.nodeFactory=t.nodeFactory,this.freeNodesScene=t.freeNodesScene,this.configureI18n=t.configureI18n,this.eventMaterializers=new Map([[j.NodeNew,this.materializeNodeNewEvent.bind(this)],[j.Composite,this.materializeCompositeEvent.bind(this)],[j.ScenePresent,this.materializeScenePresentEvent.bind(this)],[j.NodePropertyChange,this.materializeNodePropertyChangeEvent.bind(this)],[j.NodeAddChild,this.materializeNodeAddChildEvent.bind(this)],[j.NodeRemoveChild,this.materializeNodeRemoveChildEvent.bind(this)],[j.DomPointerDown,this.materializeDomPointerDownEvent.bind(this)],[j.BrowserImageDataReady,this.materializeBrowserImageDataReadyEvent.bind(this)],[j.I18nDataReadyEvent,this.materializeI18nDataReadyEvent.bind(this)]])}materialize(t){t.length>0&&(console.log(`Replaying ${t.length} events`),t.forEach(i=>{const n=this.eventMaterializers.get(i.type);n?n(i):console.log(`EventMaterializer unhandled event: ${i.type}`)}))}materializeCompositeEvent(t){const i=this.game.materializedNodes.find(n=>n.uuid===t.target);if(!i)console.log(`EventMaterializer: composite node of type ${t.compositeType} with uuid ${t.target} not found when handling CompositeEvent ${t.compositeEventType}`);else if(i.type===lt.Composite)i.handleCompositeEvent(t);else throw new Error(`EventMaterializer: node was expected to be composite, but was of type ${i.type}`)}materializeNodeNewEvent(t){const i=this.nodeFactory.createNode(t.nodeType,t.compositeType,t.nodeOptions);i.type===lt.Scene&&(i.name===X.FREE_NODES_SCENE_NAME?(this.freeNodesScene=i,this.freeNodesScene.game=this.game,this.freeNodesScene.needsInitialization=!0,this.game.freeNodesScene=this.freeNodesScene):this.game.addScene(i)),this.game.materializedNodes.push(i)}materializeNodePropertyChangeEvent(t){const i=this.game.materializedNodes.find(n=>n.uuid===t.uuid);if(!i)throw new Error(`EventMaterializer: node with uuid ${t.uuid} not found`);if(t.property in i)i[t.property]=t.value;else throw new Error(`EventMaterializer: on node ${i.name}, type ${i.type}, nodePropertyChangeEvent tried to set unknown property ${t.property} to value ${JSON.stringify(t.value)}`)}materializeNodeAddChildEvent(t){const i=this.game.materializedNodes.find(c=>c.uuid===t.uuid);if(!i)throw new Error(`EventMaterializer: parent node with uuid ${t.uuid} not found`);const n=this.game.materializedNodes.find(c=>c.uuid===t.childUuid);if(!n)throw new Error(`EventMaterializer: child node with uuid ${t.childUuid} not found`);i.addChild(n)}materializeNodeRemoveChildEvent(t){const i=this.game.materializedNodes.find(c=>c.uuid===t.uuid);if(!i)throw new Error(`EventMaterializer: parent node with uuid ${t.uuid} not found`);const n=this.game.materializedNodes.find(c=>c.uuid===t.childUuid);if(!n)throw new Error(`EventMaterializer: child node with uuid ${t.childUuid} not found`);i.removeChild(n)}materializeDomPointerDownEvent(t){this.game.currentScene?.run(q.custom({callback:()=>{const i=new li({circleOfRadius:16,fillColor:x.LightGray,strokeColor:x.Black,lineWidth:2,alpha:.75,position:{x:t.x,y:t.y}});this.game.currentScene?.addChild(i),i.run(q.sequence([q.group([q.fadeAlpha({duration:750,alpha:0}),q.scale({duration:750,scale:0})]),q.custom({callback:()=>{this.game.currentScene?.removeChild(i)}})]))}}))}materializeBrowserImageDataReadyEvent(t){this.game.imageManager.loadImages([{imageName:t.imageName,width:t.width,height:t.height,dataUrl:t.dataUrl,svgString:t.svgString}])}materializeI18nDataReadyEvent(t){this.configureI18n(t.localizationOptions)}materializeScenePresentEvent(t){let i=We.none();if(t.transitionType===ge.Slide){if(t.direction===void 0)throw new Error("EventMaterializer: ScenePresentEvent direction is undefined for slide transition");if(t.duration===void 0)throw new Error("EventMaterializer: ScenePresentEvent duration is undefined for slide transition");if(t.easingType===void 0)throw new Error("EventMaterializer: ScenePresentEvent easingType is undefined for slide transition");const n=this.game.materializedNodes.find(c=>c.uuid===t.uuid);if(!n)throw new Error(`EventMaterializer: Scene with uuid ${t.uuid} not found`);switch(t.direction){case ye.Left:{n.position.x=n.size.width;break}case ye.Right:{n.position.x=-n.size.width;break}case ye.Up:{n.position.y=n.size.height;break}case ye.Down:{n.position.y=-n.size.height;break}}i=We.slide({direction:t.direction,duration:t.duration,easing:Re.fromTypeAsString(t.easingType)})}this.game.presentScene(t.uuid,i)}}class da{constructor(t){if(this.type=oi.Game,this.sessionUuid="",this.uuid=Ue.generate(),this.publishUuid="",this.canvasKitWasmVersion="0.39.1",this.beginTimestamp=NaN,this.beginIso8601Timestamp="",this.eventListeners=new Array,this.gameMetrics=new Array,this.stepCount=0,this.steppingNow=0,this.warmupFunctionQueue=new Array,this.warmupFinished=!1,this.plugins=[],this.staticTrialSchema={},this.eventStore=new En,this.nodeFactory=new _n,this.materializedNodes=new Array,this.data={trials:new Array},this.trialIndex=0,this.drawnFrames=0,this.lastFpsUpdate=0,this.nextFpsUpdate=0,this.fpsRate=0,this.animationFramesRequested=0,this.limitFps=!1,this.gameStopRequested=!1,this.webGlRendererInfo="",this.canvasCssWidth=0,this.canvasCssHeight=0,this.scenes=new Array,this.freeNodesScene=new Ge({name:X.FREE_NODES_SCENE_NAME,backgroundColor:[255,255,255,0]}),this.incomingSceneTransitions=new Array,this.replayEventsButtonEnabled=!0,this.automaticTrialSchema={study_id:{type:["string","null"],description:"The short human-readable text ID of the study (protocol, experiment, or other aggregate) that contains the administration of this activity."},study_uuid:{type:["string","null"],format:"uuid",description:"Unique identifier of the study (protocol, experiment, or other aggregate) that contains the administration of this activity."},document_uuid:{type:"string",format:"uuid",description:"Unique identifier for this data document."},session_uuid:{type:"string",format:"uuid",description:"Unique identifier for all activities in this administration of the session. This identifier changes each time a new session starts."},activity_uuid:{type:"string",format:"uuid",description:"Unique identifier for all trials in this administration of the activity. This identifier changes each time the activity starts."},activity_id:{type:"string",description:"Human-readable identifier of the activity."},activity_publish_uuid:{type:"string",format:"uuid",description:"Persistent unique identifier of the activity. This identifier never changes. It can be used to identify the activity across different studies and sessions."},activity_version:{type:"string",description:"Version of the activity."},device_timezone:{type:"string",description:"Timezone of the device. Calculated from Intl.DateTimeFormat().resolvedOptions().timeZone."},device_timezone_offset_minutes:{type:"integer",description:"Difference in minutes between UTC and device timezone. Calculated from Date.getTimezoneOffset()."},locale:{type:["string","null"],description:"Locale of the trial. null if the activity does not support localization."}},this.snapshots=new Array,!t.id||t.id.trim()==="")throw new Error("id is required in GameOptions");if(!Ue.isValid(t.publishUuid)){const i=t.publishUuid?`Provided publishUuid was ${t.publishUuid}. `:"";console.warn(`Missing or invalid publishUuid in GameOptions. ${i}To generate a valid UUID, visit a site such as https://www.uuidgenerator.net/version4`)}this.options=t,this.name=t.name,this.id=t.id,this.publishUuid=t.publishUuid,this.fpsMetricReportThreshold=t.fpsMetricReportThreshold??X.FPS_METRIC_REPORT_THRESHOLD,this.maximumRecordedActivityMetrics=t.maximumRecordedActivityMetrics??X.MAXIMUM_RECORDED_ACTIVITY_METRICS,this.addLocalizationParametersToGameParameters(),this.options.locale!==void 0&&this.setParameters({locale:this.options.locale}),this.options.fallbackLocale!==void 0&&this.setParameters({fallback_locale:this.options.fallbackLocale}),this.options.missingLocalizationColor&&this.setParameters({missing_localization_color:this.options.missingLocalizationColor}),this.options.translation&&this.setParameters({translation:this.options.translation}),this.options.additionalTranslation&&this.setParameters({translation:this.options.additionalTranslation}),this.options.trialSchema||(this.options.trialSchema={}),t.moduleMetadata?this.moduleMetadata=t.moduleMetadata:this.moduleMetadata={name:"",version:"",dependencies:{}},t.moduleMetadata?.name&&t.version&&console.log(`\u26AA ${t.moduleMetadata.name} version ${t.version}`)}createFreeNodesScene(){this.freeNodesScene.game=this,this.freeNodesScene.needsInitialization=!0;const t={name:X.FREE_NODES_SCENE_NAME,backgroundColor:[255,255,255,0],uuid:this.freeNodesScene.uuid},i={type:j.NodeNew,target:this.freeNodesScene,nodeType:lt.Scene,...Y.createFrameUpdateTimestamps(),nodeOptions:t,sequence:m2c2Globals.eventSequence};this.eventStore.addEvent(i)}getImportedModuleBaseUrl(t,i){const n=new RegExp(`^.*${t}[^\\/]*`),c=i.match(n);if(!c||c.length===0)throw new Error(`Could not calculate imported assessment package base URL. Package name: ${t}, module URL: ${i}`);return c[0]}addLocalizationParametersToGameParameters(){this.options.parameters={...this.options.parameters,...Ni.makeLocalizationParameters()}}async init(){return this.initialize()}loadCanvasKit(t){return ca({locateFile:()=>t})}async resolveGameBaseUrls(t){let i,n=!1,c=`assets/${t.id}`;if(t.moduleMetadata.name)try{i=await import.meta.resolve(t.moduleMetadata.name),c=t.getImportedModuleBaseUrl(t.moduleMetadata.name,i)+"/assets",n=!0}catch{}let h=`assets/${t.id}`;try{const C=await import.meta.resolve("@m2c2kit/core");h=t.getImportedModuleBaseUrl("@m2c2kit/core",C)+"/assets"}catch{if(n)throw new Error(`the package ${t.moduleMetadata.name} has been imported from a module URL (${i}), but the @m2c2kit/core package module URL could not be determined.`)}return{assets:c,canvasKitWasm:h}}async configureI18n(t){if(this.i18n=new Ni(this,t),!this.i18n)throw new Error("I18n object is undefined");await this.i18n.initialize(),this.eventStore.addEvent({type:"I18nDataReadyEvent",target:this.i18n,localizationOptions:t,...Y.createFrameUpdateTimestamps()})}async waitForErudaInitialization(t=5e3){await new Promise(i=>{let n=0;const c=setInterval(()=>{m2c2Globals.erudaInitialized===!0&&(clearInterval(c),i(void 0)),n=n+100,n>t&&(console.warn(`Could not initialize eruda within ${t} milliseconds.`),clearInterval(c),i(void 0))},100)})}async initialize(){m2c2Globals.erudaRequested===!0&&await this.waitForErudaInitialization(),this.options.recordEvents===!0&&(this.eventStore.mode=de.Record),this.createFreeNodesScene();const t=await this.resolveGameBaseUrls(this);if(this.manifest===void 0&&(this.manifest=await this.loadManifest()),this._canvasKit===void 0){const i=Y.getUrlFromManifest(this,t.canvasKitWasm+`/canvaskit-${this.canvasKitWasmVersion}.wasm`);try{this.canvasKit=await this.loadCanvasKit(i)}catch{throw new Error(`game ${this.id} could not load canvaskit wasm file from ${i}`)}}if(this.isLocalizationRequested()){const i=this.getLocalizationOptionsFromGameParameters();await this.configureI18n(i)}return this.fontManager=new Tn(this,t),this.imageManager=new lr(this,t),this.soundManager=new Wn(this,t),this.eventMaterializer=new ua({game:this,nodeFactory:this.nodeFactory,freeNodesScene:this.freeNodesScene,configureI18n:this.configureI18n.bind(this)}),Promise.all([this.fontManager.initializeFonts(this.options.fonts),this.imageManager.initializeImages(this.options.images),this.soundManager.initializeSounds(this.options.sounds)])}async loadManifest(t="__NO_M2C2KIT_MANIFEST_JSON_URL__"){if(t.includes("NO_M2C2KIT_MANIFEST_JSON_URL"))return{};let i;try{if(i=await fetch(t),!i.ok)throw new Error(`Error ${i.status} on GET manifest.json from ${t}.`)}catch{throw new Error(`Network error on GET manifest.json from ${t}.`)}try{return await i.json()}catch{throw new Error(`Error parsing manifest.json from ${t}.`)}}get fontManager(){if(!this._fontManager)throw new Error("fontManager is undefined");return this._fontManager}set fontManager(t){this._fontManager=t}get imageManager(){if(!this._imageManager)throw new Error("imageManager is undefined");return this._imageManager}set imageManager(t){this._imageManager=t}get soundManager(){if(!this._soundManager)throw new Error("soundManager is undefined");return this._soundManager}set soundManager(t){this._soundManager=t}get eventMaterializer(){if(!this._eventMaterializer)throw new Error("eventMaterializer is undefined");return this._eventMaterializer}set eventMaterializer(t){this._eventMaterializer=t}addPrefixesToKey(t){let i="";if(this.studyId&&this.studyUuid)i=this.studyId.concat(":",this.studyUuid,":");else if(this.studyId||this.studyUuid)throw new Error(`study_id and study_uuid must both be set or unset. Values are study_id: ${this.studyId}, study_uuid: ${this.studyUuid}`);return i.concat(this.id.concat(this.id,":",this.publishUuid,":",t))}storeSetItem(t,i,n=!1){const c=n?t:this.addPrefixesToKey(t);return this.dataStores[0].setItem(c,i,n?"":this.publishUuid)}storeGetItem(t,i=!1){const n=i?t:this.addPrefixesToKey(t);return this.dataStores[0].getItem(n)}storeDeleteItem(t,i=!1){const n=i?t:this.addPrefixesToKey(t);return this.dataStores[0].deleteItem(n)}storeClearItems(){return this.dataStores[0].clearItemsByActivityPublishUuid(this.publishUuid)}storeItemsKeys(t=!1){return this.dataStores[0].itemsKeysByActivityPublishUuid(t?"":this.publishUuid)}storeItemExists(t,i=!1){const n=i?t:this.addPrefixesToKey(t);return this.dataStores[0].itemExists(n)}get dataStores(){if(!this._dataStores)throw new Error("dataStores is undefined");return this._dataStores}set dataStores(t){this._dataStores=t}hasDataStores(){return this._dataStores&&this._dataStores.length>0||!1}getLocalizationOptionsFromGameParameters(){const t=this.getParameter("locale"),i=this.getParameterOrFallback("fallback_locale",void 0),n=this.getParameterOrFallback("missing_localization_color",void 0),c=this.getParameterOrFallback("translation",void 0),h=this.options.translation;return{locale:t,fallbackLocale:i,missingLocalizationColor:n,additionalTranslation:c,translation:h}}isLocalizationRequested(){const t=this.getParameterOrFallback("locale",void 0);if(t==="")throw new Error("Empty string in locale. Leave locale undefined or null to prevent localization.");return t==null&&this.options.translation?(this.setParameters({locale:this.options.translation.baseLocale}),!0):!(t==null&&this.options.translation===void 0)}setParameters(t){const{parameters:i}=this.options;Object.keys(t).forEach(n=>{if(n==="eruda"){t[n]===!0&&Y.loadEruda();return}if(n==="scripts"){const c=t[n];c&&Y.loadScriptUrls(c);return}if(!i||!(n in i))console.warn(`game ${this.options.name} does not have a parameter named ${n}. attempt to set parameter ${n} to value ${t[n]} will be ignored`);else if(this.options.parameters&&this.options.parameters[n]){const c=t[n];let h;if(this.options.parameters[n].type!==void 0&&c!==void 0)try{h=Y.convertValueToType(c,this.options.parameters[n].type)}catch(C){throw new Error("Error setting parameter "+n+": "+C.message)}else h=c;this.options.parameters[n].default=h}this.additionalParameters===void 0&&(this.additionalParameters={}),this.additionalParameters[n]=t[n]})}get canvasKit(){if(!this._canvasKit)throw new Error("canvaskit is undefined");return this._canvasKit}set canvasKit(t){this._canvasKit=t}addFreeNode(t){this.freeNodesScene.addChild(t)}addFreeEntity(t){this.addFreeNode(t)}removeFreeNode(t){if(typeof t=="string"){const i=this.freeNodesScene.children.filter(n=>n.name===t).find(Boolean);if(!i)throw new Error(`cannot remove free node named "${t}" because it is not currently part of the game's free nodes. `);this.freeNodesScene.removeChild(i)}else this.freeNodesScene.removeChild(t)}removeFreeEntity(t){this.removeFreeNode(t)}removeAllFreeNodes(){for(;this.freeNodesScene.children.length;)this.freeNodesScene.children.pop()}removeAllFreeEntities(){this.removeAllFreeNodes()}get freeNodes(){return this.freeNodesScene.children}get freeEntities(){return this.freeNodes}addScene(t){t.game=this,t.needsInitialization=!0,this.scenes.push(t),this.addNodeEvents(t)}addNodeEvents(t){this.eventStore.addEvents(t.nodeEvents),t.nodeEvents.length=0;for(const i of t.children)this.addNodeEvents(i)}addScenes(t){t.forEach(i=>{this.addScene(i)})}removeScene(t){if(typeof t=="object")if(this.scenes.includes(t))this.scenes=this.scenes.filter(i=>i!==t);else throw new Error(`cannot remove scene ${t} from game because the scene is not currently added to the game`);else if(this.scenes.map(i=>i.name).includes(t))this.scenes=this.scenes.filter(i=>i.name!==t);else throw new Error(`cannot remove scene named "${t}" from game because the scene is not currently added to the game`)}presentScene(t,i){let n;if(typeof t=="string"){if(n=this.scenes.filter(T=>T.name===t).find(Boolean),n===void 0&&(n=this.scenes.filter(T=>T.uuid===t).find(Boolean)),n===void 0)throw new Error(`scene ${t} not found`)}else{if(!this.scenes.some(T=>T===t))throw new Error(`scene ${t} exists, but it has not been added to the game object`);n=t}n.initialize(),n.needsInitialization=!1;const c=new Un(n,i??We.none());this.incomingSceneTransitions.push(c),n.game.bodyBackgroundColor!==void 0?document.body.style.backgroundColor=`rgb(${n.game.bodyBackgroundColor[0]},${n.game.bodyBackgroundColor[1]},${n.game.bodyBackgroundColor[2]},${n.game.bodyBackgroundColor[3]})`:document.body.style.backgroundColor=`rgb(${n.backgroundColor[0]},${n.backgroundColor[1]},${n.backgroundColor[2]},${n.backgroundColor[3]})`;let h;i?.type===ge.Slide&&(h=i.direction);const C={type:"ScenePresent",target:n,uuid:n.uuid,...Y.createFrameUpdateTimestamps(),transitionType:i?.type??ge.None,duration:i?.duration,direction:h,easingType:i?.easing?Re.toTypeAsString(i.easing):void 0};this.eventStore.addEvent(C)}getParameter(t){if(this.options.parameters!==void 0&&Object.keys(this.options.parameters).includes(t))return this.options.parameters[t].default;throw new Error(`game parameter ${t} not found`)}getParameterOrFallback(t,i){return this.options.parameters!==void 0&&Object.keys(this.options.parameters).includes(t)?this.options.parameters[t].default:i}hasParameter(t){return!!(this.options.parameters!==void 0&&Object.keys(this.options.parameters).includes(t))}async start(t){const i=this.options;this.setupHtmlCanvases(i.canvasId,i.width,i.height,i.stretch),this.showFps=i.showFps??!1,this.bodyBackgroundColor=i.bodyBackgroundColor,this.initData(),this.setupCanvasKitSurface(),this.setupFpsFont(),this.setupCanvasDomEventHandlers(),this.beginTimestamp=Gt.now(),this.beginIso8601Timestamp=new Date().toISOString();let n;if(t!==void 0?typeof t=="object"?n=t:n=this.scenes.filter(C=>C.name===t).find(Boolean):this.entryScene!==void 0?typeof this.entryScene=="object"?n=this.entryScene:n=this.scenes.filter(C=>C.name===this.entryScene).find(Boolean):n=this.scenes.find(Boolean),n===void 0)throw new Error("cannot start game. entry scene has not been added to the game object.");if(this.presentScene(n),this.surface===void 0)throw new Error("CanvasKit surface is undefined");this.options.timeStepping?(this.addTimeSteppingControlsToDom(),this.updateTimeSteppingOutput()):this.removeTimeSteppingControlsFromDom(),this.options.showEventStoreControls&&this.addEventControlsToDom(),this.warmupFinished=!1;const c={target:this,type:j.GameWarmupStart,...Y.createFrameUpdateTimestamps()};this.raiseActivityEventOnListeners(c),this.warmupFunctionQueue.push({warmupFunction:this.warmupShadersWithPrimitives}),this.warmupFunctionQueue.push({warmupFunction:this.warmupShadersWithPrimitives,positionOffset:.10012117}),this.warmupFunctionQueue.push({warmupFunction:this.warmupShadersWithScenes}),this.surface.requestAnimationFrame(this.loop.bind(this));const h={target:this,type:j.ActivityStart,...Y.createFrameUpdateTimestamps()};this.raiseActivityEventOnListeners(h)}playEventsHandler(t){if(t?.target?.id==="replay-events"&&(this.eventStore.mode=de.Disabled,this.scenes.forEach(i=>{this.removeScene(i)}),this.currentScene=void 0,this.eventListeners=new Array,this.freeNodesScene.removeAllChildren(),this.materializedNodes=[],this.eventStore.replay(),this.setReplayEventsButtonEnabled(!1),this.setStopReplayButtonEnabled(!0)),t?.target?.id==="stop-replay"&&(this.eventStore.clearEvents(),this.setReplayEventsButtonEnabled(!0),this.setStopReplayButtonEnabled(!1)),t?.target?.id==="log-events"){if(this.eventStore.mode===de.Replay){console.log(this.eventStore.serializedEventsBeforeReplay),console.log(`Total events: ${JSON.parse(this.eventStore.serializedEventsBeforeReplay).length}`);return}console.log(JSON.stringify(this.eventStore.getEvents())),console.log(`Total events: ${this.eventStore.getEvents().length}`)}}setReplayEventsButtonEnabled(t){const i=document.getElementById("replay-events");if(i){if(t){i.removeAttribute("disabled"),this.replayEventsButtonEnabled=!0;return}i.setAttribute("disabled","true"),this.replayEventsButtonEnabled=!1}}setStopReplayButtonEnabled(t){const i=document.getElementById("stop-replay");if(i){if(t){i.removeAttribute("disabled");return}i.setAttribute("disabled","true")}}addEventControlsToDom(){const t=document.getElementById("m2c2kit-event-controls-div");t&&t.remove();const i=document.getElementsByTagName("body")[0];if(i){const n=document.createElement("div");n.id="m2c2kit-event-controls-div",n.style.position="fixed",n.style.top="4px",n.style.left="4px",i.prepend(n);const c=document.createElement("button");c.id="replay-events",c.title="replay event recording",c.innerText="\u25B6\uFE0F",c.style.marginRight="4px",n.appendChild(c),c.addEventListener("click",this.playEventsHandler.bind(this));const h=document.createElement("button");h.id="stop-replay",h.title="stop event replay",h.innerText="\u23F9\uFE0F",h.style.marginRight="4px",h.disabled=!0,n.appendChild(h),h.addEventListener("click",this.playEventsHandler.bind(this));const C=document.createElement("button");C.id="log-events",C.title="log events to console",C.innerText="\u{1F4C4}",C.style.marginRight="4px",n.appendChild(C),C.addEventListener("click",this.playEventsHandler.bind(this));const T=document.createElement("span");T.title="optional: replay events only through a given sequence number. Default is to replay all events.",T.innerText="Replay through sequence: ",n.appendChild(T);const B=document.createElement("input");B.id="sequence-number",B.title="optional: replay events only through a given sequence number. Default is to replay all events.",B.style.marginRight="4px",n.appendChild(B)}}addTimeSteppingControlsToDom(){if(document.getElementById("m2c2kit-time-stepping-div"))return;const i=document.getElementsByTagName("body")[0];if(i){const n=document.createElement("div");n.id="m2c2kit-time-stepping-div",i.prepend(n);const c=document.createElement("button");c.id="1-step-advance",c.title="advance 1 step (16.667 ms)",c.innerText=">",c.style.marginRight="4px",n.appendChild(c),c.addEventListener("click",this.advanceStepsHandler.bind(this));const h=document.createElement("button");h.id="55-step-advance",h.title="advance 55 steps (916.667 ms)",h.innerText=">>",h.style.marginRight="4px",n.appendChild(h),h.addEventListener("click",this.advanceStepsHandler.bind(this));const C=document.createElement("input");C.id="time-stepping-steps-input",C.title="steps",C.style.width="40px",C.style.marginRight="4px",C.setAttribute("readonly","true"),n.appendChild(C);const T=document.createElement("input");T.id="time-stepping-now-input",T.title="milliseconds",T.style.width="80px",T.style.marginRight="4px",T.setAttribute("readonly","true"),n.appendChild(T)}}updateTimeSteppingOutput(){const t=document.getElementById("time-stepping-steps-input");t&&(t.value=this.stepCount.toString());const i=document.getElementById("time-stepping-now-input");i&&(i.value=this.steppingNow.toFixed(2))}advanceStepsHandler(t){t?.target?.id==="1-step-advance"?(this.steppingNow=this.steppingNow+16.66666666666667,this.stepCount=this.stepCount+1):t?.target?.id==="55-step-advance"&&(this.steppingNow=this.steppingNow+16.66666666666667*55,this.stepCount=this.stepCount+55),this.updateTimeSteppingOutput()}removeTimeSteppingControlsFromDom(){const t=document.getElementById("m2c2kit-time-stepping-div");t&&t.remove()}warmupShadersWithPrimitives(t,i=0){if(t.save(),i==0?t.scale(1/m2c2Globals.canvasScale,1/m2c2Globals.canvasScale):t.scale(1/m2c2Globals.canvasScale*1.13,1/m2c2Globals.canvasScale*1.13),!this.surface)throw new Error("surface is undefined");const n=this.surface.width(),c=this.surface.height(),h=Math.round(n/2)+i,C=Math.round(c/2)+i,T=i,B=i,$=xt.makePaint(this.canvasKit,x.White,this.canvasKit.PaintStyle.Fill,!0);t.drawRect([0,0,this.surface.width(),this.surface.height()],$);const it=xt.makePaint(this.canvasKit,x.Black,this.canvasKit.PaintStyle.Fill,!1),ct=xt.makePaint(this.canvasKit,x.Black,this.canvasKit.PaintStyle.Fill,!0),ut=xt.makePaint(this.canvasKit,x.Black,this.canvasKit.PaintStyle.Stroke,!1);ut.setStrokeWidth(2);const bt=xt.makePaint(this.canvasKit,x.Black,this.canvasKit.PaintStyle.Stroke,!0);bt.setStrokeWidth(2),t.drawCircle(h,C,32,it),t.drawCircle(h,C,32,ct),t.drawCircle(h,C,32,ut),t.drawCircle(h,C,32,bt);const wt=this.fontManager,Ht=this.fontManager.getFontNames();if(Ht.length>0&&wt.fonts[Ht[0]].status===Zt.Ready){const pe=wt.getTypeface(Ht[0]),ve=new this.canvasKit.Font(pe,16*m2c2Globals.canvasScale);t.drawText("abc",h,C,it,ve),t.drawText("abc",h,C,ct,ve)}const fe=this.takeCurrentSceneSnapshot();t.drawImage(fe,T,B),fe.delete(),t.drawRect([T,B,16,16],it),t.drawRect([T,B,16,16],ct),t.drawRect([T,B,16,16],ut),t.drawRect([T,B,16,16],bt),t.restore()}warmupShadersWithScenes(t){[...this.scenes,this.freeNodesScene].forEach(h=>{h.warmup(t)});const i=this.nodes.filter(h=>h.type===lt.Sprite).map(h=>h.imageName),n=this.imageManager.images;n&&Object.keys(n).filter(C=>C!=="__outgoingSceneSnapshot").forEach(C=>{if(!i.includes(C)&&n[C].status===Qt.Ready){const T=n[C].canvaskitImage;if(!T)throw new Error(`image ${C} is undefined`);t.drawImage(T,0,0)}});const c=new this.canvasKit.Paint;if(c.setColor(this.canvasKit.Color(255,255,255,1)),!this.surface)throw new Error("surface is undefined");t.drawRect([0,0,this.surface.width(),this.surface.height()],c)}stop(){this.currentScene&&(this.currentScene._active=!1),this.gameStopRequested=!0,Gt.removeAll(),this.dispose()}dispose(){this.nodes.filter(t=>t.isDrawable).forEach(t=>t.dispose()),this.fontManager.dispose()}initData(){this.trialIndex=0,this.data={trials:new Array};const t=this.options.trialSchema??{},i=Object.entries(t);for(const[n,c]of i)if(c.type!==void 0&&!this.propertySchemaDataTypeIsValid(c.type))throw new Error(`invalid schema. variable ${n} is type ${c.type}. type must be number, string, boolean, object, or array`)}propertySchemaDataTypeIsValid(t){const i=["string","number","integer","object","array","boolean","null"];if(typeof t=="string")return i.includes(t);let n=!0;if(Array.isArray(t))t.forEach(c=>{i.includes(c)||(n=!1)});else throw new Error(`Invalid data type: ${t}`);return n}getDeviceMetadata(){const t=window.screen;return t.orientation?{userAgent:navigator.userAgent,devicePixelRatio:window.devicePixelRatio,screen:{availHeight:t.availHeight,availWidth:t.availWidth,colorDepth:t.colorDepth,height:t.height,orientation:{type:t.orientation.type,angle:t.orientation.angle},pixelDepth:t.pixelDepth,width:t.width},webGlRenderer:this.webGlRendererInfo}:{userAgent:navigator.userAgent,devicePixelRatio:window.devicePixelRatio,screen:{availHeight:t.availHeight,availWidth:t.availWidth,colorDepth:t.colorDepth,height:t.height,pixelDepth:t.pixelDepth,width:t.width},webGlRenderer:this.webGlRendererInfo}}addTrialData(t,i){if(!this.options.trialSchema)throw new Error("no trial schema were provided in GameOptions. cannot add trial data");if(this.data.trials.length<this.trialIndex+1){const h={},C=Object.entries(this.options.trialSchema);for(const[T]of C)h[T]=null;this.data.trials.push({document_uuid:Ue.generate(),study_id:this.studyId??null,study_uuid:this.studyUuid??null,session_uuid:this.sessionUuid,activity_uuid:this.uuid,activity_id:this.options.id,activity_publish_uuid:this.options.publishUuid,activity_version:this.options.version,device_timezone:Intl?.DateTimeFormat()?.resolvedOptions()?.timeZone??"",device_timezone_offset_minutes:new Date().getTimezoneOffset(),locale:this.i18n?.locale??null,...h,device_metadata:this.getDeviceMetadata()})}if(!(t in this.options.trialSchema))throw new Error(`trial variable ${t} not defined in schema`);let n;Array.isArray(this.options.trialSchema[t].type)?n=this.options.trialSchema[t].type:n=[this.options.trialSchema[t].type];let c=typeof i;if(c==="object"&&Object.prototype.toString.call(i)==="[object Array]"&&(c="array"),i==null&&(c="null"),!n.includes(c)&&!(c==="number"&&Number.isInteger(i)&&n.includes("integer")))throw new Error(`type for variable ${t} (value: ${i}) is "${c}". Based on schema for this variable, expected type was "${n}"`);this.data.trials[this.trialIndex][t]=i}addTrialSchema(t){Object.keys(t).forEach(n=>{if(!this.options.trialSchema)throw new Error("trial schema is undefined");this.options.trialSchema[n]=t[n]})}addStaticTrialData(t,i){if(!this.options.trialSchema)throw new Error("trial schema is undefined");if(this.options.trialSchema[t]===void 0)throw new Error(`trial variable ${t} not defined in schema`);this.staticTrialSchema[t]=i}trialComplete(){this.data.trials[this.trialIndex]?.locale&&(this.data.trials[this.trialIndex].locale=this.i18n?.locale??null),this.data.trials[this.trialIndex]?.device_metadata&&(this.data.trials[this.trialIndex].device_metadata=this.getDeviceMetadata()),Object.keys(this.staticTrialSchema).length>0&&(this.data.trials[this.trialIndex]={...this.data.trials[this.trialIndex],...this.staticTrialSchema}),this.trialIndex++;const t={type:j.ActivityData,...Y.createFrameUpdateTimestamps(),target:this,newData:this.data.trials[this.trialIndex-1],newDataSchema:this.makeNewGameDataSchema(),data:this.data,dataSchema:this.makeGameDataSchema(),dataType:"Trial",activityConfiguration:this.makeGameActivityConfiguration(this.options.parameters??{}),activityConfigurationSchema:this.makeGameActivityConfigurationSchema(this.options.parameters??{}),activityMetrics:this.gameMetrics};this.raiseActivityEventOnListeners(t)}makeNewGameDataSchema(){return{description:`A single trial and metadata from the assessment ${this.name}.`,$comment:`Activity identifier: ${this.options.id}, version: ${this.options.version}.`,$schema:"https://json-schema.org/draft/2019-09/schema",type:"object",properties:{...this.automaticTrialSchema,...this.options.trialSchema,device_metadata:$n}}}makeGameDataSchema(){return{description:`All trials and metadata from the assessment ${this.name}.`,$comment:`Activity identifier: ${this.options.id}, version: ${this.options.version}.`,$schema:"https://json-schema.org/draft/2019-09/schema",type:"object",required:["trials"],properties:{trials:{type:"array",items:{$ref:"#/$defs/trial"},description:"All trials from the assessment."}},$defs:{trial:{type:"object",properties:{...this.automaticTrialSchema,...this.options.trialSchema,device_metadata:$n}}}}}makeGameActivityConfiguration(t){const i=JSON.parse(JSON.stringify(t)),{locale:n,fallback_locale:c,missing_localization_color:h,translation:C,...T}=i;for(const B in T)for(const $ in T[B])$=="default"&&(T[B]=T[B][$]);return T}makeGameActivityConfigurationSchema(t){const i=JSON.parse(JSON.stringify(t)),{locale:n,fallback_locale:c,missing_localization_color:h,translation:C,...T}=i;for(const B in T){if(!("type"in T[B])&&"value"in T[B]){const $=typeof T[B].default;$!=="bigint"&&$!=="function"&&$!=="symbol"&&$!=="undefined"&&(T[B].type=$)}for(const $ in T[B])$=="default"&&delete T[B][$]}return{description:`activity configuration from the assessment ${this.name}`,type:"object",properties:T}}end(){const t={target:this,type:j.ActivityEnd,...Y.createFrameUpdateTimestamps()},i={data:this.data,dataSchema:this.makeGameDataSchema(),dataType:"Trial",activityConfiguration:this.makeGameActivityConfiguration(this.options.parameters??{}),activityConfigurationSchema:this.makeGameActivityConfigurationSchema(this.options.parameters??{}),activityMetrics:this.gameMetrics};this.raiseActivityEventOnListeners(t,i)}cancel(){const t={target:this,type:j.ActivityCancel,...Y.createFrameUpdateTimestamps()},i={data:this.data,dataSchema:this.makeGameDataSchema(),dataType:"Trial",activityConfiguration:this.makeGameActivityConfiguration(this.options.parameters??{}),activityConfigurationSchema:this.makeGameActivityConfigurationSchema(this.options.parameters??{}),activityMetrics:this.gameMetrics};this.raiseActivityEventOnListeners(t,i)}setupHtmlCanvases(t,i,n,c){m2c2Globals.canvasScale=Math.round(window.devicePixelRatio*100)/100;let h;if(t===void 0){const C=document.getElementsByTagName("canvas");let T=new Array;for(let $=0;$<C.length;$++)T.push(C[$]);if(T=T.filter($=>!$.id.startsWith("m2c2kit-scratch-canvas")),T.length===0)throw new Error("no html canvas tag was found in the html");const B=T.filter($=>$.id==="m2c2kit-canvas")[0];B?(h=B,T.length>1&&console.log("using canvas with id 'm2c2kit-canvas'")):(h=C[0],T.length>1&&console.log("using first canvas"))}else if(h=document.getElementById(t),h===void 0)throw new Error(`could not find canvas HTML element with id "${t}"`);if(c||window.innerWidth<i||window.innerHeight<n){const C=n/i;window.innerHeight/window.innerWidth<C?m2c2Globals.rootScale=window.innerHeight/n:m2c2Globals.rootScale=window.innerWidth/i}h.style.width=m2c2Globals.rootScale*i+"px",h.style.height=m2c2Globals.rootScale*n+"px",h.width=m2c2Globals.rootScale*i*m2c2Globals.canvasScale,h.height=m2c2Globals.rootScale*n*m2c2Globals.canvasScale,this.htmlCanvas=h,this.canvasCssWidth=i,this.canvasCssHeight=n,m2c2Globals.canvasCssWidth=i,m2c2Globals.canvasCssHeight=n}setupCanvasKitSurface(){if(this.htmlCanvas===void 0)throw new Error("main html canvas is undefined");window.logWebGl=this.options.logWebGl,this.interceptWebGlCalls();try{this.webGlRendererInfo=mr.getRendererString()}catch{this.webGlRendererInfo="err",mr.dispose()}const t=this.canvasKit.MakeWebGLCanvasSurface(this.htmlCanvas);if(t===null)throw new Error("could not make CanvasKit surface from canvas HTML element");this.surface=t,console.log(`\u26AA CanvasKit surface is backed by ${this.surface.reportBackendTypeIsGPU()?"GPU":"CPU"}`),this.surface.getCanvas().scale(m2c2Globals.canvasScale,m2c2Globals.canvasScale)}interceptWebGlCalls(){if(!this.htmlCanvas.__proto__.m2c2ModifiedGetContext){this.htmlCanvas.__proto__.m2c2ModifiedGetContext=!0;const t=this.htmlCanvas.__proto__.getContext;this.htmlCanvas.__proto__.getContext=function(...i){window.logWebGl&&console.log(`\u{1F53C} getContext(${i.map(c=>c.toString()).join(", ")})`);const n=t.apply(this,[...i]);if(n.__proto__.compileShader&&!n.__proto__.m2c2ModifiedCompileShader){n.__proto__.m2c2ModifiedCompileShader=!0;const c=n.__proto__.compileShader;n.__proto__.compileShader=function(...h){if(window.logWebGl){const C=h[0],T=n.getShaderSource(C);console.log("\u{1F53C} compileShader():"),console.log(T)}return c.apply(this,[...h])}}return n}}}setupFpsFont(){this.fpsTextFont=new this.canvasKit.Font(null,X.FPS_DISPLAY_TEXT_FONT_SIZE*m2c2Globals.canvasScale),this.fpsTextPaint=new this.canvasKit.Paint,this.fpsTextPaint.setColor(this.canvasKit.Color(X.FPS_DISPLAY_TEXT_COLOR[0],X.FPS_DISPLAY_TEXT_COLOR[1],X.FPS_DISPLAY_TEXT_COLOR[2],X.FPS_DISPLAY_TEXT_COLOR[3])),this.fpsTextPaint.setAntiAlias(!0)}setupCanvasDomEventHandlers(){if(this.htmlCanvas===void 0)throw new Error("main html canvas is undefined");this.htmlCanvas.addEventListener("pointerdown",this.htmlCanvasPointerDownHandler.bind(this)),this.htmlCanvas.addEventListener("pointerup",this.htmlCanvasPointerUpHandler.bind(this)),this.htmlCanvas.addEventListener("pointermove",this.htmlCanvasPointerMoveHandler.bind(this)),this.htmlCanvas.addEventListener("touchstart",t=>{t.preventDefault()}),this.htmlCanvas.addEventListener("pointerleave",this.htmlCanvasPointerLeaveHandler.bind(this))}loop(t){if(!this.surface)throw new Error("surface is undefined");if(this.warmupFunctionQueue.length>0){const i=this.warmupFunctionQueue.shift();i?.warmupFunction.call(this,t,i.positionOffset),this.surface.requestAnimationFrame(this.loop.bind(this));return}if(!this.warmupFinished){this.warmupFinished=!0;const i={target:this,type:j.GameWarmupEnd,...Y.createFrameUpdateTimestamps()};this.raiseActivityEventOnListeners(i),this.surface.requestAnimationFrame(this.loop.bind(this));return}if(this.soundManager.hasSoundsToDecode()&&navigator.userActivation.hasBeenActive&&this.soundManager.decodeFetchedSounds(),this.gameStopRequested){this.surface.deleteLater();return}if(this.animationFramesRequested++,!this.limitFps||this.animationFramesRequested%Math.round(60/X.LIMITED_FPS_RATE)===0){if(this.currentScene===void 0&&this.incomingSceneTransitions.length===0&&this.eventStore.mode!==de.Replay)throw new Error("Can not run game without a current or incoming scene");if(this.updateGameTime(),this.eventStore.mode===de.Replay){const i=this.eventStore.dequeueEvents(Gt.now());this.eventMaterializer.materialize(i),this.eventStore.eventQueueLength===0&&!this.replayEventsButtonEnabled&&(this.setReplayEventsButtonEnabled(!0),this.setStopReplayButtonEnabled(!1))}for(this.handleIncomingSceneTransitions(this.incomingSceneTransitions),this.update(),this.draw(t);this.snapshots.length>0;)this.snapshots.shift()?.delete();this.snapshots.push(this.takeCurrentSceneSnapshot()),this.freeNodesScene.draw(t),this.pendingScreenshot&&(this.handlePendingScreenshot(this.pendingScreenshot),this.pendingScreenshot=void 0)}this.priorUpdateTime=m2c2Globals.now,this.surface.requestAnimationFrame(this.loop.bind(this))}updateGameTime(){this.options.timeStepping?m2c2Globals.now=this.steppingNow:m2c2Globals.now=performance.now(),this.priorUpdateTime?m2c2Globals.deltaTime=m2c2Globals.now-this.priorUpdateTime:m2c2Globals.deltaTime=0}handleIncomingSceneTransitions(t){if(t.length!==0&&(this.snapshots.length>0||t[0].transition.type===ge.None)){const i=t.shift();if(i===void 0)throw new Error("no incoming scene transition");const n=i.scene,c=i.transition;if(c.type===ge.None){this.currentScene&&(this.currentScene._active=!1),this.currentScene=n,this.currentScene._active=!0,this.raiseSceneEvent(n,"SceneSetup"),this.raiseSceneEvent(n,"SceneAppear");return}if(this.currentSceneSnapshot=this.snapshots.shift(),!this.currentSceneSnapshot)throw new Error("No snapshot available for outgoing scene");const h=this.createOutgoingScene(this.currentSceneSnapshot);h._active=!0,this.currentScene&&(this.currentScene._active=!1),this.currentScene=n,this.currentScene._active=!0,this.raiseSceneEvent(n,"SceneSetup"),this.animateSceneTransition(n,c,h)}}createOutgoingScene(t){const i=new Ge({name:X.OUTGOING_SCENE_NAME});i.size.width=this.canvasCssWidth,i.size.height=this.canvasCssHeight,this.addScene(i);const n={imageName:X.OUTGOING_SCENE_IMAGE_NAME,canvaskitImage:t,width:this.canvasCssWidth,height:this.canvasCssHeight,status:Qt.Ready,localize:!1,isFallback:!1};this.imageManager.addImage(n);const c=new hi({name:X.OUTGOING_SCENE_SPRITE_NAME,imageName:X.OUTGOING_SCENE_IMAGE_NAME,position:{x:this.canvasCssWidth/m2c2Globals.rootScale/2,y:this.canvasCssHeight/m2c2Globals.rootScale/2}});return c.scale=1/m2c2Globals.rootScale,i.addChild(c),i}async registerPlugin(t){if(t.type!==oi.Game)throw new Error(`registerPlugin(): plugin ${t.id} is not a game plugin. It is a ${t.type} plugin.`);if(this.plugins.includes(t)||this.plugins.map(i=>i.id).includes(t.id))throw new Error(`registerPlugin(): plugin ${t.id} already registered.`);this.plugins.push(t),t.initialize&&await t.initialize(this)}update(){this.executeBeforeUpdatePlugins(),this.updateScenes(),this.executeAfterUpdatePlugins()}updateScenes(){this.scenes.filter(t=>t._active).forEach(t=>t.update()),this.freeNodesScene.update()}executeBeforeUpdatePlugins(){this.plugins.filter(t=>typeof t.beforeUpdate=="function"&&t.disabled!==!0).forEach(t=>{t.beforeUpdate&&t.beforeUpdate(this,m2c2Globals.deltaTime)})}executeAfterUpdatePlugins(){this.plugins.filter(t=>typeof t.afterUpdate=="function"&&t.disabled!==!0).forEach(t=>{t.afterUpdate&&t.afterUpdate(this,m2c2Globals.deltaTime)})}draw(t){this.scenes.filter(i=>i._active).forEach(i=>i.draw(t)),this.drawnFrames++,this.calculateFps(),this.showFps&&this.drawFps(t)}calculateFps(){this.lastFpsUpdate===0?(this.lastFpsUpdate=m2c2Globals.now,this.nextFpsUpdate=m2c2Globals.now+X.FPS_DISPLAY_UPDATE_INTERVAL):m2c2Globals.now>=this.nextFpsUpdate&&(this.fpsRate=this.drawnFrames/((m2c2Globals.now-this.lastFpsUpdate)/1e3),this.drawnFrames=0,this.lastFpsUpdate=m2c2Globals.now,this.nextFpsUpdate=m2c2Globals.now+X.FPS_DISPLAY_UPDATE_INTERVAL,this.gameMetrics.length<this.maximumRecordedActivityMetrics&&this.fpsRate<this.fpsMetricReportThreshold&&this.gameMetrics.push({fps:Number.parseFloat(this.fpsRate.toFixed(2)),fps_interval_ms:X.FPS_DISPLAY_UPDATE_INTERVAL,fps_report_threshold:this.fpsMetricReportThreshold,activity_type:oi.Game,activity_uuid:this.uuid,iso8601_timestamp:new Date().toISOString()}))}takeCurrentSceneSnapshot(){if(this.surface===void 0)throw new Error("CanvasKit surface is undefined");return this.surface.makeImageSnapshot()}handlePendingScreenshot(t){if(!this.surface)throw new Error("no surface");let i;if(t.rect.length==4){const c=t.rect[0]*m2c2Globals.canvasScale,h=t.rect[1]*m2c2Globals.canvasScale,C=t.rect[2]*m2c2Globals.canvasScale,T=t.rect[3]*m2c2Globals.canvasScale,B=[c,h,c+C,h+T];i=this.surface.makeImageSnapshot(B)}else i=this.surface.makeImageSnapshot();const n=i.encodeToBytes();t.promiseResolve(n)}takeScreenshot(t,i,n,c){if(!this.surface)throw new Error("no canvaskit surface. unable to take screenshot.");const h=[t,i,n,c].map(C=>C?0:1).reduce((C,T)=>C+T);return new Promise((C,T)=>{switch(h){case 0:{if(!t||!i||!n||!c){T("missing values in arguments for takeScreenshot()");return}this.pendingScreenshot={rect:[t,i,n,c],promiseResolve:C};break}case 4:{this.pendingScreenshot={rect:[],promiseResolve:C};break}default:T("Exactly 0 or 4 arguments must be supplied to takeScreenshot()")}})}animateSceneTransition(t,i,n){const c=i.duration;switch(t._transitioning=!0,n._transitioning=!0,i.type){case ge.Slide:{switch(i.direction){case ye.Left:t.position.x=t.size.width,t.run(q.sequence([q.move({point:{x:0,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{t._transitioning=!1,this.raiseSceneEvent(t,"SceneAppear"),this.removeScene(X.OUTGOING_SCENE_NAME)},runDuringTransition:!0})])),n.run(q.sequence([q.move({point:{x:-n.size.width,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{n._active=!1,n._transitioning=!1,this.currentSceneSnapshot&&this.currentSceneSnapshot.delete()},runDuringTransition:!0})]));break;case ye.Right:t.position.x=-t.size.width,t.run(q.sequence([q.move({point:{x:0,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{t._transitioning=!1,this.raiseSceneEvent(t,"SceneAppear"),this.removeScene(X.OUTGOING_SCENE_NAME)},runDuringTransition:!0})])),n.run(q.sequence([q.move({point:{x:n.size.width,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{n._active=!1,n._transitioning=!1,this.currentSceneSnapshot&&this.currentSceneSnapshot.delete()},runDuringTransition:!0})]));break;case ye.Up:t.position.y=t.size.height,t.run(q.sequence([q.move({point:{x:0,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{t._transitioning=!1,this.raiseSceneEvent(t,"SceneAppear"),this.removeScene(X.OUTGOING_SCENE_NAME)},runDuringTransition:!0})])),n.run(q.sequence([q.move({point:{x:0,y:-n.size.height},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{n._active=!1,n._transitioning=!1,this.currentSceneSnapshot&&this.currentSceneSnapshot.delete()},runDuringTransition:!0})]));break;case ye.Down:t.position.y=-t.size.height,t.run(q.sequence([q.move({point:{x:0,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{t._transitioning=!1,this.raiseSceneEvent(t,"SceneAppear"),this.removeScene(X.OUTGOING_SCENE_NAME)},runDuringTransition:!0})])),n.run(q.sequence([q.move({point:{x:0,y:n.size.height},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{n._active=!1,n._transitioning=!1,this.currentSceneSnapshot&&this.currentSceneSnapshot.delete()},runDuringTransition:!0})]));break;default:throw new Error("unknown transition direction")}break}default:throw new Error("unknown transition type")}}drawFps(t){t.save();const i=m2c2Globals.canvasScale;if(t.scale(1/i,1/i),!this.fpsTextFont||!this.fpsTextPaint)throw new Error("fps font or paint is undefined");t.drawText("FPS: "+this.fpsRate.toFixed(2),0,0+X.FPS_DISPLAY_TEXT_FONT_SIZE*i,this.fpsTextPaint,this.fpsTextFont),t.restore()}createEventListener(t,i,n,c){const h=this.nodes.filter(T=>T.name===i);h.length>1&&console.warn(`warning: createEventListener() found more than one node with name ${i}. Event listener will be attached to first node found. All nodes that receive tap events should be uniquely named`);const C=h.filter(T=>T.name===i).find(Boolean);if(C===void 0)throw new Error(`could not create event listener. node with name ${i} could not be found in the game node tree`);if(!Object.values(j).includes(t))throw new Error(`game ${this.id}: could not create event listener. event type ${t} is not known`);C.addEventListener(t,n,c)}get nodes(){function t(n,c){c.push(n),n.children.forEach(h=>t(h,c))}const i=new Array;return[...this.scenes,this.freeNodesScene].forEach(n=>t(n,i)),i}get entities(){return this.nodes}htmlCanvasPointerDownHandler(t){t.preventDefault();const i=this.currentScene;if(!i||!this.sceneCanReceiveUserInteraction(i))return;if(!this.htmlCanvas)throw new Error("main html canvas is undefined");const n={type:"DomPointerDown",target:this.htmlCanvas,x:t.offsetX/m2c2Globals.rootScale,y:t.offsetY/m2c2Globals.rootScale,...Y.createTimestamps()};this.eventStore.addEvent(n);const c={target:i,type:j.PointerDown,handled:!1,...Y.createTimestamps()};this.processDomPointerDown(this.freeNodesScene,c,t),this.processDomPointerDown(i,c,t)}htmlCanvasPointerUpHandler(t){t.preventDefault();const i=this.currentScene;if(!i||!this.sceneCanReceiveUserInteraction(i))return;const n={target:i,type:j.PointerUp,handled:!1,...Y.createTimestamps()};this.processDomPointerUp(this.freeNodesScene,n,t),this.processDomPointerUp(i,n,t)}htmlCanvasPointerMoveHandler(t){t.preventDefault();const i=this.currentScene;if(!i||!this.sceneCanReceiveUserInteraction(i))return;const n={target:i,type:j.PointerMove,handled:!1,...Y.createTimestamps()};this.processDomPointerMove(this.freeNodesScene,n,t),this.processDomPointerMove(i,n,t)}htmlCanvasPointerLeaveHandler(t){if(!this.currentScene)return;t.preventDefault();const i=this.currentScene;if(!i||!this.sceneCanReceiveUserInteraction(i))return;const n={target:i,type:j.PointerLeave,handled:!1,...Y.createTimestamps()};this.processDomPointerLeave(this.freeNodesScene,n,t),this.processDomPointerLeave(i,n,t)}processDomPointerDown(t,i,n){i.handled||(t.isUserInteractionEnabled&&this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.pressed=!0,t.pressedAndWithinHitArea=!0,t.pressedInitialPointerOffset={x:n.offsetX,y:n.offsetY},this.raiseM2PointerDownEvent(t,i,n),this.raiseTapDownEvent(t,i,n)),t.children&&t.children.filter(c=>!c.hidden).filter(c=>c.isDrawable).sort((c,h)=>h.zPosition-c.zPosition).forEach(c=>this.processDomPointerDown(c,i,n)))}processDomPointerUp(t,i,n){if(!i.handled){if(t.dragging){t.dragging=!1,t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseM2DragEndEvent(t,i,n),i.handled=!0;return}t.isUserInteractionEnabled&&t.pressed&&t.pressedAndWithinHitArea?(t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseTapUpEvent(t,i,n),this.raiseTapUpAny(t,i,n),this.raiseM2PointerUpEvent(t,i,n)):t.isUserInteractionEnabled&&t.pressed&&t.pressedAndWithinHitArea==!1?(t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseTapUpAny(t,i,n)):t.isUserInteractionEnabled&&this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseM2PointerUpEvent(t,i,n)),t.children&&t.children.filter(c=>!c.hidden).filter(c=>c.isDrawable).sort((c,h)=>h.zPosition-c.zPosition).forEach(c=>this.processDomPointerUp(c,i,n))}}processDomPointerMove(t,i,n){if(!i.handled){if(t.isUserInteractionEnabled&&t.draggable&&t.pressed){let c=!1,h,C;t.dragging===!1?(t.dragging=!0,c=!0,h=n.offsetX-t.pressedInitialPointerOffset.x,C=n.offsetY-t.pressedInitialPointerOffset.y):(h=n.offsetX-t.draggingLastPointerOffset.x,C=n.offsetY-t.draggingLastPointerOffset.y),t.position.x+=h,t.position.y+=C,t.draggingLastPointerOffset={x:n.offsetX,y:n.offsetY},i.handled=!0,c?this.raiseM2DragStartEvent(t,i,n):this.raiseM2DragEvent(t,i,n);return}t.isUserInteractionEnabled&&t.pressed&&t.pressedAndWithinHitArea&&!this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.pressedAndWithinHitArea=!1,this.raiseTapLeaveEvent(t,i,n)),t.isUserInteractionEnabled&&this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(this.raiseM2PointerMoveEvent(t,i,n),t.withinHitArea=!0),t.isUserInteractionEnabled&&t.withinHitArea&&!this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.withinHitArea=!1,this.raiseM2PointerLeaveEvent(t,i,n)),t.children&&t.children.filter(c=>!c.hidden).filter(c=>c.isDrawable).sort((c,h)=>h.zPosition-c.zPosition).forEach(c=>this.processDomPointerMove(c,i,n))}}processDomPointerLeave(t,i,n){if(!i.handled){if(t.dragging){const c={target:t,type:j.DragEnd,handled:!1,...Y.createTimestamps()};t.dragging=!1,t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseM2DragEndEvent(t,c,n);return}t.isUserInteractionEnabled&&t.pressed&&t.pressedAndWithinHitArea&&!this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.pressedAndWithinHitArea=!1,this.raiseTapLeaveEvent(t,i,n)),t.isUserInteractionEnabled&&t.withinHitArea&&!this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.withinHitArea=!1,this.raiseM2PointerLeaveEvent(t,i,n)),t.children&&t.children.filter(c=>!c.hidden).filter(c=>c.isDrawable).sort((c,h)=>h.zPosition-c.zPosition).forEach(c=>this.processDomPointerLeave(c,i,n))}}raiseM2PointerDownEvent(t,i,n){i.target=t,i.type=j.PointerDown,this.raiseEventOnListeningNodes(t,i,n)}raiseTapDownEvent(t,i,n){i.target=t,i.type=j.TapDown,this.raiseEventOnListeningNodes(t,i,n)}raiseTapLeaveEvent(t,i,n){i.target=t,i.type=j.TapLeave,this.raiseEventOnListeningNodes(t,i,n)}raiseM2PointerUpEvent(t,i,n){i.target=t,i.type=j.PointerUp,this.raiseEventOnListeningNodes(t,i,n)}raiseTapUpEvent(t,i,n){i.target=t,i.type=j.TapUp,this.raiseEventOnListeningNodes(t,i,n)}raiseTapUpAny(t,i,n){i.target=t,i.type=j.TapUpAny,this.raiseEventOnListeningNodes(t,i,n)}raiseM2PointerMoveEvent(t,i,n){i.target=t,i.type=j.PointerMove,this.raiseEventOnListeningNodes(t,i,n)}raiseM2PointerLeaveEvent(t,i,n){i.target=t,i.type=j.PointerLeave,this.raiseEventOnListeningNodes(t,i,n)}raiseM2DragStartEvent(t,i,n){i.target=t,i.type=j.DragStart,this.raiseEventOnListeningNodes(t,i,n)}raiseM2DragEvent(t,i,n){i.target=t,i.type=j.Drag,this.raiseEventOnListeningNodes(t,i,n)}raiseM2DragEndEvent(t,i,n){i.target=t,i.type=j.DragEnd,this.raiseEventOnListeningNodes(t,i,n)}raiseSceneEvent(t,i){const n={target:t,type:i,...Y.createFrameUpdateTimestamps()};t.eventListeners.filter(c=>c.type===i).forEach(c=>c.callback(n))}calculatePointWithinNodeFromDomPointerEvent(t,i){let n=t.size.width,c=t.size.height;if(t.type===lt.Shape&&t.shapeType===Wt.Circle){const it=t.circleOfRadius;if(!it)throw"circleOfRadius is undefined";n=it*2,c=it*2}let h=i.offsetX,C=i.offsetY;const T=Y.calculateNodeAbsoluteBoundingBox(t);Y.nodeOrAncestorHasBeenRotated(t)&&Y.calculateRotationTransforms(t).forEach(ct=>{const ut=Y.rotatePoint({x:h,y:C},-ct.radians,ct.center);h=ut.x,C=ut.y});const B=(h-T.xMin)/(T.xMax-T.xMin)*n,$=(C-T.yMin)/(T.yMax-T.yMin)*c;return{x:B,y:$}}onStart(t,i){this.addEventListener(j.ActivityStart,t,i)}onCancel(t,i){this.addEventListener(j.ActivityCancel,t,i)}onEnd(t,i){this.addEventListener(j.ActivityEnd,t,i)}onData(t,i){this.addEventListener(j.ActivityData,t,i)}onWarmupStart(t,i){this.addEventListener(j.GameWarmupStart,t,i)}onWarmupEnd(t,i){this.addEventListener(j.GameWarmupEnd,t,i)}addEventListener(t,i,n){const c={type:t,activityUuid:this.uuid,callback:i};n?.replaceExisting&&(this.eventListeners=this.eventListeners.filter(h=>!(h.activityUuid===c.activityUuid&&h.type===c.type))),this.eventListeners.push(c)}raiseActivityEventOnListeners(t,i){i&&(t={...t,...i}),this.eventListeners.filter(n=>n.type===t.type).forEach(n=>{n.callback(t)})}raiseEventOnListeningNodes(t,i,n){t.eventListeners.filter(c=>c.type===i.type).forEach(c=>{if(c.nodeUuid===t.uuid){switch(i.target=t,i.type){case j.PointerDown:case j.PointerMove:case j.PointerUp:case j.PointerLeave:i.point=this.calculatePointWithinNodeFromDomPointerEvent(t,n),i.buttons=n.buttons,c.callback(i);break;case j.TapDown:case j.TapUp:case j.TapUpAny:case j.TapLeave:i.point=this.calculatePointWithinNodeFromDomPointerEvent(t,n),i.buttons=n.buttons,c.callback(i);break;case j.DragStart:case j.Drag:case j.DragEnd:i.position={x:t.position.x,y:t.position.y},i.buttons=n.buttons,c.callback(i);break}t.suppressEvents||this.eventStore.addEvent(i)}})}sceneCanReceiveUserInteraction(t){return!!(t._active&&t._transitioning===!1)}IsCanvasPointWithinNodeBounds(t,i,n){if(!t.isDrawable)throw"only drawable nodes can receive pointer events";if(t.type===lt.Shape&&t.shapeType===Wt.Circle){const h=Y.calculateNodeAbsoluteBoundingBox(t),C=t.circleOfRadius;if(!C)throw"circleOfRadius is undefined";const T={x:h.xMin+C*t.absoluteScale,y:h.yMin+C*t.absoluteScale};return Math.sqrt(Math.pow(i-T.x,2)+Math.pow(n-T.y,2))<=C*t.absoluteScale}if(t.size.width===0||t.size.height===0||t.type===lt.TextLine&&isNaN(t.size.width))return!1;const c=Y.calculateRotatedPoints(t);return t.isUserInteractionEnabled&&Y.isPointInsideRectangle({x:i,y:n},c)}}function fa(){globalThis.m2c2Globals={now:performance.now(),iso8601Now:"",deltaTime:NaN,canvasScale:NaN,rootScale:1,canvasCssWidth:NaN,canvasCssHeight:NaN,m2NodeClassRegistry:{},__sequence:0,get eventSequence(){return m2c2Globals.__sequence++,m2c2Globals.__sequence-1},addedScriptUrls:[]}}fa();const Gn=class Hn{constructor(t){this.startTime=NaN,this.stopTime=NaN,this.stopped=!0,this.cumulativeElapsed=NaN,this.name=t}static now(){return window.performance.now()}static start(t){let i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)i=new Hn(t),i.cumulativeElapsed=0,this._timers.push(i);else if(i.stopped==!1)throw new Error(`can't start timer. timer with name ${t} is already started`);i.startTime=window.performance.now(),i.stopped=!1}static stop(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't stop timer. timer with name ${t} does not exist`);if(i.stopped===!0)throw new Error(`can't stop timer. timer with name ${t} is already stopped`);i.stopTime=window.performance.now(),i.cumulativeElapsed=i.cumulativeElapsed+i.stopTime-i.startTime,i.stopped=!0}static restart(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't restart timer. timer with name ${t} does not exist`);i.startTime=window.performance.now(),i.cumulativeElapsed=0,i.stopped=!1}static elapsed(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't get elapsed time. timer with name ${t} does not exist`);return i.stopped?i.cumulativeElapsed:i.cumulativeElapsed+window.performance.now()-i.startTime}static remove(t){if(this._timers.filter(n=>n.name===t).find(Boolean)===void 0)throw new Error(`can't remove timer. timer with name ${t} does not exist`);this._timers=this._timers.filter(n=>n.name!=t)}static removeAll(){this._timers=new Array}static exists(t){return this._timers.some(i=>i.name===t)}};Gn._timers=new Array;let pa=Gn;class gr{static SingleFromRange(t,i){return Math.floor(Math.random()*(i-t+1))+t}static FromRangeWithoutReplacement(t,i,n){if(t>n-i+1)throw new Error(`number of requested draws (n = ${t}) is greater than number of integers in range [ ${i}, ${n}]`);const c=new Array;for(let h=0;h<t;h++){const C=gr.SingleFromRange(i,n);c.includes(C)?t++:c.push(C)}return c}static FromGridWithoutReplacement(t,i,n,c){const h=new Array,C=i*n-1,T=this.FromRangeWithoutReplacement(t,0,C);let B=0,$=NaN;for(;B<t;){const it=T[B]%n,ct=(T[B]-it)/n;if(c===void 0||c(ct,it))h.push({row:ct,column:it}),B++;else{do $=this.FromRangeWithoutReplacement(1,0,C)[0];while(T.includes($));T[B]=$}}return h}}class ma extends ae{constructor(t){super(t),this.type=lt.SoundPlayer,this.isDrawable=!1,this.soundName=t.soundName}initialize(){}dispose(){}duplicate(t){throw new Error("Method not implemented.")}}class ga extends ae{constructor(t){if(super(t),this.type=lt.SoundRecorder,this.isDrawable=!1,this._isRecording=!1,this._isPaused=!1,this.audioChunks=[],this.timerUuid="",t?.mimeType){const i=this.getMediaRecorderSupportedAudioMimeTypes();if(i.includes(t.mimeType))this.mimeType=t.mimeType;else if(console.warn(`Unsupported MIME type in SoundRecorderOptions: ${t.mimeType}. Supported types are: ${i}.`),t.backupMimeTypes){const n=this.getSupportedBackupMimeType(t.backupMimeTypes);n&&(this.mimeType=n,console.log(`Using backup MIME type: ${n}.`))}}t?.audioTrackConstraints&&(this.audioTrackConstraints=t.audioTrackConstraints),t?.maximumDuration&&(this.maximumDuration=t.maximumDuration)}initialize(){}async start(){if(this.isRecording)throw new Error("cannot start SoundRecorder because it is already started.");const t=this.getMediaRecorderSupportedAudioMimeTypes();if(t.length===0)throw new Error("SoundRecorder found no supported MIME types for MediaRecorder.");this.mimeType||(this.mimeType=t[0],console.log(`Using MIME type: ${this.mimeType}.`));let i;try{i=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints?this.audioTrackConstraints:!0})}catch{throw new Error("Error getting user media.")}if(!i)throw new Error("no stream.");const n=i.getAudioTracks();this.mediaTrackSettings=n?.map(c=>c.getSettings()),this.mediaRecorder=new MediaRecorder(i,{mimeType:this.mimeType}),this.mediaRecorder.ondataavailable=c=>{this.audioChunks.push(c.data)},this.mediaRecorder.onerror=c=>{throw new Error(`MediaRecorder error: ${c?.error?.message} ${c?.message}`)},this.mediaRecorder.start(),this.beginIso8601Timestamp=new Date().toISOString(),this.timerUuid=Ue.generate(),Gt.startNew(this.timerUuid),this._isRecording=!0,this._isPaused=!1}async stop(){if(!this.isRecording)throw new Error("cannot stop SoundRecorder because it has not started.");return new Promise(t=>{if(!this.mediaRecorder)throw new Error("no media recorder");this.mediaRecorder.onstop=async()=>{if(!this.mimeType)throw new Error("no mimeType");this._isRecording=!1,this._isPaused=!1;const i=new Blob(this.audioChunks,{type:this.getMimeTypeWithoutCodecs(this.mimeType)}),n=await this.blobToBase64(i);t({mimeType:this.mimeType,beginIso8601Timestamp:this.beginIso8601Timestamp??"",endIso8601Timestamp:this.endIso8601Timestamp??"",duration:Gt.elapsed(this.timerUuid),audioTrackSettings:this.mediaTrackSettings,audioBase64:n,audioBlob:i})},this.mediaRecorder.stop(),this.endIso8601Timestamp=new Date().toISOString(),this.isPaused||Gt.stop(this.timerUuid)})}pause(){if(!this.isRecording)throw new Error("cannot pause SoundRecorder because it is not started.");if(this.isPaused)throw new Error("cannot pause SoundRecorder because it is already paused.");this.mediaRecorder?.pause(),this._isPaused=!0,Gt.stop(this.timerUuid)}resume(){if(!this.isRecording)throw new Error("cannot resume SoundRecorder because it is not started.");if(!this.isPaused)throw new Error("cannot resume SoundRecorder because it is not paused.");this.mediaRecorder?.resume(),this._isPaused=!1,Gt.start(this.timerUuid)}get isRecording(){return this._isRecording}get isPaused(){return this._isPaused}update(){if(super.update(),this.isRecording&&!this.isPaused&&this.maximumDuration!==void 0&&Gt.elapsed(this.timerUuid)>this.maximumDuration){this.pause();return}}getMediaRecorderSupportedAudioMimeTypes(){const t=["audio"],i=["webm","ogg","mp3","mp4","x-matroska","3gpp","3gpp2","3gp2","quicktime","mpeg","aac","flac","x-flac","wave","wav","x-wav","x-pn-wav","not-supported"],n=["vp9","vp9.0","vp8","vp8.0","avc1","av1","h265","h.265","h264","h.264","opus","vorbis","pcm","aac","mpeg","mp4a","rtx","red","ulpfec","g722","pcmu","pcma","cn","telephone-event","not-supported"];return[...new Set(i.flatMap(c=>t.flatMap(h=>[`${h}/${c}`]))),...new Set(i.flatMap(c=>n.flatMap(h=>t.flatMap(C=>[`${C}/${c};codecs=${h}`])))),...new Set(i.flatMap(c=>n.flatMap(h=>n.flatMap(C=>t.flatMap(T=>[`${T}/${c};codecs="${h}, ${C}"`])))))].filter(c=>MediaRecorder.isTypeSupported(c))}blobToBase64(t){return new Promise((i,n)=>{const c=new FileReader;c.onloadend=()=>{const h=c.result?.toString().split(",").pop();if(h===void 0)throw new Error("base64WithoutPrefix is undefined.");i(h)},c.onerror=n,c.readAsDataURL(t)})}getMimeTypeWithoutCodecs(t){const i=t.match(/^[^;]+/);return i?i[0]:""}getSupportedBackupMimeType(t){const i=this.getMediaRecorderSupportedAudioMimeTypes();for(const n of t)if(i.includes(n))return n}dispose(){}duplicate(t){throw new Error(`Method not implemented. ${t}`)}}class ya{static create(t){return new Array}}console.log("\u26AA @m2c2kit/core version 0.3.24 (63d6720d)");export{q as Action,oi as ActivityType,xt as CanvasKitHelpers,qs as ColorfulMutablePath,Xs as Composite,X as Constants,Bt as ConstraintType,gn as CustomAction,Cn as Dimensions,Re as Easings,H as Equal,Qs as Equals,En as EventStore,de as EventStoreMode,bn as FadeAlphaAction,Tn as FontManager,da as Game,pn as GroupAction,Ni as I18n,lr as ImageManager,Ii as Label,$e as LabelHorizontalAlignmentMode,An as LayoutConstraint,pa as LegacyTimer,j as M2EventType,Qt as M2ImageStatus,ae as M2Node,_n as M2NodeFactory,lt as M2NodeType,Ut as M2SoundStatus,Y as M2c2KitHelpers,wn as MoveAction,Oi as MutablePath,zn as NoneTransition,yn as PlayAction,gr as RandomDraws,ar as RepeatAction,mn as RepeatForeverAction,Pn as RotateAction,Sn as ScaleAction,Ge as Scene,Un as SceneTransition,fn as SequenceAction,li as Shape,Wt as ShapeType,Bn as SlideTransition,Wn as SoundManager,ma as SoundPlayer,ga as SoundRecorder,hi as Sprite,ya as Story,Li as TextLine,Gt as Timer,We as Transition,ye as TransitionDirection,ge as TransitionType,Ue as Uuid,vn as WaitAction,x as WebColors,mr as WebGlInfo,Ne as handleInterfaceOptions};
3
+ `+l.replace(/^Error(:[^\n]*)?\n/,""))});return s.prototype=Object.create(e.prototype),s.prototype.constructor=s,s.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},s}(Error,"UnboundTypeError"),Object.assign(Dr.prototype,{get(e){return this.je[e]},has(e){return this.je[e]!==void 0},Af(e){var r=this.sf.pop()||this.je.length;return this.je[r]=e,r},Bf(e){this.je[e]=void 0,this.sf.push(e)}}),Kt.je.push({value:void 0},{value:null},{value:!0},{value:!1}),Kt.Ge=Kt.je.length,h.count_emval_handles=function(){for(var e=0,r=Kt.Ge;r<Kt.je.length;++r)Kt.je[r]!==void 0&&++e;return e};for(var E,jt=0;32>jt;++jt)Ci.push(Array(jt));var _s=new Float32Array(288);for(jt=0;288>jt;++jt)Pe[jt]=_s.subarray(0,jt+1);var Ts=new Int32Array(288);for(jt=0;288>jt;++jt)ei[jt]=Ts.subarray(0,jt+1);var Fs={T:function(){return 0},Bb:()=>{},Db:function(){return 0},yb:()=>{},zb:()=>{},U:function(){},Ab:()=>{},C:function(e){var r=ui[e];delete ui[e];var s=r.hf,l=r.ke,d=r.rf,m=d.map(P=>P.Vf).concat(d.map(P=>P.fg));te([e],m,P=>{var y={};return d.forEach((v,A)=>{var O=P[A],D=v.Tf,K=v.Uf,F=P[A+d.length],J=v.eg,st=v.gg;y[v.Of]={read:nt=>O.fromWireType(D(K,nt)),write:(nt,$t)=>{var kt=[];J(st,nt,F.toWireType(kt,$t)),Ui(kt)}}}),[{name:r.name,fromWireType:function(v){var A={},O;for(O in y)A[O]=y[O].read(v);return l(v),A},toWireType:function(v,A){for(var O in y)if(!(O in A))throw new TypeError(`Missing field: "${O}"`);var D=s();for(O in y)y[O].write(D,A[O]);return v!==null&&v.push(l,D),D},argPackAdvance:8,readValueFromPointer:Ke,de:l}]})},qb:function(){},Hb:function(e,r,s,l,d){var m=pi(s);r=Tt(r),le(e,{name:r,fromWireType:function(P){return!!P},toWireType:function(P,y){return y?l:d},argPackAdvance:8,readValueFromPointer:function(P){if(s===1)var y=oe;else if(s===2)y=Se;else if(s===4)y=G;else throw new TypeError("Unknown boolean type size: "+r);return this.fromWireType(y[P>>m])},de:null})},m:function(e,r,s,l,d,m,P,y,v,A,O,D,K){O=Tt(O),m=Ot(d,m),y&&(y=Ot(P,y)),A&&(A=Ot(v,A)),K=Ot(D,K);var F=kr(O);Ki(F,function(){Xe(`Cannot construct ${O} due to unbound types`,[l])}),te([e,r,s],l?[l]:[],function(J){if(J=J[0],l)var st=J.Pd,nt=st.Fe;else nt=be.prototype;J=ji(F,function(){if(Object.getPrototypeOf(this)!==$t)throw new Le("Use 'new' to construct "+O);if(kt.ne===void 0)throw new Le(O+" has no accessible constructor");var ri=kt.ne[arguments.length];if(ri===void 0)throw new Le(`Tried to invoke ctor of ${O} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(kt.ne).toString()}) parameters instead!`);return ri.apply(this,arguments)});var $t=Object.create(nt,{constructor:{value:J}});J.prototype=$t;var kt=new Zn(O,J,$t,K,st,m,y,A);kt.$d&&(kt.$d.Pe===void 0&&(kt.$d.Pe=[]),kt.$d.Pe.push(kt)),st=new he(O,kt,!0,!1,!1),nt=new he(O+"*",kt,!1,!1,!1);var ii=new he(O+" const*",kt,!1,!0,!1);return Nr[e]={pointerType:nt,If:ii},Or(F,J),[st,nt,ii]})},f:function(e,r,s,l,d,m,P){var y=yi(s,l);r=Tt(r),m=Ot(d,m),te([],[e],function(v){function A(){Xe(`Cannot call ${O} due to unbound types`,y)}v=v[0];var O=`${v.name}.${r}`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]);var D=v.Pd.constructor;return D[r]===void 0?(A.Ce=s-1,D[r]=A):(Hi(D,r,O),D[r].Xd[s-1]=A),te([],y,function(K){if(K=[K[0],null].concat(K.slice(1)),K=gi(O,K,null,m,P),D[r].Xd===void 0?(K.Ce=s-1,D[r]=K):D[r].Xd[s-1]=K,v.Pd.Pe)for(const F of v.Pd.Pe)F.constructor.hasOwnProperty(r)||(F.constructor[r]=K);return[]}),[]})},A:function(e,r,s,l,d,m){var P=yi(r,s);d=Ot(l,d),te([],[e],function(y){y=y[0];var v=`constructor ${y.name}`;if(y.Pd.ne===void 0&&(y.Pd.ne=[]),y.Pd.ne[r-1]!==void 0)throw new Le(`Cannot register multiple constructors with identical number of parameters (${r-1}) for class '${y.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return y.Pd.ne[r-1]=()=>{Xe(`Cannot construct ${y.name} due to unbound types`,P)},te([],P,function(A){return A.splice(1,0,null),y.Pd.ne[r-1]=gi(v,A,null,d,m),[]}),[]})},b:function(e,r,s,l,d,m,P,y){var v=yi(s,l);r=Tt(r),m=Ot(d,m),te([],[e],function(A){function O(){Xe(`Cannot call ${D} due to unbound types`,v)}A=A[0];var D=`${A.name}.${r}`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),y&&A.Pd.cg.push(r);var K=A.Pd.Fe,F=K[r];return F===void 0||F.Xd===void 0&&F.className!==A.name&&F.Ce===s-2?(O.Ce=s-2,O.className=A.name,K[r]=O):(Hi(K,r,D),K[r].Xd[s-2]=O),te([],v,function(J){return J=gi(D,J,A,m,P),K[r].Xd===void 0?(J.Ce=s-2,K[r]=J):K[r].Xd[s-2]=J,[]}),[]})},t:function(e,r,s){e=Tt(e),te([],[r],function(l){return l=l[0],h[e]=l.fromWireType(s),[]})},Gb:function(e,r){r=Tt(r),le(e,{name:r,fromWireType:function(s){var l=Vt(s);return qi(s),l},toWireType:function(s,l){return qt(l)},argPackAdvance:8,readValueFromPointer:Ke,de:null})},l:function(e,r,s,l){function d(){}s=pi(s),r=Tt(r),d.values={},le(e,{name:r,constructor:d,fromWireType:function(m){return this.constructor.values[m]},toWireType:function(m,P){return P.value},argPackAdvance:8,readValueFromPointer:ns(r,s,l),de:null}),Ki(r,d)},c:function(e,r,s){var l=Qe(e,"enum");r=Tt(r),e=l.constructor,l=Object.create(l.constructor.prototype,{value:{value:s},constructor:{value:ji(`${l.name}_${r}`,function(){})}}),e.values[s]=l,e[r]=l},W:function(e,r,s){s=pi(s),r=Tt(r),le(e,{name:r,fromWireType:function(l){return l},toWireType:function(l,d){return d},argPackAdvance:8,readValueFromPointer:ss(r,s),de:null})},y:function(e,r,s,l,d,m){var P=yi(r,s);e=Tt(e),d=Ot(l,d),Ki(e,function(){Xe(`Cannot call ${e} due to unbound types`,P)},r-1),te([],P,function(y){return y=[y[0],null].concat(y.slice(1)),Or(e,gi(e,y,null,d,m),r-1),[]})},E:function(e,r,s,l,d){r=Tt(r),d===-1&&(d=4294967295),d=pi(s);var m=y=>y;if(l===0){var P=32-8*s;m=y=>y<<P>>>P}s=r.includes("unsigned")?function(y,v){return v>>>0}:function(y,v){return v},le(e,{name:r,fromWireType:m,toWireType:s,argPackAdvance:8,readValueFromPointer:as(r,d,l!==0),de:null})},s:function(e,r,s){function l(m){m>>=2;var P=Pt;return new d(P.buffer,P[m+1],P[m])}var d=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][r];s=Tt(s),le(e,{name:s,fromWireType:l,argPackAdvance:8,readValueFromPointer:l},{Wf:!0})},q:function(e,r,s,l,d,m,P,y,v,A,O,D){s=Tt(s),m=Ot(d,m),y=Ot(P,y),A=Ot(v,A),D=Ot(O,D),te([e],[r],function(K){return K=K[0],[new he(s,K.Pd,!1,!1,!0,K,l,m,y,A,D)]})},V:function(e,r){r=Tt(r);var s=r==="std::string";le(e,{name:r,fromWireType:function(l){var d=Pt[l>>2],m=l+4;if(s)for(var P=m,y=0;y<=d;++y){var v=m+y;if(y==d||ht[v]==0){if(P=P?_e(ht,P,v-P):"",A===void 0)var A=P;else A+="\0",A+=P;P=v+1}}else{for(A=Array(d),y=0;y<d;++y)A[y]=String.fromCharCode(ht[m+y]);A=A.join("")}return me(l),A},toWireType:function(l,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var m=typeof d=="string";m||d instanceof Uint8Array||d instanceof Uint8ClampedArray||d instanceof Int8Array||mt("Cannot pass non-string to std::string");var P=s&&m?ie(d):d.length,y=Fi(4+P+1),v=y+4;if(Pt[y>>2]=P,s&&m)ee(d,ht,v,P+1);else if(m)for(m=0;m<P;++m){var A=d.charCodeAt(m);255<A&&(me(v),mt("String has UTF-16 code units that do not fit in 8 bits")),ht[v+m]=A}else for(m=0;m<P;++m)ht[v+m]=d[m];return l!==null&&l.push(me,y),y},argPackAdvance:8,readValueFromPointer:Ke,de:function(l){me(l)}})},N:function(e,r,s){if(s=Tt(s),r===2)var l=os,d=ls,m=hs,P=()=>ke,y=1;else r===4&&(l=cs,d=us,m=ds,P=()=>Pt,y=2);le(e,{name:s,fromWireType:function(v){for(var A=Pt[v>>2],O=P(),D,K=v+4,F=0;F<=A;++F){var J=v+4+F*r;(F==A||O[J>>y]==0)&&(K=l(K,J-K),D===void 0?D=K:(D+="\0",D+=K),K=J+r)}return me(v),D},toWireType:function(v,A){typeof A!="string"&&mt(`Cannot pass non-string to C++ string type ${s}`);var O=m(A),D=Fi(4+O+r);return Pt[D>>2]=O>>y,d(A,D+4,O+r),v!==null&&v.push(me,D),D},argPackAdvance:8,readValueFromPointer:Ke,de:function(v){me(v)}})},D:function(e,r,s,l,d,m){ui[e]={name:Tt(r),hf:Ot(s,l),ke:Ot(d,m),rf:[]}},e:function(e,r,s,l,d,m,P,y,v,A){ui[e].rf.push({Of:Tt(r),Vf:s,Tf:Ot(l,d),Uf:m,fg:P,eg:Ot(y,v),gg:A})},Ib:function(e,r){r=Tt(r),le(e,{Yf:!0,name:r,argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},Fb:()=>!0,ub:()=>{throw 1/0},F:function(e,r,s){e=Vt(e),r=Qe(r,"emval::as");var l=[],d=qt(l);return Pt[s>>2]=d,r.toWireType(l,e)},Z:function(e,r,s,l,d){e=wi[e],r=Vt(r),s=vi(s);var m=[];return Pt[l>>2]=qt(m),e(r,s,m,d)},w:function(e,r,s,l){e=wi[e],r=Vt(r),s=vi(s),e(r,s,null,l)},d:qi,K:function(e){return e===0?qt(Br()):(e=vi(e),qt(Br()[e]))},u:function(e,r){var s=ms(e,r),l=s[0];r=l.name+"_$"+s.slice(1).map(function(P){return P.name}).join("_")+"$";var d=Ur[r];if(d!==void 0)return d;var m=Array(e-1);return d=ps((P,y,v,A)=>{for(var O=0,D=0;D<e-1;++D)m[D]=s[D+1].readValueFromPointer(A+O),O+=s[D+1].argPackAdvance;for(P=P[y].apply(P,m),D=0;D<e-1;++D)s[D+1].Lf&&s[D+1].Lf(m[D]);if(!l.Yf)return l.toWireType(v,P)}),Ur[r]=d},z:function(e,r){return e=Vt(e),r=Vt(r),qt(e[r])},p:function(e){4<e&&(Kt.get(e).wf+=1)},J:function(e,r,s,l){e=Vt(e);var d=$r[r];return d||(d=gs(r),$r[r]=d),d(e,s,l)},H:function(){return qt([])},g:function(e){return qt(vi(e))},G:function(){return qt({})},kb:function(e){return e=Vt(e),!e},B:function(e){var r=Vt(e);Ui(r),qi(e)},i:function(e,r,s){e=Vt(e),r=Vt(r),s=Vt(s),e[r]=s},h:function(e,r){return e=Qe(e,"_emval_take_value"),e=e.readValueFromPointer(r),qt(e)},nb:function(){return-52},ob:function(){},a:()=>{zi("")},Eb:()=>performance.now(),vb:e=>{var r=ht.length;if(e>>>=0,2147483648<e)return!1;for(var s=1;4>=s;s*=2){var l=r*(1+.2/s);l=Math.min(l,e+100663296);var d=Math;l=Math.max(e,l);t:{d=d.min.call(d,2147483648,l+(65536-l%65536)%65536)-ci.buffer.byteLength+65535>>>16;try{ci.grow(d),vr();var m=1;break t}catch{}m=void 0}if(m)return!0}return!1},lb:function(){return rt?rt.handle:0},wb:(e,r)=>{var s=0;return Vr().forEach(function(l,d){var m=r+s;for(d=Pt[e+4*d>>2]=m,m=0;m<l.length;++m)oe[d++>>0]=l.charCodeAt(m);oe[d>>0]=0,s+=l.length+1}),0},xb:(e,r)=>{var s=Vr();Pt[e>>2]=s.length;var l=0;return s.forEach(function(d){l+=d.length+1}),Pt[r>>2]=l,0},Jb:e=>{Kn||(h.onExit&&h.onExit(e),Di=!0),it(e,new Jn(e))},M:()=>52,mb:function(){return 52},Cb:()=>52,pb:function(){return 70},S:(e,r,s,l)=>{for(var d=0,m=0;m<s;m++){var P=Pt[r>>2],y=Pt[r+4>>2];r+=8;for(var v=0;v<y;v++){var A=ht[P+v],O=As[e];A===0||A===10?((e===1?at:we)(_e(O,0)),O.length=0):O.push(A)}d+=y}return Pt[l>>2]=d,0},aa:function(e){E.activeTexture(e)},ba:function(e,r){E.attachShader(re[e],ne[r])},ca:function(e,r,s){E.bindAttribLocation(re[e],r,s?_e(ht,s):"")},da:function(e,r){e==35051?E.ef=r:e==35052&&(E.De=r),E.bindBuffer(e,Si[r])},$:function(e,r){E.bindFramebuffer(e,bi[r])},fc:function(e,r){E.bindRenderbuffer(e,Ze[r])},Rb:function(e,r){E.bindSampler(e,Fe[r])},ea:function(e,r){E.bindTexture(e,Yt[r])},zc:qr,Cc:qr,fa:function(e,r,s,l){E.blendColor(e,r,s,l)},ga:function(e){E.blendEquation(e)},ha:function(e,r){E.blendFunc(e,r)},$b:function(e,r,s,l,d,m,P,y,v,A){E.blitFramebuffer(e,r,s,l,d,m,P,y,v,A)},ia:function(e,r,s,l){2<=rt.version?s&&r?E.bufferData(e,ht,l,s,r):E.bufferData(e,r,l):E.bufferData(e,s?ht.subarray(s,s+r):r,l)},ja:function(e,r,s,l){2<=rt.version?s&&E.bufferSubData(e,r,ht,l,s):E.bufferSubData(e,r,ht.subarray(l,l+s))},gc:function(e){return E.checkFramebufferStatus(e)},Q:function(e){E.clear(e)},_:function(e,r,s,l){E.clearColor(e,r,s,l)},R:function(e){E.clearStencil(e)},sb:function(e,r,s,l){return E.clientWaitSync(Me[e],r,(s>>>0)+4294967296*l)},ka:function(e,r,s,l){E.colorMask(!!e,!!r,!!s,!!l)},la:function(e){E.compileShader(ne[e])},ma:function(e,r,s,l,d,m,P,y){2<=rt.version?E.De||!P?E.compressedTexImage2D(e,r,s,l,d,m,P,y):E.compressedTexImage2D(e,r,s,l,d,m,ht,y,P):E.compressedTexImage2D(e,r,s,l,d,m,y?ht.subarray(y,y+P):null)},na:function(e,r,s,l,d,m,P,y,v){2<=rt.version?E.De||!y?E.compressedTexSubImage2D(e,r,s,l,d,m,P,y,v):E.compressedTexSubImage2D(e,r,s,l,d,m,P,ht,v,y):E.compressedTexSubImage2D(e,r,s,l,d,m,P,v?ht.subarray(v,v+y):null)},Zb:function(e,r,s,l,d){E.copyBufferSubData(e,r,s,l,d)},oa:function(e,r,s,l,d,m,P,y){E.copyTexSubImage2D(e,r,s,l,d,m,P,y)},pa:function(){var e=De(re),r=E.createProgram();return r.name=e,r.Ye=r.We=r.Xe=0,r.kf=1,re[e]=r,e},qa:function(e){var r=De(ne);return ne[r]=E.createShader(e),r},ra:function(e){E.cullFace(e)},sa:function(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2],d=Si[l];d&&(E.deleteBuffer(d),d.name=0,Si[l]=null,l==E.ef&&(E.ef=0),l==E.De&&(E.De=0))}},hc:function(e,r){for(var s=0;s<e;++s){var l=G[r+4*s>>2],d=bi[l];d&&(E.deleteFramebuffer(d),d.name=0,bi[l]=null)}},ta:function(e){if(e){var r=re[e];r?(E.deleteProgram(r),r.name=0,re[e]=null):At(1281)}},ic:function(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2],d=Ze[l];d&&(E.deleteRenderbuffer(d),d.name=0,Ze[l]=null)}},Sb:function(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2],d=Fe[l];d&&(E.deleteSampler(d),d.name=0,Fe[l]=null)}},ua:function(e){if(e){var r=ne[e];r?(E.deleteShader(r),ne[e]=null):At(1281)}},_b:function(e){if(e){var r=Me[e];r?(E.deleteSync(r),r.name=0,Me[e]=null):At(1281)}},va:function(e,r){for(var s=0;s<e;s++){var l=G[r+4*s>>2],d=Yt[l];d&&(E.deleteTexture(d),d.name=0,Yt[l]=null)}},Ac:Yr,Dc:Yr,wa:function(e){E.depthMask(!!e)},xa:function(e){E.disable(e)},ya:function(e){E.disableVertexAttribArray(e)},za:function(e,r,s){E.drawArrays(e,r,s)},xc:function(e,r,s,l){E.drawArraysInstanced(e,r,s,l)},vc:function(e,r,s,l,d){E.pf.drawArraysInstancedBaseInstanceWEBGL(e,r,s,l,d)},tc:function(e,r){for(var s=Ci[e],l=0;l<e;l++)s[l]=G[r+4*l>>2];E.drawBuffers(s)},Aa:Jr,yc:function(e,r,s,l,d){E.drawElementsInstanced(e,r,s,l,d)},wc:function(e,r,s,l,d,m,P){E.pf.drawElementsInstancedBaseVertexBaseInstanceWEBGL(e,r,s,l,d,m,P)},nc:function(e,r,s,l,d,m){Jr(e,l,d,m)},Ba:function(e){E.enable(e)},Ca:function(e){E.enableVertexAttribArray(e)},Xb:function(e,r){return(e=E.fenceSync(e,r))?(r=De(Me),e.name=r,Me[r]=e,r):0},Da:function(){E.finish()},Ea:function(){E.flush()},jc:function(e,r,s,l){E.framebufferRenderbuffer(e,r,s,Ze[l])},kc:function(e,r,s,l,d){E.framebufferTexture2D(e,r,s,Yt[l],d)},Fa:function(e){E.frontFace(e)},Ga:function(e,r){ze(e,r,"createBuffer",Si)},lc:function(e,r){ze(e,r,"createFramebuffer",bi)},mc:function(e,r){ze(e,r,"createRenderbuffer",Ze)},Tb:function(e,r){ze(e,r,"createSampler",Fe)},Ha:function(e,r){ze(e,r,"createTexture",Yt)},Bc:Xr,Ec:Xr,bc:function(e){E.generateMipmap(e)},Ia:function(e,r,s){s?G[s>>2]=E.getBufferParameter(e,r):At(1281)},Ja:function(){var e=E.getError()||Ai;return Ai=0,e},Ka:function(e,r){Qr(e,r,2)},cc:function(e,r,s,l){e=E.getFramebufferAttachmentParameter(e,r,s),(e instanceof WebGLRenderbuffer||e instanceof WebGLTexture)&&(e=e.name|0),G[l>>2]=e},L:function(e,r){Qr(e,r,0)},La:function(e,r,s,l){e=E.getProgramInfoLog(re[e]),e===null&&(e="(unknown error)"),r=0<r&&l?ee(e,ht,l,r):0,s&&(G[s>>2]=r)},Ma:function(e,r,s){if(s)if(e>=Wr)At(1281);else if(e=re[e],r==35716)e=E.getProgramInfoLog(e),e===null&&(e="(unknown error)"),G[s>>2]=e.length+1;else if(r==35719){if(!e.Ye)for(r=0;r<E.getProgramParameter(e,35718);++r)e.Ye=Math.max(e.Ye,E.getActiveUniform(e,r).name.length+1);G[s>>2]=e.Ye}else if(r==35722){if(!e.We)for(r=0;r<E.getProgramParameter(e,35721);++r)e.We=Math.max(e.We,E.getActiveAttrib(e,r).name.length+1);G[s>>2]=e.We}else if(r==35381){if(!e.Xe)for(r=0;r<E.getProgramParameter(e,35382);++r)e.Xe=Math.max(e.Xe,E.getActiveUniformBlockName(e,r).length+1);G[s>>2]=e.Xe}else G[s>>2]=E.getProgramParameter(e,r);else At(1281)},dc:function(e,r,s){s?G[s>>2]=E.getRenderbufferParameter(e,r):At(1281)},Na:function(e,r,s,l){e=E.getShaderInfoLog(ne[e]),e===null&&(e="(unknown error)"),r=0<r&&l?ee(e,ht,l,r):0,s&&(G[s>>2]=r)},Ob:function(e,r,s,l){e=E.getShaderPrecisionFormat(e,r),G[s>>2]=e.rangeMin,G[s+4>>2]=e.rangeMax,G[l>>2]=e.precision},Oa:function(e,r,s){s?r==35716?(e=E.getShaderInfoLog(ne[e]),e===null&&(e="(unknown error)"),G[s>>2]=e?e.length+1:0):r==35720?(e=E.getShaderSource(ne[e]),G[s>>2]=e?e.length+1:0):G[s>>2]=E.getShaderParameter(ne[e],r):At(1281)},P:function(e){var r=Gr[e];if(!r){switch(e){case 7939:r=E.getSupportedExtensions()||[],r=r.concat(r.map(function(l){return"GL_"+l})),r=ti(r.join(" "));break;case 7936:case 7937:case 37445:case 37446:(r=E.getParameter(e))||At(1280),r=r&&ti(r);break;case 7938:r=E.getParameter(7938),r=2<=rt.version?"OpenGL ES 3.0 ("+r+")":"OpenGL ES 2.0 ("+r+")",r=ti(r);break;case 35724:r=E.getParameter(35724);var s=r.match(/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/);s!==null&&(s[1].length==3&&(s[1]+="0"),r="OpenGL ES GLSL ES "+s[1]+" ("+r+")"),r=ti(r);break;default:At(1280)}Gr[e]=r}return r},jb:function(e,r){if(2>rt.version)return At(1282),0;var s=jr[e];if(s)return 0>r||r>=s.length?(At(1281),0):s[r];switch(e){case 7939:return s=E.getSupportedExtensions()||[],s=s.concat(s.map(function(l){return"GL_"+l})),s=s.map(function(l){return ti(l)}),s=jr[e]=s,0>r||r>=s.length?(At(1281),0):s[r];default:return At(1280),0}},Pa:function(e,r){if(r=r?_e(ht,r):"",e=re[e]){var s=e,l=s.Ne,d=s.yf,m;if(!l)for(s.Ne=l={},s.xf={},m=0;m<E.getProgramParameter(s,35718);++m){var P=E.getActiveUniform(s,m),y=P.name;P=P.size;var v=Zr(y);v=0<v?y.slice(0,v):y;var A=s.kf;for(s.kf+=P,d[v]=[P,A],y=0;y<P;++y)l[A]=y,s.xf[A++]=v}if(s=e.Ne,l=0,d=r,m=Zr(r),0<m&&(l=parseInt(r.slice(m+1))>>>0,d=r.slice(0,m)),(d=e.yf[d])&&l<d[0]&&(l+=d[1],s[l]=s[l]||E.getUniformLocation(e,r)))return l}else At(1281);return-1},Pb:function(e,r,s){for(var l=Ci[r],d=0;d<r;d++)l[d]=G[s+4*d>>2];E.invalidateFramebuffer(e,l)},Qb:function(e,r,s,l,d,m,P){for(var y=Ci[r],v=0;v<r;v++)y[v]=G[s+4*v>>2];E.invalidateSubFramebuffer(e,y,l,d,m,P)},Yb:function(e){return E.isSync(Me[e])},Qa:function(e){return(e=Yt[e])?E.isTexture(e):0},Ra:function(e){E.lineWidth(e)},Sa:function(e){e=re[e],E.linkProgram(e),e.Ne=0,e.yf={}},rc:function(e,r,s,l,d,m){E.uf.multiDrawArraysInstancedBaseInstanceWEBGL(e,G,r>>2,G,s>>2,G,l>>2,Pt,d>>2,m)},sc:function(e,r,s,l,d,m,P,y){E.uf.multiDrawElementsInstancedBaseVertexBaseInstanceWEBGL(e,G,r>>2,s,G,l>>2,G,d>>2,G,m>>2,Pt,P>>2,y)},Ta:function(e,r){e==3317&&(Hr=r),E.pixelStorei(e,r)},uc:function(e){E.readBuffer(e)},Ua:function(e,r,s,l,d,m,P){if(2<=rt.version)if(E.ef)E.readPixels(e,r,s,l,d,m,P);else{var y=Ei(m);E.readPixels(e,r,s,l,d,m,y,P>>31-Math.clz32(y.BYTES_PER_ELEMENT))}else(P=Qi(m,d,s,l,P))?E.readPixels(e,r,s,l,d,m,P):At(1280)},ec:function(e,r,s,l){E.renderbufferStorage(e,r,s,l)},ac:function(e,r,s,l,d){E.renderbufferStorageMultisample(e,r,s,l,d)},Ub:function(e,r,s){E.samplerParameterf(Fe[e],r,s)},Vb:function(e,r,s){E.samplerParameteri(Fe[e],r,s)},Wb:function(e,r,s){E.samplerParameteri(Fe[e],r,G[s>>2])},Va:function(e,r,s,l){E.scissor(e,r,s,l)},Wa:function(e,r,s,l){for(var d="",m=0;m<r;++m){var P=l?G[l+4*m>>2]:-1,y=G[s+4*m>>2];P=y?_e(ht,y,0>P?void 0:P):"",d+=P}E.shaderSource(ne[e],d)},Xa:function(e,r,s){E.stencilFunc(e,r,s)},Ya:function(e,r,s,l){E.stencilFuncSeparate(e,r,s,l)},Za:function(e){E.stencilMask(e)},_a:function(e,r){E.stencilMaskSeparate(e,r)},$a:function(e,r,s){E.stencilOp(e,r,s)},ab:function(e,r,s,l){E.stencilOpSeparate(e,r,s,l)},bb:function(e,r,s,l,d,m,P,y,v){if(2<=rt.version)if(E.De)E.texImage2D(e,r,s,l,d,m,P,y,v);else if(v){var A=Ei(y);E.texImage2D(e,r,s,l,d,m,P,y,A,v>>31-Math.clz32(A.BYTES_PER_ELEMENT))}else E.texImage2D(e,r,s,l,d,m,P,y,null);else E.texImage2D(e,r,s,l,d,m,P,y,v?Qi(y,P,l,d,v):null)},cb:function(e,r,s){E.texParameterf(e,r,s)},db:function(e,r,s){E.texParameterf(e,r,tt[s>>2])},eb:function(e,r,s){E.texParameteri(e,r,s)},fb:function(e,r,s){E.texParameteri(e,r,G[s>>2])},oc:function(e,r,s,l,d){E.texStorage2D(e,r,s,l,d)},gb:function(e,r,s,l,d,m,P,y,v){if(2<=rt.version)if(E.De)E.texSubImage2D(e,r,s,l,d,m,P,y,v);else if(v){var A=Ei(y);E.texSubImage2D(e,r,s,l,d,m,P,y,A,v>>31-Math.clz32(A.BYTES_PER_ELEMENT))}else E.texSubImage2D(e,r,s,l,d,m,P,y,null);else A=null,v&&(A=Qi(y,P,d,m,v)),E.texSubImage2D(e,r,s,l,d,m,P,y,A)},hb:function(e,r){E.uniform1f(vt(e),r)},ib:function(e,r,s){if(2<=rt.version)r&&E.uniform1fv(vt(e),tt,s>>2,r);else{if(288>=r)for(var l=Pe[r-1],d=0;d<r;++d)l[d]=tt[s+4*d>>2];else l=tt.subarray(s>>2,s+4*r>>2);E.uniform1fv(vt(e),l)}},Zc:function(e,r){E.uniform1i(vt(e),r)},_c:function(e,r,s){if(2<=rt.version)r&&E.uniform1iv(vt(e),G,s>>2,r);else{if(288>=r)for(var l=ei[r-1],d=0;d<r;++d)l[d]=G[s+4*d>>2];else l=G.subarray(s>>2,s+4*r>>2);E.uniform1iv(vt(e),l)}},$c:function(e,r,s){E.uniform2f(vt(e),r,s)},ad:function(e,r,s){if(2<=rt.version)r&&E.uniform2fv(vt(e),tt,s>>2,2*r);else{if(144>=r)for(var l=Pe[2*r-1],d=0;d<2*r;d+=2)l[d]=tt[s+4*d>>2],l[d+1]=tt[s+(4*d+4)>>2];else l=tt.subarray(s>>2,s+8*r>>2);E.uniform2fv(vt(e),l)}},Yc:function(e,r,s){E.uniform2i(vt(e),r,s)},Xc:function(e,r,s){if(2<=rt.version)r&&E.uniform2iv(vt(e),G,s>>2,2*r);else{if(144>=r)for(var l=ei[2*r-1],d=0;d<2*r;d+=2)l[d]=G[s+4*d>>2],l[d+1]=G[s+(4*d+4)>>2];else l=G.subarray(s>>2,s+8*r>>2);E.uniform2iv(vt(e),l)}},Wc:function(e,r,s,l){E.uniform3f(vt(e),r,s,l)},Vc:function(e,r,s){if(2<=rt.version)r&&E.uniform3fv(vt(e),tt,s>>2,3*r);else{if(96>=r)for(var l=Pe[3*r-1],d=0;d<3*r;d+=3)l[d]=tt[s+4*d>>2],l[d+1]=tt[s+(4*d+4)>>2],l[d+2]=tt[s+(4*d+8)>>2];else l=tt.subarray(s>>2,s+12*r>>2);E.uniform3fv(vt(e),l)}},Uc:function(e,r,s,l){E.uniform3i(vt(e),r,s,l)},Tc:function(e,r,s){if(2<=rt.version)r&&E.uniform3iv(vt(e),G,s>>2,3*r);else{if(96>=r)for(var l=ei[3*r-1],d=0;d<3*r;d+=3)l[d]=G[s+4*d>>2],l[d+1]=G[s+(4*d+4)>>2],l[d+2]=G[s+(4*d+8)>>2];else l=G.subarray(s>>2,s+12*r>>2);E.uniform3iv(vt(e),l)}},Sc:function(e,r,s,l,d){E.uniform4f(vt(e),r,s,l,d)},Rc:function(e,r,s){if(2<=rt.version)r&&E.uniform4fv(vt(e),tt,s>>2,4*r);else{if(72>=r){var l=Pe[4*r-1],d=tt;s>>=2;for(var m=0;m<4*r;m+=4){var P=s+m;l[m]=d[P],l[m+1]=d[P+1],l[m+2]=d[P+2],l[m+3]=d[P+3]}}else l=tt.subarray(s>>2,s+16*r>>2);E.uniform4fv(vt(e),l)}},Fc:function(e,r,s,l,d){E.uniform4i(vt(e),r,s,l,d)},Gc:function(e,r,s){if(2<=rt.version)r&&E.uniform4iv(vt(e),G,s>>2,4*r);else{if(72>=r)for(var l=ei[4*r-1],d=0;d<4*r;d+=4)l[d]=G[s+4*d>>2],l[d+1]=G[s+(4*d+4)>>2],l[d+2]=G[s+(4*d+8)>>2],l[d+3]=G[s+(4*d+12)>>2];else l=G.subarray(s>>2,s+16*r>>2);E.uniform4iv(vt(e),l)}},Hc:function(e,r,s,l){if(2<=rt.version)r&&E.uniformMatrix2fv(vt(e),!!s,tt,l>>2,4*r);else{if(72>=r)for(var d=Pe[4*r-1],m=0;m<4*r;m+=4)d[m]=tt[l+4*m>>2],d[m+1]=tt[l+(4*m+4)>>2],d[m+2]=tt[l+(4*m+8)>>2],d[m+3]=tt[l+(4*m+12)>>2];else d=tt.subarray(l>>2,l+16*r>>2);E.uniformMatrix2fv(vt(e),!!s,d)}},Ic:function(e,r,s,l){if(2<=rt.version)r&&E.uniformMatrix3fv(vt(e),!!s,tt,l>>2,9*r);else{if(32>=r)for(var d=Pe[9*r-1],m=0;m<9*r;m+=9)d[m]=tt[l+4*m>>2],d[m+1]=tt[l+(4*m+4)>>2],d[m+2]=tt[l+(4*m+8)>>2],d[m+3]=tt[l+(4*m+12)>>2],d[m+4]=tt[l+(4*m+16)>>2],d[m+5]=tt[l+(4*m+20)>>2],d[m+6]=tt[l+(4*m+24)>>2],d[m+7]=tt[l+(4*m+28)>>2],d[m+8]=tt[l+(4*m+32)>>2];else d=tt.subarray(l>>2,l+36*r>>2);E.uniformMatrix3fv(vt(e),!!s,d)}},Jc:function(e,r,s,l){if(2<=rt.version)r&&E.uniformMatrix4fv(vt(e),!!s,tt,l>>2,16*r);else{if(18>=r){var d=Pe[16*r-1],m=tt;l>>=2;for(var P=0;P<16*r;P+=16){var y=l+P;d[P]=m[y],d[P+1]=m[y+1],d[P+2]=m[y+2],d[P+3]=m[y+3],d[P+4]=m[y+4],d[P+5]=m[y+5],d[P+6]=m[y+6],d[P+7]=m[y+7],d[P+8]=m[y+8],d[P+9]=m[y+9],d[P+10]=m[y+10],d[P+11]=m[y+11],d[P+12]=m[y+12],d[P+13]=m[y+13],d[P+14]=m[y+14],d[P+15]=m[y+15]}}else d=tt.subarray(l>>2,l+64*r>>2);E.uniformMatrix4fv(vt(e),!!s,d)}},Kc:function(e){e=re[e],E.useProgram(e),E.Kf=e},Lc:function(e,r){E.vertexAttrib1f(e,r)},Mc:function(e,r){E.vertexAttrib2f(e,tt[r>>2],tt[r+4>>2])},Nc:function(e,r){E.vertexAttrib3f(e,tt[r>>2],tt[r+4>>2],tt[r+8>>2])},Oc:function(e,r){E.vertexAttrib4f(e,tt[r>>2],tt[r+4>>2],tt[r+8>>2],tt[r+12>>2])},pc:function(e,r){E.vertexAttribDivisor(e,r)},qc:function(e,r,s,l,d){E.vertexAttribIPointer(e,r,s,l,d)},Pc:function(e,r,s,l,d,m){E.vertexAttribPointer(e,r,s,!!l,d,m)},Qc:function(e,r,s,l){E.viewport(e,r,s,l)},rb:function(e,r,s,l){E.waitSync(Me[e],r,(s>>>0)+4294967296*l)},j:xs,n:Ds,k:Ms,I:Bs,Lb:Us,Y:$s,X:Gs,O:Os,o:Ls,x:ks,r:Ns,v:Is,Kb:Ws,Mb:zs,Nb:Rs,tb:(e,r,s,l)=>Es(e,r,s,l)};(function(){function e(s){if(dt=s=s.exports,ci=dt.bd,vr(),Rt=dt.dd,Sr.unshift(dt.cd),Ee--,h.monitorRunDependencies&&h.monitorRunDependencies(Ee),Ee==0&&He){var l=He;He=null,l()}return s}var r={a:Fs};if(Ee++,h.monitorRunDependencies&&h.monitorRunDependencies(Ee),h.instantiateWasm)try{return h.instantiateWasm(r,e)}catch(s){we("Module.instantiateWasm callback failed with error: "+s),T(s)}return Yn(r,function(s){e(s.instance)}).catch(T),{}})();var me=h._free=e=>(me=h._free=dt.ed)(e),Fi=h._malloc=e=>(Fi=h._malloc=dt.fd)(e),nn=e=>(nn=dt.gd)(e);h.__embind_initialize_bindings=()=>(h.__embind_initialize_bindings=dt.hd)();var It=(e,r)=>(It=dt.id)(e,r),Lt=()=>(Lt=dt.jd)(),Dt=e=>(Dt=dt.kd)(e);h.dynCall_viji=(e,r,s,l,d)=>(h.dynCall_viji=dt.ld)(e,r,s,l,d),h.dynCall_vijiii=(e,r,s,l,d,m,P)=>(h.dynCall_vijiii=dt.md)(e,r,s,l,d,m,P),h.dynCall_viiiiij=(e,r,s,l,d,m,P,y)=>(h.dynCall_viiiiij=dt.nd)(e,r,s,l,d,m,P,y),h.dynCall_jiiiijiiiii=(e,r,s,l,d,m,P,y,v,A,O,D)=>(h.dynCall_jiiiijiiiii=dt.od)(e,r,s,l,d,m,P,y,v,A,O,D),h.dynCall_viiij=(e,r,s,l,d,m)=>(h.dynCall_viiij=dt.pd)(e,r,s,l,d,m),h.dynCall_jii=(e,r,s)=>(h.dynCall_jii=dt.qd)(e,r,s),h.dynCall_vij=(e,r,s,l)=>(h.dynCall_vij=dt.rd)(e,r,s,l),h.dynCall_iiij=(e,r,s,l,d)=>(h.dynCall_iiij=dt.sd)(e,r,s,l,d),h.dynCall_iiiij=(e,r,s,l,d,m)=>(h.dynCall_iiiij=dt.td)(e,r,s,l,d,m),h.dynCall_viij=(e,r,s,l,d)=>(h.dynCall_viij=dt.ud)(e,r,s,l,d),h.dynCall_ji=(e,r)=>(h.dynCall_ji=dt.vd)(e,r),h.dynCall_iij=(e,r,s,l)=>(h.dynCall_iij=dt.wd)(e,r,s,l),h.dynCall_jiiiiii=(e,r,s,l,d,m,P)=>(h.dynCall_jiiiiii=dt.xd)(e,r,s,l,d,m,P),h.dynCall_jiiiiji=(e,r,s,l,d,m,P,y)=>(h.dynCall_jiiiiji=dt.yd)(e,r,s,l,d,m,P,y),h.dynCall_iijj=(e,r,s,l,d,m)=>(h.dynCall_iijj=dt.zd)(e,r,s,l,d,m),h.dynCall_iiiji=(e,r,s,l,d,m)=>(h.dynCall_iiiji=dt.Ad)(e,r,s,l,d,m),h.dynCall_iiji=(e,r,s,l,d)=>(h.dynCall_iiji=dt.Bd)(e,r,s,l,d),h.dynCall_iijjiii=(e,r,s,l,d,m,P,y,v)=>(h.dynCall_iijjiii=dt.Cd)(e,r,s,l,d,m,P,y,v),h.dynCall_vijjjii=(e,r,s,l,d,m,P,y,v,A)=>(h.dynCall_vijjjii=dt.Dd)(e,r,s,l,d,m,P,y,v,A),h.dynCall_jiji=(e,r,s,l,d)=>(h.dynCall_jiji=dt.Ed)(e,r,s,l,d),h.dynCall_viijii=(e,r,s,l,d,m,P)=>(h.dynCall_viijii=dt.Fd)(e,r,s,l,d,m,P),h.dynCall_iiiiij=(e,r,s,l,d,m,P)=>(h.dynCall_iiiiij=dt.Gd)(e,r,s,l,d,m,P),h.dynCall_iiiiijj=(e,r,s,l,d,m,P,y,v)=>(h.dynCall_iiiiijj=dt.Hd)(e,r,s,l,d,m,P,y,v),h.dynCall_iiiiiijj=(e,r,s,l,d,m,P,y,v,A)=>(h.dynCall_iiiiiijj=dt.Id)(e,r,s,l,d,m,P,y,v,A);function Ms(e,r,s,l){var d=Lt();try{return Rt.get(e)(r,s,l)}catch(m){if(Dt(d),m!==m+0)throw m;It(1,0)}}function xs(e,r){var s=Lt();try{return Rt.get(e)(r)}catch(l){if(Dt(s),l!==l+0)throw l;It(1,0)}}function Rs(e,r,s,l,d,m,P,y,v,A){var O=Lt();try{Rt.get(e)(r,s,l,d,m,P,y,v,A)}catch(D){if(Dt(O),D!==D+0)throw D;It(1,0)}}function Ns(e,r,s,l){var d=Lt();try{Rt.get(e)(r,s,l)}catch(m){if(Dt(d),m!==m+0)throw m;It(1,0)}}function ks(e,r,s){var l=Lt();try{Rt.get(e)(r,s)}catch(d){if(Dt(l),d!==d+0)throw d;It(1,0)}}function Os(e){var r=Lt();try{Rt.get(e)()}catch(s){if(Dt(r),s!==s+0)throw s;It(1,0)}}function Is(e,r,s,l,d){var m=Lt();try{Rt.get(e)(r,s,l,d)}catch(P){if(Dt(m),P!==P+0)throw P;It(1,0)}}function Ls(e,r){var s=Lt();try{Rt.get(e)(r)}catch(l){if(Dt(s),l!==l+0)throw l;It(1,0)}}function Ds(e,r,s){var l=Lt();try{return Rt.get(e)(r,s)}catch(d){if(Dt(l),d!==d+0)throw d;It(1,0)}}function zs(e,r,s,l,d,m,P){var y=Lt();try{Rt.get(e)(r,s,l,d,m,P)}catch(v){if(Dt(y),v!==v+0)throw v;It(1,0)}}function Bs(e,r,s,l,d){var m=Lt();try{return Rt.get(e)(r,s,l,d)}catch(P){if(Dt(m),P!==P+0)throw P;It(1,0)}}function Us(e,r,s,l,d,m){var P=Lt();try{return Rt.get(e)(r,s,l,d,m)}catch(y){if(Dt(P),y!==y+0)throw y;It(1,0)}}function $s(e,r,s,l,d,m,P){var y=Lt();try{return Rt.get(e)(r,s,l,d,m,P)}catch(v){if(Dt(y),v!==v+0)throw v;It(1,0)}}function Ws(e,r,s,l,d,m){var P=Lt();try{Rt.get(e)(r,s,l,d,m)}catch(y){if(Dt(P),y!==y+0)throw y;It(1,0)}}function Gs(e,r,s,l,d,m,P,y,v,A){var O=Lt();try{return Rt.get(e)(r,s,l,d,m,P,y,v,A)}catch(D){if(Dt(O),D!==D+0)throw D;It(1,0)}}var Mi;He=function e(){Mi||sn(),Mi||(He=e)};function sn(){function e(){if(!Mi&&(Mi=!0,h.calledRun=!0,!Di)){if(Bi(Sr),C(h),h.onRuntimeInitialized&&h.onRuntimeInitialized(),h.postRun)for(typeof h.postRun=="function"&&(h.postRun=[h.postRun]);h.postRun.length;){var r=h.postRun.shift();br.unshift(r)}Bi(br)}}if(!(0<Ee)){if(h.preRun)for(typeof h.preRun=="function"&&(h.preRun=[h.preRun]);h.preRun.length;)Vn();Bi(wr),0<Ee||(h.setStatus?(h.setStatus("Running..."),setTimeout(function(){setTimeout(function(){h.setStatus("")},1),e()},1)):e())}}if(h.preInit)for(typeof h.preInit=="function"&&(h.preInit=[h.preInit]);0<h.preInit.length;)h.preInit.pop()();return sn(),c.ready}})();g.exports=i}(cr)),cr.exports}var ha=la(),ca=Zs(ha);class We{static slide(t){let i=Re.linear;return typeof t.easing=="string"?i=Re.fromTypeAsString(t.easing):t.easing!==void 0&&(i=t.easing),new Bn(t.direction,t.duration,i)}static none(){return new zn}}class zn extends We{constructor(){super(),this.type=ge.None,this.duration=NaN,this.easing=Re.none}}class Bn extends We{constructor(t,i,n){super(),this.type=ge.Slide,this.direction=t,this.duration=i,this.easing=n}}const ge={Slide:"Slide",None:"None"},ye={Up:"Up",Down:"Down",Right:"Right",Left:"Left"};class Un{constructor(t,i){this.scene=t,this.transition=i}}const $n={type:"object",description:"Information about the user's device.",properties:{userAgent:{type:"string",description:"The user agent string returned by navigator.userAgent."},devicePixelRatio:{type:"number",description:"Ratio of physical pixels to CSS pixels."},screen:{type:"object",description:"Screen information returned by window.screen.",properties:{availHeight:{type:"number",description:"Height of screen, in pixels, excluding UI features."},availWidth:{type:"number",description:"Width of screen, in pixels, excluding UI features."},colorDepth:{type:"number",description:"Color depth of screen."},height:{type:"number",description:"Height of screen, in pixels"},width:{type:"number",description:"Width of screen, in pixels."},orientation:{type:"object",description:"Information about the device's orientation.",properties:{type:{type:"string",description:"The orientation type (ScreenOrientation.type)."},angle:{type:"number",description:"The orientation angle (ScreenOrientation.angle)."}}},pixelDepth:{type:"number",description:"Pixel depth of screen."}}},webGlRenderer:{type:"string",description:"WebGL driver vendor and renderer. Taken from WEBGL_debug_renderer_info."}}};class mr{static getRendererString(){const t=document.createElement("canvas");t.id="webgl-renderer-info-canvas",t.height=0,t.width=0,t.hidden=!0,document.body.appendChild(t);const i=t.getContext("webgl");let n="no webgl context";if(!i)return n;const c=i.getExtension("WEBGL_debug_renderer_info");return c!=null?n=String(i.getParameter(c.UNMASKED_VENDOR_WEBGL))+", "+String(i.getParameter(c.UNMASKED_RENDERER_WEBGL)):n="no debug renderer info",t.remove(),n}static dispose(){const t=document.getElementById("webgl-renderer-info-canvas");t&&t.remove()}}class Wn{constructor(t,i){this.sounds={},this.game=t,this.baseUrls=i}get audioContext(){if(!this._audioContext){if(!navigator.userActivation.hasBeenActive)throw new Error("AudioContext cannot be created until user has interacted with the page");this._audioContext=new AudioContext}return this._audioContext}initializeSounds(t){return t?this.loadSounds(t):Promise.resolve()}loadSounds(t){return t.length===0?Promise.resolve():(t.forEach(i=>{let n=i.url;Y.urlHasScheme(i.url)||(n=Y.getUrlFromManifest(this.game,`${this.baseUrls.assets}/${i.url}`));const c={soundName:i.soundName,data:void 0,audioBuffer:void 0,url:n,status:i.lazy?Ut.Deferred:Ut.WillFetch};this.sounds[i.soundName]&&console.warn(`A sound named ${i.soundName} has already been loaded. It will be replaced.`),this.sounds[i.soundName]=c}),this.fetchSounds())}async fetchSounds(){const t=Object.values(this.sounds).map(i=>i.status===Ut.WillFetch?(i.status=Ut.Fetching,fetch(i.url).then(n=>{if(!n.ok)throw i.status=Ut.Error,new Error(`cannot fetch sound ${i.soundName} at url ${i.url}: ${n.statusText}`);return n.arrayBuffer().then(c=>{i.data=c,i.status=Ut.Fetched,console.log(`\u26AA sound fetched. name: ${i.soundName}, bytes: ${c.byteLength}`)})})):Promise.resolve());await Promise.all(t)}fetchDeferredSound(t){return t.status=Ut.WillFetch,this.fetchSounds()}hasSoundsToDecode(){return Object.values(this.sounds).filter(t=>t.status===Ut.Fetched).length>0}decodeFetchedSounds(){const i=Object.values(this.sounds).filter(n=>n.status===Ut.Fetched).map(n=>this.decodeSound(n));return Promise.all(i)}async decodeSound(t){if(!t.data)throw new Error(`data is undefined for sound ${t.soundName} (url ${t.url})`);try{t.status=Ut.Decoding;const i=await this.audioContext.decodeAudioData(t.data);t.audioBuffer=i,t.status=Ut.Ready,console.log(`\u26AA sound decoded. name: ${t.soundName}, duration (seconds): ${i.duration}`)}catch{throw t.status=Ut.Error,new Error(`error decoding sound ${t.soundName} (url: ${t.url})`)}}getSound(t){const i=this.sounds[t];if(!i)throw new Error(`getSound(): sound ${t} not found`);return i}dispose(){}getSoundNames(){return Object.keys(this.sounds)}}class ua{constructor(t){this.game=t.game,this.nodeFactory=t.nodeFactory,this.freeNodesScene=t.freeNodesScene,this.configureI18n=t.configureI18n,this.eventMaterializers=new Map([[j.NodeNew,this.materializeNodeNewEvent.bind(this)],[j.Composite,this.materializeCompositeEvent.bind(this)],[j.ScenePresent,this.materializeScenePresentEvent.bind(this)],[j.NodePropertyChange,this.materializeNodePropertyChangeEvent.bind(this)],[j.NodeAddChild,this.materializeNodeAddChildEvent.bind(this)],[j.NodeRemoveChild,this.materializeNodeRemoveChildEvent.bind(this)],[j.DomPointerDown,this.materializeDomPointerDownEvent.bind(this)],[j.BrowserImageDataReady,this.materializeBrowserImageDataReadyEvent.bind(this)],[j.I18nDataReadyEvent,this.materializeI18nDataReadyEvent.bind(this)]])}materialize(t){t.length>0&&(console.log(`Replaying ${t.length} events`),t.forEach(i=>{const n=this.eventMaterializers.get(i.type);n?n(i):console.log(`EventMaterializer unhandled event: ${i.type}`)}))}materializeCompositeEvent(t){const i=this.game.materializedNodes.find(n=>n.uuid===t.target);if(!i)console.log(`EventMaterializer: composite node of type ${t.compositeType} with uuid ${t.target} not found when handling CompositeEvent ${t.compositeEventType}`);else if(i.type===lt.Composite)i.handleCompositeEvent(t);else throw new Error(`EventMaterializer: node was expected to be composite, but was of type ${i.type}`)}materializeNodeNewEvent(t){const i=this.nodeFactory.createNode(t.nodeType,t.compositeType,t.nodeOptions);i.type===lt.Scene&&(i.name===X.FREE_NODES_SCENE_NAME?(this.freeNodesScene=i,this.freeNodesScene.game=this.game,this.freeNodesScene.needsInitialization=!0,this.game.freeNodesScene=this.freeNodesScene):this.game.addScene(i)),this.game.materializedNodes.push(i)}materializeNodePropertyChangeEvent(t){const i=this.game.materializedNodes.find(n=>n.uuid===t.uuid);if(!i)throw new Error(`EventMaterializer: node with uuid ${t.uuid} not found`);if(t.property in i)i[t.property]=t.value;else throw new Error(`EventMaterializer: on node ${i.name}, type ${i.type}, nodePropertyChangeEvent tried to set unknown property ${t.property} to value ${JSON.stringify(t.value)}`)}materializeNodeAddChildEvent(t){const i=this.game.materializedNodes.find(c=>c.uuid===t.uuid);if(!i)throw new Error(`EventMaterializer: parent node with uuid ${t.uuid} not found`);const n=this.game.materializedNodes.find(c=>c.uuid===t.childUuid);if(!n)throw new Error(`EventMaterializer: child node with uuid ${t.childUuid} not found`);i.addChild(n)}materializeNodeRemoveChildEvent(t){const i=this.game.materializedNodes.find(c=>c.uuid===t.uuid);if(!i)throw new Error(`EventMaterializer: parent node with uuid ${t.uuid} not found`);const n=this.game.materializedNodes.find(c=>c.uuid===t.childUuid);if(!n)throw new Error(`EventMaterializer: child node with uuid ${t.childUuid} not found`);i.removeChild(n)}materializeDomPointerDownEvent(t){this.game.currentScene?.run(q.custom({callback:()=>{const i=new li({circleOfRadius:16,fillColor:x.LightGray,strokeColor:x.Black,lineWidth:2,alpha:.75,position:{x:t.x,y:t.y}});this.game.currentScene?.addChild(i),i.run(q.sequence([q.group([q.fadeAlpha({duration:750,alpha:0}),q.scale({duration:750,scale:0})]),q.custom({callback:()=>{this.game.currentScene?.removeChild(i)}})]))}}))}materializeBrowserImageDataReadyEvent(t){this.game.imageManager.loadImages([{imageName:t.imageName,width:t.width,height:t.height,dataUrl:t.dataUrl,svgString:t.svgString}])}materializeI18nDataReadyEvent(t){this.configureI18n(t.localizationOptions)}materializeScenePresentEvent(t){let i=We.none();if(t.transitionType===ge.Slide){if(t.direction===void 0)throw new Error("EventMaterializer: ScenePresentEvent direction is undefined for slide transition");if(t.duration===void 0)throw new Error("EventMaterializer: ScenePresentEvent duration is undefined for slide transition");if(t.easingType===void 0)throw new Error("EventMaterializer: ScenePresentEvent easingType is undefined for slide transition");const n=this.game.materializedNodes.find(c=>c.uuid===t.uuid);if(!n)throw new Error(`EventMaterializer: Scene with uuid ${t.uuid} not found`);switch(t.direction){case ye.Left:{n.position.x=n.size.width;break}case ye.Right:{n.position.x=-n.size.width;break}case ye.Up:{n.position.y=n.size.height;break}case ye.Down:{n.position.y=-n.size.height;break}}i=We.slide({direction:t.direction,duration:t.duration,easing:Re.fromTypeAsString(t.easingType)})}this.game.presentScene(t.uuid,i)}}class da{constructor(t){if(this.type=oi.Game,this.sessionUuid="",this.uuid=Ue.generate(),this.publishUuid="",this.canvasKitWasmVersion="0.39.1",this.beginTimestamp=NaN,this.beginIso8601Timestamp="",this.eventListeners=new Array,this.gameMetrics=new Array,this.stepCount=0,this.steppingNow=0,this.warmupFunctionQueue=new Array,this.warmupFinished=!1,this.plugins=[],this.staticTrialSchema={},this.eventStore=new En,this.nodeFactory=new _n,this.materializedNodes=new Array,this.data={trials:new Array},this.trialIndex=0,this.drawnFrames=0,this.lastFpsUpdate=0,this.nextFpsUpdate=0,this.fpsRate=0,this.animationFramesRequested=0,this.limitFps=!1,this.gameStopRequested=!1,this.webGlRendererInfo="",this.canvasCssWidth=0,this.canvasCssHeight=0,this.scenes=new Array,this.freeNodesScene=new Ge({name:X.FREE_NODES_SCENE_NAME,backgroundColor:[255,255,255,0]}),this.incomingSceneTransitions=new Array,this.replayEventsButtonEnabled=!0,this.automaticTrialSchema={study_id:{type:["string","null"],description:"The short human-readable text ID of the study (protocol, experiment, or other aggregate) that contains the administration of this activity."},study_uuid:{type:["string","null"],format:"uuid",description:"Unique identifier of the study (protocol, experiment, or other aggregate) that contains the administration of this activity."},document_uuid:{type:"string",format:"uuid",description:"Unique identifier for this data document."},session_uuid:{type:"string",format:"uuid",description:"Unique identifier for all activities in this administration of the session. This identifier changes each time a new session starts."},activity_uuid:{type:"string",format:"uuid",description:"Unique identifier for all trials in this administration of the activity. This identifier changes each time the activity starts."},activity_id:{type:"string",description:"Human-readable identifier of the activity."},activity_publish_uuid:{type:"string",format:"uuid",description:"Persistent unique identifier of the activity. This identifier never changes. It can be used to identify the activity across different studies and sessions."},activity_version:{type:"string",description:"Version of the activity."},device_timezone:{type:"string",description:"Timezone of the device. Calculated from Intl.DateTimeFormat().resolvedOptions().timeZone."},device_timezone_offset_minutes:{type:"integer",description:"Difference in minutes between UTC and device timezone. Calculated from Date.getTimezoneOffset()."},locale:{type:["string","null"],description:"Locale of the trial. null if the activity does not support localization."}},this.snapshots=new Array,!t.id||t.id.trim()==="")throw new Error("id is required in GameOptions");if(!Ue.isValid(t.publishUuid)){const i=t.publishUuid?`Provided publishUuid was ${t.publishUuid}. `:"";console.warn(`Missing or invalid publishUuid in GameOptions. ${i}To generate a valid UUID, visit a site such as https://www.uuidgenerator.net/version4`)}this.options=t,this.name=t.name,this.id=t.id,this.publishUuid=t.publishUuid,this.fpsMetricReportThreshold=t.fpsMetricReportThreshold??X.FPS_METRIC_REPORT_THRESHOLD,this.maximumRecordedActivityMetrics=t.maximumRecordedActivityMetrics??X.MAXIMUM_RECORDED_ACTIVITY_METRICS,this.addLocalizationParametersToGameParameters(),this.options.locale!==void 0&&this.setParameters({locale:this.options.locale}),this.options.fallbackLocale!==void 0&&this.setParameters({fallback_locale:this.options.fallbackLocale}),this.options.missingLocalizationColor&&this.setParameters({missing_localization_color:this.options.missingLocalizationColor}),this.options.translation&&this.setParameters({translation:this.options.translation}),this.options.additionalTranslation&&this.setParameters({translation:this.options.additionalTranslation}),this.options.trialSchema||(this.options.trialSchema={}),t.moduleMetadata?this.moduleMetadata=t.moduleMetadata:this.moduleMetadata={name:"",version:"",dependencies:{}},t.moduleMetadata?.name&&t.version&&console.log(`\u26AA ${t.moduleMetadata.name} version ${t.version}`)}createFreeNodesScene(){this.freeNodesScene.game=this,this.freeNodesScene.needsInitialization=!0;const t={name:X.FREE_NODES_SCENE_NAME,backgroundColor:[255,255,255,0],uuid:this.freeNodesScene.uuid},i={type:j.NodeNew,target:this.freeNodesScene,nodeType:lt.Scene,...Y.createFrameUpdateTimestamps(),nodeOptions:t,sequence:m2c2Globals.eventSequence};this.eventStore.addEvent(i)}getImportedModuleBaseUrl(t,i){const n=new RegExp(`^.*${t}[^\\/]*`),c=i.match(n);if(!c||c.length===0)throw new Error(`Could not calculate imported assessment package base URL. Package name: ${t}, module URL: ${i}`);return c[0]}addLocalizationParametersToGameParameters(){this.options.parameters={...this.options.parameters,...Ni.makeLocalizationParameters()}}async init(){return this.initialize()}loadCanvasKit(t){return ca({locateFile:()=>t})}async resolveGameBaseUrls(t){let i,n=!1,c=`assets/${t.id}`;if(t.moduleMetadata.name)try{i=await import.meta.resolve(t.moduleMetadata.name),c=t.getImportedModuleBaseUrl(t.moduleMetadata.name,i)+"/assets",n=!0}catch{}let h=`assets/${t.id}`;try{const C=await import.meta.resolve("@m2c2kit/core");h=t.getImportedModuleBaseUrl("@m2c2kit/core",C)+"/assets"}catch{if(n)throw new Error(`the package ${t.moduleMetadata.name} has been imported from a module URL (${i}), but the @m2c2kit/core package module URL could not be determined.`)}return{assets:c,canvasKitWasm:h}}async configureI18n(t){if(this.i18n=new Ni(this,t),!this.i18n)throw new Error("I18n object is undefined");await this.i18n.initialize(),this.eventStore.addEvent({type:"I18nDataReadyEvent",target:this.i18n,localizationOptions:t,...Y.createFrameUpdateTimestamps()})}async waitForErudaInitialization(t=5e3){await new Promise(i=>{let n=0;const c=setInterval(()=>{m2c2Globals.erudaInitialized===!0&&(clearInterval(c),i(void 0)),n=n+100,n>t&&(console.warn(`Could not initialize eruda within ${t} milliseconds.`),clearInterval(c),i(void 0))},100)})}async initialize(){m2c2Globals.erudaRequested===!0&&await this.waitForErudaInitialization(),this.options.recordEvents===!0&&(this.eventStore.mode=de.Record),this.createFreeNodesScene();const t=await this.resolveGameBaseUrls(this);if(this.manifest===void 0&&(this.manifest=await this.loadManifest()),this._canvasKit===void 0){const i=Y.getUrlFromManifest(this,t.canvasKitWasm+`/canvaskit-${this.canvasKitWasmVersion}.wasm`);try{this.canvasKit=await this.loadCanvasKit(i)}catch{throw new Error(`game ${this.id} could not load canvaskit wasm file from ${i}`)}}if(this.isLocalizationRequested()){const i=this.getLocalizationOptionsFromGameParameters();await this.configureI18n(i)}return this.fontManager=new Tn(this,t),this.imageManager=new lr(this,t),this.soundManager=new Wn(this,t),this.eventMaterializer=new ua({game:this,nodeFactory:this.nodeFactory,freeNodesScene:this.freeNodesScene,configureI18n:this.configureI18n.bind(this)}),Promise.all([this.fontManager.initializeFonts(this.options.fonts),this.imageManager.initializeImages(this.options.images),this.soundManager.initializeSounds(this.options.sounds)])}async loadManifest(t="__NO_M2C2KIT_MANIFEST_JSON_URL__"){if(t.includes("NO_M2C2KIT_MANIFEST_JSON_URL"))return{};let i;try{if(i=await fetch(t),!i.ok)throw new Error(`Error ${i.status} on GET manifest.json from ${t}.`)}catch{throw new Error(`Network error on GET manifest.json from ${t}.`)}try{return await i.json()}catch{throw new Error(`Error parsing manifest.json from ${t}.`)}}get fontManager(){if(!this._fontManager)throw new Error("fontManager is undefined");return this._fontManager}set fontManager(t){this._fontManager=t}get imageManager(){if(!this._imageManager)throw new Error("imageManager is undefined");return this._imageManager}set imageManager(t){this._imageManager=t}get soundManager(){if(!this._soundManager)throw new Error("soundManager is undefined");return this._soundManager}set soundManager(t){this._soundManager=t}get eventMaterializer(){if(!this._eventMaterializer)throw new Error("eventMaterializer is undefined");return this._eventMaterializer}set eventMaterializer(t){this._eventMaterializer=t}addPrefixesToKey(t){let i="";if(this.studyId&&this.studyUuid)i=this.studyId.concat(":",this.studyUuid,":");else if(this.studyId||this.studyUuid)throw new Error(`study_id and study_uuid must both be set or unset. Values are study_id: ${this.studyId}, study_uuid: ${this.studyUuid}`);return i.concat(this.id.concat(this.id,":",this.publishUuid,":",t))}storeSetItem(t,i,n=!1){const c=n?t:this.addPrefixesToKey(t);return this.dataStores[0].setItem(c,i,n?"":this.publishUuid)}storeGetItem(t,i=!1){const n=i?t:this.addPrefixesToKey(t);return this.dataStores[0].getItem(n)}storeDeleteItem(t,i=!1){const n=i?t:this.addPrefixesToKey(t);return this.dataStores[0].deleteItem(n)}storeClearItems(){return this.dataStores[0].clearItemsByActivityPublishUuid(this.publishUuid)}storeItemsKeys(t=!1){return this.dataStores[0].itemsKeysByActivityPublishUuid(t?"":this.publishUuid)}storeItemExists(t,i=!1){const n=i?t:this.addPrefixesToKey(t);return this.dataStores[0].itemExists(n)}get dataStores(){if(!this._dataStores)throw new Error("dataStores is undefined");return this._dataStores}set dataStores(t){this._dataStores=t}hasDataStores(){return this._dataStores&&this._dataStores.length>0||!1}getLocalizationOptionsFromGameParameters(){const t=this.getParameter("locale"),i=this.getParameterOrFallback("fallback_locale",void 0),n=this.getParameterOrFallback("missing_localization_color",void 0),c=this.getParameterOrFallback("translation",void 0),h=this.options.translation;return{locale:t,fallbackLocale:i,missingLocalizationColor:n,additionalTranslation:c,translation:h}}isLocalizationRequested(){const t=this.getParameterOrFallback("locale",void 0);if(t==="")throw new Error("Empty string in locale. Leave locale undefined or null to prevent localization.");return t==null&&this.options.translation?(this.setParameters({locale:this.options.translation.baseLocale}),!0):!(t==null&&this.options.translation===void 0)}setParameters(t){const{parameters:i}=this.options;Object.keys(t).forEach(n=>{if(n==="eruda"){t[n]===!0&&Y.loadEruda();return}if(n==="scripts"){const c=t[n];c&&Y.loadScriptUrls(c);return}if(!i||!(n in i))console.warn(`game ${this.options.name} does not have a parameter named ${n}. attempt to set parameter ${n} to value ${t[n]} will be ignored`);else if(this.options.parameters&&this.options.parameters[n]){const c=t[n];let h;if(this.options.parameters[n].type!==void 0&&c!==void 0)try{h=Y.convertValueToType(c,this.options.parameters[n].type)}catch(C){throw new Error("Error setting parameter "+n+": "+C.message)}else h=c;this.options.parameters[n].default=h}this.additionalParameters===void 0&&(this.additionalParameters={}),this.additionalParameters[n]=t[n]})}get canvasKit(){if(!this._canvasKit)throw new Error("canvaskit is undefined");return this._canvasKit}set canvasKit(t){this._canvasKit=t}addFreeNode(t){this.freeNodesScene.addChild(t)}addFreeEntity(t){this.addFreeNode(t)}removeFreeNode(t){if(typeof t=="string"){const i=this.freeNodesScene.children.filter(n=>n.name===t).find(Boolean);if(!i)throw new Error(`cannot remove free node named "${t}" because it is not currently part of the game's free nodes. `);this.freeNodesScene.removeChild(i)}else this.freeNodesScene.removeChild(t)}removeFreeEntity(t){this.removeFreeNode(t)}removeAllFreeNodes(){for(;this.freeNodesScene.children.length;)this.freeNodesScene.children.pop()}removeAllFreeEntities(){this.removeAllFreeNodes()}get freeNodes(){return this.freeNodesScene.children}get freeEntities(){return this.freeNodes}addScene(t){t.game=this,t.needsInitialization=!0,this.scenes.push(t),this.addNodeEvents(t)}addNodeEvents(t){this.eventStore.addEvents(t.nodeEvents),t.nodeEvents.length=0;for(const i of t.children)this.addNodeEvents(i)}addScenes(t){t.forEach(i=>{this.addScene(i)})}removeScene(t){if(typeof t=="object")if(this.scenes.includes(t))this.scenes=this.scenes.filter(i=>i!==t);else throw new Error(`cannot remove scene ${t} from game because the scene is not currently added to the game`);else if(this.scenes.map(i=>i.name).includes(t))this.scenes=this.scenes.filter(i=>i.name!==t);else throw new Error(`cannot remove scene named "${t}" from game because the scene is not currently added to the game`)}presentScene(t,i){let n;if(typeof t=="string"){if(n=this.scenes.filter(T=>T.name===t).find(Boolean),n===void 0&&(n=this.scenes.filter(T=>T.uuid===t).find(Boolean)),n===void 0)throw new Error(`scene ${t} not found`)}else{if(!this.scenes.some(T=>T===t))throw new Error(`scene ${t} exists, but it has not been added to the game object`);n=t}n.initialize(),n.needsInitialization=!1;const c=new Un(n,i??We.none());this.incomingSceneTransitions.push(c),n.game.bodyBackgroundColor!==void 0?document.body.style.backgroundColor=`rgb(${n.game.bodyBackgroundColor[0]},${n.game.bodyBackgroundColor[1]},${n.game.bodyBackgroundColor[2]},${n.game.bodyBackgroundColor[3]})`:document.body.style.backgroundColor=`rgb(${n.backgroundColor[0]},${n.backgroundColor[1]},${n.backgroundColor[2]},${n.backgroundColor[3]})`;let h;i?.type===ge.Slide&&(h=i.direction);const C={type:"ScenePresent",target:n,uuid:n.uuid,...Y.createFrameUpdateTimestamps(),transitionType:i?.type??ge.None,duration:i?.duration,direction:h,easingType:i?.easing?Re.toTypeAsString(i.easing):void 0};this.eventStore.addEvent(C)}getParameter(t){if(this.options.parameters!==void 0&&Object.keys(this.options.parameters).includes(t))return this.options.parameters[t].default;throw new Error(`game parameter ${t} not found`)}getParameterOrFallback(t,i){return this.options.parameters!==void 0&&Object.keys(this.options.parameters).includes(t)?this.options.parameters[t].default:i}hasParameter(t){return!!(this.options.parameters!==void 0&&Object.keys(this.options.parameters).includes(t))}async start(t){const i=this.options;this.setupHtmlCanvases(i.canvasId,i.width,i.height,i.stretch),this.showFps=i.showFps??!1,this.bodyBackgroundColor=i.bodyBackgroundColor,this.initData(),this.setupCanvasKitSurface(),this.setupFpsFont(),this.setupCanvasDomEventHandlers(),this.beginTimestamp=Gt.now(),this.beginIso8601Timestamp=new Date().toISOString();let n;if(t!==void 0?typeof t=="object"?n=t:n=this.scenes.filter(C=>C.name===t).find(Boolean):this.entryScene!==void 0?typeof this.entryScene=="object"?n=this.entryScene:n=this.scenes.filter(C=>C.name===this.entryScene).find(Boolean):n=this.scenes.find(Boolean),n===void 0)throw new Error("cannot start game. entry scene has not been added to the game object.");if(this.presentScene(n),this.surface===void 0)throw new Error("CanvasKit surface is undefined");this.options.timeStepping?(this.addTimeSteppingControlsToDom(),this.updateTimeSteppingOutput()):this.removeTimeSteppingControlsFromDom(),this.options.showEventStoreControls&&this.addEventControlsToDom(),this.warmupFinished=!1;const c={target:this,type:j.GameWarmupStart,...Y.createFrameUpdateTimestamps()};this.raiseActivityEventOnListeners(c),this.warmupFunctionQueue.push({warmupFunction:this.warmupShadersWithPrimitives}),this.warmupFunctionQueue.push({warmupFunction:this.warmupShadersWithPrimitives,positionOffset:.10012117}),this.warmupFunctionQueue.push({warmupFunction:this.warmupShadersWithScenes}),this.surface.requestAnimationFrame(this.loop.bind(this));const h={target:this,type:j.ActivityStart,...Y.createFrameUpdateTimestamps()};this.raiseActivityEventOnListeners(h)}playEventsHandler(t){if(t?.target?.id==="replay-events"&&(this.eventStore.mode=de.Disabled,this.scenes.forEach(i=>{this.removeScene(i)}),this.currentScene=void 0,this.eventListeners=new Array,this.freeNodesScene.removeAllChildren(),this.materializedNodes=[],this.eventStore.replay(),this.setReplayEventsButtonEnabled(!1),this.setStopReplayButtonEnabled(!0)),t?.target?.id==="stop-replay"&&(this.eventStore.clearEvents(),this.setReplayEventsButtonEnabled(!0),this.setStopReplayButtonEnabled(!1)),t?.target?.id==="log-events"){if(this.eventStore.mode===de.Replay){console.log(this.eventStore.serializedEventsBeforeReplay),console.log(`Total events: ${JSON.parse(this.eventStore.serializedEventsBeforeReplay).length}`);return}console.log(JSON.stringify(this.eventStore.getEvents())),console.log(`Total events: ${this.eventStore.getEvents().length}`)}}setReplayEventsButtonEnabled(t){const i=document.getElementById("replay-events");if(i){if(t){i.removeAttribute("disabled"),this.replayEventsButtonEnabled=!0;return}i.setAttribute("disabled","true"),this.replayEventsButtonEnabled=!1}}setStopReplayButtonEnabled(t){const i=document.getElementById("stop-replay");if(i){if(t){i.removeAttribute("disabled");return}i.setAttribute("disabled","true")}}addEventControlsToDom(){const t=document.getElementById("m2c2kit-event-controls-div");t&&t.remove();const i=document.getElementsByTagName("body")[0];if(i){const n=document.createElement("div");n.id="m2c2kit-event-controls-div",n.style.position="fixed",n.style.top="4px",n.style.left="4px",i.prepend(n);const c=document.createElement("button");c.id="replay-events",c.title="replay event recording",c.innerText="\u25B6\uFE0F",c.style.marginRight="4px",n.appendChild(c),c.addEventListener("click",this.playEventsHandler.bind(this));const h=document.createElement("button");h.id="stop-replay",h.title="stop event replay",h.innerText="\u23F9\uFE0F",h.style.marginRight="4px",h.disabled=!0,n.appendChild(h),h.addEventListener("click",this.playEventsHandler.bind(this));const C=document.createElement("button");C.id="log-events",C.title="log events to console",C.innerText="\u{1F4C4}",C.style.marginRight="4px",n.appendChild(C),C.addEventListener("click",this.playEventsHandler.bind(this));const T=document.createElement("span");T.title="optional: replay events only through a given sequence number. Default is to replay all events.",T.innerText="Replay through sequence: ",n.appendChild(T);const B=document.createElement("input");B.id="sequence-number",B.title="optional: replay events only through a given sequence number. Default is to replay all events.",B.style.marginRight="4px",n.appendChild(B)}}addTimeSteppingControlsToDom(){if(document.getElementById("m2c2kit-time-stepping-div"))return;const i=document.getElementsByTagName("body")[0];if(i){const n=document.createElement("div");n.id="m2c2kit-time-stepping-div",i.prepend(n);const c=document.createElement("button");c.id="1-step-advance",c.title="advance 1 step (16.667 ms)",c.innerText=">",c.style.marginRight="4px",n.appendChild(c),c.addEventListener("click",this.advanceStepsHandler.bind(this));const h=document.createElement("button");h.id="55-step-advance",h.title="advance 55 steps (916.667 ms)",h.innerText=">>",h.style.marginRight="4px",n.appendChild(h),h.addEventListener("click",this.advanceStepsHandler.bind(this));const C=document.createElement("input");C.id="time-stepping-steps-input",C.title="steps",C.style.width="40px",C.style.marginRight="4px",C.setAttribute("readonly","true"),n.appendChild(C);const T=document.createElement("input");T.id="time-stepping-now-input",T.title="milliseconds",T.style.width="80px",T.style.marginRight="4px",T.setAttribute("readonly","true"),n.appendChild(T)}}updateTimeSteppingOutput(){const t=document.getElementById("time-stepping-steps-input");t&&(t.value=this.stepCount.toString());const i=document.getElementById("time-stepping-now-input");i&&(i.value=this.steppingNow.toFixed(2))}advanceStepsHandler(t){t?.target?.id==="1-step-advance"?(this.steppingNow=this.steppingNow+16.66666666666667,this.stepCount=this.stepCount+1):t?.target?.id==="55-step-advance"&&(this.steppingNow=this.steppingNow+16.66666666666667*55,this.stepCount=this.stepCount+55),this.updateTimeSteppingOutput()}removeTimeSteppingControlsFromDom(){const t=document.getElementById("m2c2kit-time-stepping-div");t&&t.remove()}warmupShadersWithPrimitives(t,i=0){if(t.save(),i==0?t.scale(1/m2c2Globals.canvasScale,1/m2c2Globals.canvasScale):t.scale(1/m2c2Globals.canvasScale*1.13,1/m2c2Globals.canvasScale*1.13),!this.surface)throw new Error("surface is undefined");const n=this.surface.width(),c=this.surface.height(),h=Math.round(n/2)+i,C=Math.round(c/2)+i,T=i,B=i,$=xt.makePaint(this.canvasKit,x.White,this.canvasKit.PaintStyle.Fill,!0);t.drawRect([0,0,this.surface.width(),this.surface.height()],$);const it=xt.makePaint(this.canvasKit,x.Black,this.canvasKit.PaintStyle.Fill,!1),ct=xt.makePaint(this.canvasKit,x.Black,this.canvasKit.PaintStyle.Fill,!0),ut=xt.makePaint(this.canvasKit,x.Black,this.canvasKit.PaintStyle.Stroke,!1);ut.setStrokeWidth(2);const bt=xt.makePaint(this.canvasKit,x.Black,this.canvasKit.PaintStyle.Stroke,!0);bt.setStrokeWidth(2),t.drawCircle(h,C,32,it),t.drawCircle(h,C,32,ct),t.drawCircle(h,C,32,ut),t.drawCircle(h,C,32,bt);const wt=this.fontManager,Ht=this.fontManager.getFontNames();if(Ht.length>0&&wt.fonts[Ht[0]].status===Zt.Ready){const pe=wt.getTypeface(Ht[0]),ve=new this.canvasKit.Font(pe,16*m2c2Globals.canvasScale);t.drawText("abc",h,C,it,ve),t.drawText("abc",h,C,ct,ve)}const fe=this.takeCurrentSceneSnapshot();t.drawImage(fe,T,B),fe.delete(),t.drawRect([T,B,16,16],it),t.drawRect([T,B,16,16],ct),t.drawRect([T,B,16,16],ut),t.drawRect([T,B,16,16],bt),t.restore()}warmupShadersWithScenes(t){[...this.scenes,this.freeNodesScene].forEach(h=>{h.warmup(t)});const i=this.nodes.filter(h=>h.type===lt.Sprite).map(h=>h.imageName),n=this.imageManager.images;n&&Object.keys(n).filter(C=>C!=="__outgoingSceneSnapshot").forEach(C=>{if(!i.includes(C)&&n[C].status===Qt.Ready){const T=n[C].canvaskitImage;if(!T)throw new Error(`image ${C} is undefined`);t.drawImage(T,0,0)}});const c=new this.canvasKit.Paint;if(c.setColor(this.canvasKit.Color(255,255,255,1)),!this.surface)throw new Error("surface is undefined");t.drawRect([0,0,this.surface.width(),this.surface.height()],c)}stop(){this.currentScene&&(this.currentScene._active=!1),this.gameStopRequested=!0,Gt.removeAll(),this.dispose()}dispose(){this.nodes.filter(t=>t.isDrawable).forEach(t=>t.dispose()),this.fontManager.dispose()}initData(){this.trialIndex=0,this.data={trials:new Array};const t=this.options.trialSchema??{},i=Object.entries(t);for(const[n,c]of i)if(c.type!==void 0&&!this.propertySchemaDataTypeIsValid(c.type))throw new Error(`invalid schema. variable ${n} is type ${c.type}. type must be number, string, boolean, object, or array`)}propertySchemaDataTypeIsValid(t){const i=["string","number","integer","object","array","boolean","null"];if(typeof t=="string")return i.includes(t);let n=!0;if(Array.isArray(t))t.forEach(c=>{i.includes(c)||(n=!1)});else throw new Error(`Invalid data type: ${t}`);return n}getDeviceMetadata(){const t=window.screen;return t.orientation?{userAgent:navigator.userAgent,devicePixelRatio:window.devicePixelRatio,screen:{availHeight:t.availHeight,availWidth:t.availWidth,colorDepth:t.colorDepth,height:t.height,orientation:{type:t.orientation.type,angle:t.orientation.angle},pixelDepth:t.pixelDepth,width:t.width},webGlRenderer:this.webGlRendererInfo}:{userAgent:navigator.userAgent,devicePixelRatio:window.devicePixelRatio,screen:{availHeight:t.availHeight,availWidth:t.availWidth,colorDepth:t.colorDepth,height:t.height,pixelDepth:t.pixelDepth,width:t.width},webGlRenderer:this.webGlRendererInfo}}addTrialData(t,i){if(!this.options.trialSchema)throw new Error("no trial schema were provided in GameOptions. cannot add trial data");if(this.data.trials.length<this.trialIndex+1){const h={},C=Object.entries(this.options.trialSchema);for(const[T]of C)h[T]=null;this.data.trials.push({document_uuid:Ue.generate(),study_id:this.studyId??null,study_uuid:this.studyUuid??null,session_uuid:this.sessionUuid,activity_uuid:this.uuid,activity_id:this.options.id,activity_publish_uuid:this.options.publishUuid,activity_version:this.options.version,device_timezone:Intl?.DateTimeFormat()?.resolvedOptions()?.timeZone??"",device_timezone_offset_minutes:new Date().getTimezoneOffset(),locale:this.i18n?.locale??null,...h,device_metadata:this.getDeviceMetadata()})}if(!(t in this.options.trialSchema))throw new Error(`trial variable ${t} not defined in schema`);let n;Array.isArray(this.options.trialSchema[t].type)?n=this.options.trialSchema[t].type:n=[this.options.trialSchema[t].type];let c=typeof i;if(c==="object"&&Object.prototype.toString.call(i)==="[object Array]"&&(c="array"),i==null&&(c="null"),!n.includes(c)&&!(c==="number"&&Number.isInteger(i)&&n.includes("integer")))throw new Error(`type for variable ${t} (value: ${i}) is "${c}". Based on schema for this variable, expected type was "${n}"`);this.data.trials[this.trialIndex][t]=i}addTrialSchema(t){Object.keys(t).forEach(n=>{if(!this.options.trialSchema)throw new Error("trial schema is undefined");this.options.trialSchema[n]=t[n]})}addStaticTrialData(t,i){if(!this.options.trialSchema)throw new Error("trial schema is undefined");if(this.options.trialSchema[t]===void 0)throw new Error(`trial variable ${t} not defined in schema`);this.staticTrialSchema[t]=i}trialComplete(){this.data.trials[this.trialIndex]?.locale&&(this.data.trials[this.trialIndex].locale=this.i18n?.locale??null),this.data.trials[this.trialIndex]?.device_metadata&&(this.data.trials[this.trialIndex].device_metadata=this.getDeviceMetadata()),Object.keys(this.staticTrialSchema).length>0&&(this.data.trials[this.trialIndex]={...this.data.trials[this.trialIndex],...this.staticTrialSchema}),this.trialIndex++;const t={type:j.ActivityData,...Y.createFrameUpdateTimestamps(),target:this,newData:this.data.trials[this.trialIndex-1],newDataSchema:this.makeNewGameDataSchema(),data:this.data,dataSchema:this.makeGameDataSchema(),dataType:"Trial",activityConfiguration:this.makeGameActivityConfiguration(this.options.parameters??{}),activityConfigurationSchema:this.makeGameActivityConfigurationSchema(this.options.parameters??{}),activityMetrics:this.gameMetrics};this.raiseActivityEventOnListeners(t)}makeNewGameDataSchema(){return{description:`A single trial and metadata from the assessment ${this.name}.`,$comment:`Activity identifier: ${this.options.id}, version: ${this.options.version}.`,$schema:"https://json-schema.org/draft/2019-09/schema",type:"object",properties:{...this.automaticTrialSchema,...this.options.trialSchema,device_metadata:$n}}}makeGameDataSchema(){return{description:`All trials and metadata from the assessment ${this.name}.`,$comment:`Activity identifier: ${this.options.id}, version: ${this.options.version}.`,$schema:"https://json-schema.org/draft/2019-09/schema",type:"object",required:["trials"],properties:{trials:{type:"array",items:{$ref:"#/$defs/trial"},description:"All trials from the assessment."}},$defs:{trial:{type:"object",properties:{...this.automaticTrialSchema,...this.options.trialSchema,device_metadata:$n}}}}}makeGameActivityConfiguration(t){const i=JSON.parse(JSON.stringify(t)),{locale:n,fallback_locale:c,missing_localization_color:h,translation:C,...T}=i;for(const B in T)for(const $ in T[B])$=="default"&&(T[B]=T[B][$]);return T}makeGameActivityConfigurationSchema(t){const i=JSON.parse(JSON.stringify(t)),{locale:n,fallback_locale:c,missing_localization_color:h,translation:C,...T}=i;for(const B in T){if(!("type"in T[B])&&"value"in T[B]){const $=typeof T[B].default;$!=="bigint"&&$!=="function"&&$!=="symbol"&&$!=="undefined"&&(T[B].type=$)}for(const $ in T[B])$=="default"&&delete T[B][$]}return{description:`activity configuration from the assessment ${this.name}`,type:"object",properties:T}}end(){const t={target:this,type:j.ActivityEnd,...Y.createFrameUpdateTimestamps()},i={data:this.data,dataSchema:this.makeGameDataSchema(),dataType:"Trial",activityConfiguration:this.makeGameActivityConfiguration(this.options.parameters??{}),activityConfigurationSchema:this.makeGameActivityConfigurationSchema(this.options.parameters??{}),activityMetrics:this.gameMetrics};this.raiseActivityEventOnListeners(t,i)}cancel(){const t={target:this,type:j.ActivityCancel,...Y.createFrameUpdateTimestamps()},i={data:this.data,dataSchema:this.makeGameDataSchema(),dataType:"Trial",activityConfiguration:this.makeGameActivityConfiguration(this.options.parameters??{}),activityConfigurationSchema:this.makeGameActivityConfigurationSchema(this.options.parameters??{}),activityMetrics:this.gameMetrics};this.raiseActivityEventOnListeners(t,i)}setupHtmlCanvases(t,i,n,c){m2c2Globals.canvasScale=Math.round(window.devicePixelRatio*100)/100;let h;if(t===void 0){const C=document.getElementsByTagName("canvas");let T=new Array;for(let $=0;$<C.length;$++)T.push(C[$]);if(T=T.filter($=>!$.id.startsWith("m2c2kit-scratch-canvas")),T.length===0)throw new Error("no html canvas tag was found in the html");const B=T.filter($=>$.id==="m2c2kit-canvas")[0];B?(h=B,T.length>1&&console.log("using canvas with id 'm2c2kit-canvas'")):(h=C[0],T.length>1&&console.log("using first canvas"))}else if(h=document.getElementById(t),h===void 0)throw new Error(`could not find canvas HTML element with id "${t}"`);if(c||window.innerWidth<i||window.innerHeight<n){const C=n/i;window.innerHeight/window.innerWidth<C?m2c2Globals.rootScale=window.innerHeight/n:m2c2Globals.rootScale=window.innerWidth/i}h.style.width=m2c2Globals.rootScale*i+"px",h.style.height=m2c2Globals.rootScale*n+"px",h.width=m2c2Globals.rootScale*i*m2c2Globals.canvasScale,h.height=m2c2Globals.rootScale*n*m2c2Globals.canvasScale,this.htmlCanvas=h,this.canvasCssWidth=i,this.canvasCssHeight=n,m2c2Globals.canvasCssWidth=i,m2c2Globals.canvasCssHeight=n}setupCanvasKitSurface(){if(this.htmlCanvas===void 0)throw new Error("main html canvas is undefined");window.logWebGl=this.options.logWebGl,this.interceptWebGlCalls();try{this.webGlRendererInfo=mr.getRendererString()}catch{this.webGlRendererInfo="err",mr.dispose()}const t=this.canvasKit.MakeWebGLCanvasSurface(this.htmlCanvas);if(t===null)throw new Error("could not make CanvasKit surface from canvas HTML element");this.surface=t,console.log(`\u26AA CanvasKit surface is backed by ${this.surface.reportBackendTypeIsGPU()?"GPU":"CPU"}`),this.surface.getCanvas().scale(m2c2Globals.canvasScale,m2c2Globals.canvasScale)}interceptWebGlCalls(){if(!this.htmlCanvas.__proto__.m2c2ModifiedGetContext){this.htmlCanvas.__proto__.m2c2ModifiedGetContext=!0;const t=this.htmlCanvas.__proto__.getContext;this.htmlCanvas.__proto__.getContext=function(...i){window.logWebGl&&console.log(`\u{1F53C} getContext(${i.map(c=>c.toString()).join(", ")})`);const n=t.apply(this,[...i]);if(n.__proto__.compileShader&&!n.__proto__.m2c2ModifiedCompileShader){n.__proto__.m2c2ModifiedCompileShader=!0;const c=n.__proto__.compileShader;n.__proto__.compileShader=function(...h){if(window.logWebGl){const C=h[0],T=n.getShaderSource(C);console.log("\u{1F53C} compileShader():"),console.log(T)}return c.apply(this,[...h])}}return n}}}setupFpsFont(){this.fpsTextFont=new this.canvasKit.Font(null,X.FPS_DISPLAY_TEXT_FONT_SIZE*m2c2Globals.canvasScale),this.fpsTextPaint=new this.canvasKit.Paint,this.fpsTextPaint.setColor(this.canvasKit.Color(X.FPS_DISPLAY_TEXT_COLOR[0],X.FPS_DISPLAY_TEXT_COLOR[1],X.FPS_DISPLAY_TEXT_COLOR[2],X.FPS_DISPLAY_TEXT_COLOR[3])),this.fpsTextPaint.setAntiAlias(!0)}setupCanvasDomEventHandlers(){if(this.htmlCanvas===void 0)throw new Error("main html canvas is undefined");this.htmlCanvas.addEventListener("pointerdown",this.htmlCanvasPointerDownHandler.bind(this)),this.htmlCanvas.addEventListener("pointerup",this.htmlCanvasPointerUpHandler.bind(this)),this.htmlCanvas.addEventListener("pointermove",this.htmlCanvasPointerMoveHandler.bind(this)),this.htmlCanvas.addEventListener("touchstart",t=>{t.preventDefault()}),this.htmlCanvas.addEventListener("pointerleave",this.htmlCanvasPointerLeaveHandler.bind(this))}loop(t){if(!this.surface)throw new Error("surface is undefined");if(this.warmupFunctionQueue.length>0){const i=this.warmupFunctionQueue.shift();i?.warmupFunction.call(this,t,i.positionOffset),this.surface.requestAnimationFrame(this.loop.bind(this));return}if(!this.warmupFinished){this.warmupFinished=!0;const i={target:this,type:j.GameWarmupEnd,...Y.createFrameUpdateTimestamps()};this.raiseActivityEventOnListeners(i),this.surface.requestAnimationFrame(this.loop.bind(this));return}if(this.soundManager.hasSoundsToDecode()&&navigator.userActivation.hasBeenActive&&this.soundManager.decodeFetchedSounds(),this.gameStopRequested){this.surface.deleteLater();return}if(this.animationFramesRequested++,!this.limitFps||this.animationFramesRequested%Math.round(60/X.LIMITED_FPS_RATE)===0){if(this.currentScene===void 0&&this.incomingSceneTransitions.length===0&&this.eventStore.mode!==de.Replay)throw new Error("Can not run game without a current or incoming scene");if(this.updateGameTime(),this.eventStore.mode===de.Replay){const i=this.eventStore.dequeueEvents(Gt.now());this.eventMaterializer.materialize(i),this.eventStore.eventQueueLength===0&&!this.replayEventsButtonEnabled&&(this.setReplayEventsButtonEnabled(!0),this.setStopReplayButtonEnabled(!1))}for(this.handleIncomingSceneTransitions(this.incomingSceneTransitions),this.update(),this.draw(t);this.snapshots.length>0;)this.snapshots.shift()?.delete();this.snapshots.push(this.takeCurrentSceneSnapshot()),this.freeNodesScene.draw(t),this.pendingScreenshot&&(this.handlePendingScreenshot(this.pendingScreenshot),this.pendingScreenshot=void 0)}this.priorUpdateTime=m2c2Globals.now,this.surface.requestAnimationFrame(this.loop.bind(this))}updateGameTime(){this.options.timeStepping?m2c2Globals.now=this.steppingNow:m2c2Globals.now=performance.now(),this.priorUpdateTime?m2c2Globals.deltaTime=m2c2Globals.now-this.priorUpdateTime:m2c2Globals.deltaTime=0}handleIncomingSceneTransitions(t){if(t.length!==0&&(this.snapshots.length>0||t[0].transition.type===ge.None)){const i=t.shift();if(i===void 0)throw new Error("no incoming scene transition");const n=i.scene,c=i.transition;if(c.type===ge.None){this.currentScene&&(this.currentScene._active=!1),this.currentScene=n,this.currentScene._active=!0,this.raiseSceneEvent(n,"SceneSetup"),this.raiseSceneEvent(n,"SceneAppear");return}if(this.currentSceneSnapshot=this.snapshots.shift(),!this.currentSceneSnapshot)throw new Error("No snapshot available for outgoing scene");const h=this.createOutgoingScene(this.currentSceneSnapshot);h._active=!0,this.currentScene&&(this.currentScene._active=!1),this.currentScene=n,this.currentScene._active=!0,this.raiseSceneEvent(n,"SceneSetup"),this.animateSceneTransition(n,c,h)}}createOutgoingScene(t){const i=new Ge({name:X.OUTGOING_SCENE_NAME});i.size.width=this.canvasCssWidth,i.size.height=this.canvasCssHeight,this.addScene(i);const n={imageName:X.OUTGOING_SCENE_IMAGE_NAME,canvaskitImage:t,width:this.canvasCssWidth,height:this.canvasCssHeight,status:Qt.Ready,localize:!1,isFallback:!1};this.imageManager.addImage(n);const c=new hi({name:X.OUTGOING_SCENE_SPRITE_NAME,imageName:X.OUTGOING_SCENE_IMAGE_NAME,position:{x:this.canvasCssWidth/m2c2Globals.rootScale/2,y:this.canvasCssHeight/m2c2Globals.rootScale/2}});return c.scale=1/m2c2Globals.rootScale,i.addChild(c),i}async registerPlugin(t){if(t.type!==oi.Game)throw new Error(`registerPlugin(): plugin ${t.id} is not a game plugin. It is a ${t.type} plugin.`);if(this.plugins.includes(t)||this.plugins.map(i=>i.id).includes(t.id))throw new Error(`registerPlugin(): plugin ${t.id} already registered.`);this.plugins.push(t),t.initialize&&await t.initialize(this)}update(){this.executeBeforeUpdatePlugins(),this.updateScenes(),this.executeAfterUpdatePlugins()}updateScenes(){this.scenes.filter(t=>t._active).forEach(t=>t.update()),this.freeNodesScene.update()}executeBeforeUpdatePlugins(){this.plugins.filter(t=>typeof t.beforeUpdate=="function"&&t.disabled!==!0).forEach(t=>{t.beforeUpdate&&t.beforeUpdate(this,m2c2Globals.deltaTime)})}executeAfterUpdatePlugins(){this.plugins.filter(t=>typeof t.afterUpdate=="function"&&t.disabled!==!0).forEach(t=>{t.afterUpdate&&t.afterUpdate(this,m2c2Globals.deltaTime)})}draw(t){this.scenes.filter(i=>i._active).forEach(i=>i.draw(t)),this.drawnFrames++,this.calculateFps(),this.showFps&&this.drawFps(t)}calculateFps(){this.lastFpsUpdate===0?(this.lastFpsUpdate=m2c2Globals.now,this.nextFpsUpdate=m2c2Globals.now+X.FPS_DISPLAY_UPDATE_INTERVAL):m2c2Globals.now>=this.nextFpsUpdate&&(this.fpsRate=this.drawnFrames/((m2c2Globals.now-this.lastFpsUpdate)/1e3),this.drawnFrames=0,this.lastFpsUpdate=m2c2Globals.now,this.nextFpsUpdate=m2c2Globals.now+X.FPS_DISPLAY_UPDATE_INTERVAL,this.gameMetrics.length<this.maximumRecordedActivityMetrics&&this.fpsRate<this.fpsMetricReportThreshold&&this.gameMetrics.push({fps:Number.parseFloat(this.fpsRate.toFixed(2)),fps_interval_ms:X.FPS_DISPLAY_UPDATE_INTERVAL,fps_report_threshold:this.fpsMetricReportThreshold,activity_type:oi.Game,activity_uuid:this.uuid,iso8601_timestamp:new Date().toISOString()}))}takeCurrentSceneSnapshot(){if(this.surface===void 0)throw new Error("CanvasKit surface is undefined");return this.surface.makeImageSnapshot()}handlePendingScreenshot(t){if(!this.surface)throw new Error("no surface");let i;if(t.rect.length==4){const c=t.rect[0]*m2c2Globals.canvasScale,h=t.rect[1]*m2c2Globals.canvasScale,C=t.rect[2]*m2c2Globals.canvasScale,T=t.rect[3]*m2c2Globals.canvasScale,B=[c,h,c+C,h+T];i=this.surface.makeImageSnapshot(B)}else i=this.surface.makeImageSnapshot();const n=i.encodeToBytes();t.promiseResolve(n)}takeScreenshot(t,i,n,c){if(!this.surface)throw new Error("no canvaskit surface. unable to take screenshot.");const h=[t,i,n,c].map(C=>C?0:1).reduce((C,T)=>C+T);return new Promise((C,T)=>{switch(h){case 0:{if(!t||!i||!n||!c){T("missing values in arguments for takeScreenshot()");return}this.pendingScreenshot={rect:[t,i,n,c],promiseResolve:C};break}case 4:{this.pendingScreenshot={rect:[],promiseResolve:C};break}default:T("Exactly 0 or 4 arguments must be supplied to takeScreenshot()")}})}animateSceneTransition(t,i,n){const c=i.duration;switch(t._transitioning=!0,n._transitioning=!0,i.type){case ge.Slide:{switch(i.direction){case ye.Left:t.position.x=t.size.width,t.run(q.sequence([q.move({point:{x:0,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{t._transitioning=!1,this.raiseSceneEvent(t,"SceneAppear"),this.removeScene(X.OUTGOING_SCENE_NAME)},runDuringTransition:!0})])),n.run(q.sequence([q.move({point:{x:-n.size.width,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{n._active=!1,n._transitioning=!1,this.currentSceneSnapshot&&this.currentSceneSnapshot.delete()},runDuringTransition:!0})]));break;case ye.Right:t.position.x=-t.size.width,t.run(q.sequence([q.move({point:{x:0,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{t._transitioning=!1,this.raiseSceneEvent(t,"SceneAppear"),this.removeScene(X.OUTGOING_SCENE_NAME)},runDuringTransition:!0})])),n.run(q.sequence([q.move({point:{x:n.size.width,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{n._active=!1,n._transitioning=!1,this.currentSceneSnapshot&&this.currentSceneSnapshot.delete()},runDuringTransition:!0})]));break;case ye.Up:t.position.y=t.size.height,t.run(q.sequence([q.move({point:{x:0,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{t._transitioning=!1,this.raiseSceneEvent(t,"SceneAppear"),this.removeScene(X.OUTGOING_SCENE_NAME)},runDuringTransition:!0})])),n.run(q.sequence([q.move({point:{x:0,y:-n.size.height},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{n._active=!1,n._transitioning=!1,this.currentSceneSnapshot&&this.currentSceneSnapshot.delete()},runDuringTransition:!0})]));break;case ye.Down:t.position.y=-t.size.height,t.run(q.sequence([q.move({point:{x:0,y:0},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{t._transitioning=!1,this.raiseSceneEvent(t,"SceneAppear"),this.removeScene(X.OUTGOING_SCENE_NAME)},runDuringTransition:!0})])),n.run(q.sequence([q.move({point:{x:0,y:n.size.height},duration:c,easing:i.easing,runDuringTransition:!0}),q.custom({callback:()=>{n._active=!1,n._transitioning=!1,this.currentSceneSnapshot&&this.currentSceneSnapshot.delete()},runDuringTransition:!0})]));break;default:throw new Error("unknown transition direction")}break}default:throw new Error("unknown transition type")}}drawFps(t){t.save();const i=m2c2Globals.canvasScale;if(t.scale(1/i,1/i),!this.fpsTextFont||!this.fpsTextPaint)throw new Error("fps font or paint is undefined");t.drawText("FPS: "+this.fpsRate.toFixed(2),0,0+X.FPS_DISPLAY_TEXT_FONT_SIZE*i,this.fpsTextPaint,this.fpsTextFont),t.restore()}createEventListener(t,i,n,c){const h=this.nodes.filter(T=>T.name===i);h.length>1&&console.warn(`warning: createEventListener() found more than one node with name ${i}. Event listener will be attached to first node found. All nodes that receive tap events should be uniquely named`);const C=h.filter(T=>T.name===i).find(Boolean);if(C===void 0)throw new Error(`could not create event listener. node with name ${i} could not be found in the game node tree`);if(!Object.values(j).includes(t))throw new Error(`game ${this.id}: could not create event listener. event type ${t} is not known`);C.addEventListener(t,n,c)}get nodes(){function t(n,c){c.push(n),n.children.forEach(h=>t(h,c))}const i=new Array;return[...this.scenes,this.freeNodesScene].forEach(n=>t(n,i)),i}get entities(){return this.nodes}htmlCanvasPointerDownHandler(t){t.preventDefault();const i=this.currentScene;if(!i||!this.sceneCanReceiveUserInteraction(i))return;if(!this.htmlCanvas)throw new Error("main html canvas is undefined");const n={type:"DomPointerDown",target:this.htmlCanvas,x:t.offsetX/m2c2Globals.rootScale,y:t.offsetY/m2c2Globals.rootScale,...Y.createTimestamps()};this.eventStore.addEvent(n);const c={target:i,type:j.PointerDown,handled:!1,...Y.createTimestamps()};this.processDomPointerDown(this.freeNodesScene,c,t),this.processDomPointerDown(i,c,t)}htmlCanvasPointerUpHandler(t){t.preventDefault();const i=this.currentScene;if(!i||!this.sceneCanReceiveUserInteraction(i))return;const n={target:i,type:j.PointerUp,handled:!1,...Y.createTimestamps()};this.processDomPointerUp(this.freeNodesScene,n,t),this.processDomPointerUp(i,n,t)}htmlCanvasPointerMoveHandler(t){t.preventDefault();const i=this.currentScene;if(!i||!this.sceneCanReceiveUserInteraction(i))return;const n={target:i,type:j.PointerMove,handled:!1,...Y.createTimestamps()};this.processDomPointerMove(this.freeNodesScene,n,t),this.processDomPointerMove(i,n,t)}htmlCanvasPointerLeaveHandler(t){if(!this.currentScene)return;t.preventDefault();const i=this.currentScene;if(!i||!this.sceneCanReceiveUserInteraction(i))return;const n={target:i,type:j.PointerLeave,handled:!1,...Y.createTimestamps()};this.processDomPointerLeave(this.freeNodesScene,n,t),this.processDomPointerLeave(i,n,t)}processDomPointerDown(t,i,n){i.handled||(t.isUserInteractionEnabled&&this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.pressed=!0,t.pressedAndWithinHitArea=!0,t.pressedInitialPointerOffset={x:n.offsetX,y:n.offsetY},this.raiseM2PointerDownEvent(t,i,n),this.raiseTapDownEvent(t,i,n)),t.children&&t.children.filter(c=>!c.hidden).filter(c=>c.isDrawable).sort((c,h)=>h.zPosition-c.zPosition).forEach(c=>this.processDomPointerDown(c,i,n)))}processDomPointerUp(t,i,n){if(!i.handled){if(t.dragging){t.dragging=!1,t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseM2DragEndEvent(t,i,n),i.handled=!0;return}t.isUserInteractionEnabled&&t.pressed&&t.pressedAndWithinHitArea?(t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseTapUpEvent(t,i,n),this.raiseTapUpAny(t,i,n),this.raiseM2PointerUpEvent(t,i,n)):t.isUserInteractionEnabled&&t.pressed&&t.pressedAndWithinHitArea==!1?(t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseTapUpAny(t,i,n)):t.isUserInteractionEnabled&&this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseM2PointerUpEvent(t,i,n)),t.children&&t.children.filter(c=>!c.hidden).filter(c=>c.isDrawable).sort((c,h)=>h.zPosition-c.zPosition).forEach(c=>this.processDomPointerUp(c,i,n))}}processDomPointerMove(t,i,n){if(!i.handled){if(t.isUserInteractionEnabled&&t.draggable&&t.pressed){let c=!1,h,C;t.dragging===!1?(t.dragging=!0,c=!0,h=n.offsetX-t.pressedInitialPointerOffset.x,C=n.offsetY-t.pressedInitialPointerOffset.y):(h=n.offsetX-t.draggingLastPointerOffset.x,C=n.offsetY-t.draggingLastPointerOffset.y),t.position.x+=h,t.position.y+=C,t.draggingLastPointerOffset={x:n.offsetX,y:n.offsetY},i.handled=!0,c?this.raiseM2DragStartEvent(t,i,n):this.raiseM2DragEvent(t,i,n);return}t.isUserInteractionEnabled&&t.pressed&&t.pressedAndWithinHitArea&&!this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.pressedAndWithinHitArea=!1,this.raiseTapLeaveEvent(t,i,n)),t.isUserInteractionEnabled&&this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(this.raiseM2PointerMoveEvent(t,i,n),t.withinHitArea=!0),t.isUserInteractionEnabled&&t.withinHitArea&&!this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.withinHitArea=!1,this.raiseM2PointerLeaveEvent(t,i,n)),t.children&&t.children.filter(c=>!c.hidden).filter(c=>c.isDrawable).sort((c,h)=>h.zPosition-c.zPosition).forEach(c=>this.processDomPointerMove(c,i,n))}}processDomPointerLeave(t,i,n){if(!i.handled){if(t.dragging){const c={target:t,type:j.DragEnd,handled:!1,...Y.createTimestamps()};t.dragging=!1,t.pressed=!1,t.pressedAndWithinHitArea=!1,this.raiseM2DragEndEvent(t,c,n);return}t.isUserInteractionEnabled&&t.pressed&&t.pressedAndWithinHitArea&&!this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.pressedAndWithinHitArea=!1,this.raiseTapLeaveEvent(t,i,n)),t.isUserInteractionEnabled&&t.withinHitArea&&!this.IsCanvasPointWithinNodeBounds(t,n.offsetX,n.offsetY)&&(t.withinHitArea=!1,this.raiseM2PointerLeaveEvent(t,i,n)),t.children&&t.children.filter(c=>!c.hidden).filter(c=>c.isDrawable).sort((c,h)=>h.zPosition-c.zPosition).forEach(c=>this.processDomPointerLeave(c,i,n))}}raiseM2PointerDownEvent(t,i,n){i.target=t,i.type=j.PointerDown,this.raiseEventOnListeningNodes(t,i,n)}raiseTapDownEvent(t,i,n){i.target=t,i.type=j.TapDown,this.raiseEventOnListeningNodes(t,i,n)}raiseTapLeaveEvent(t,i,n){i.target=t,i.type=j.TapLeave,this.raiseEventOnListeningNodes(t,i,n)}raiseM2PointerUpEvent(t,i,n){i.target=t,i.type=j.PointerUp,this.raiseEventOnListeningNodes(t,i,n)}raiseTapUpEvent(t,i,n){i.target=t,i.type=j.TapUp,this.raiseEventOnListeningNodes(t,i,n)}raiseTapUpAny(t,i,n){i.target=t,i.type=j.TapUpAny,this.raiseEventOnListeningNodes(t,i,n)}raiseM2PointerMoveEvent(t,i,n){i.target=t,i.type=j.PointerMove,this.raiseEventOnListeningNodes(t,i,n)}raiseM2PointerLeaveEvent(t,i,n){i.target=t,i.type=j.PointerLeave,this.raiseEventOnListeningNodes(t,i,n)}raiseM2DragStartEvent(t,i,n){i.target=t,i.type=j.DragStart,this.raiseEventOnListeningNodes(t,i,n)}raiseM2DragEvent(t,i,n){i.target=t,i.type=j.Drag,this.raiseEventOnListeningNodes(t,i,n)}raiseM2DragEndEvent(t,i,n){i.target=t,i.type=j.DragEnd,this.raiseEventOnListeningNodes(t,i,n)}raiseSceneEvent(t,i){const n={target:t,type:i,...Y.createFrameUpdateTimestamps()};t.eventListeners.filter(c=>c.type===i).forEach(c=>c.callback(n))}calculatePointWithinNodeFromDomPointerEvent(t,i){let n=t.size.width,c=t.size.height;if(t.type===lt.Shape&&t.shapeType===Wt.Circle){const it=t.circleOfRadius;if(!it)throw"circleOfRadius is undefined";n=it*2,c=it*2}let h=i.offsetX,C=i.offsetY;const T=Y.calculateNodeAbsoluteBoundingBox(t);Y.nodeOrAncestorHasBeenRotated(t)&&Y.calculateRotationTransforms(t).forEach(ct=>{const ut=Y.rotatePoint({x:h,y:C},-ct.radians,ct.center);h=ut.x,C=ut.y});const B=(h-T.xMin)/(T.xMax-T.xMin)*n,$=(C-T.yMin)/(T.yMax-T.yMin)*c;return{x:B,y:$}}onStart(t,i){this.addEventListener(j.ActivityStart,t,i)}onCancel(t,i){this.addEventListener(j.ActivityCancel,t,i)}onEnd(t,i){this.addEventListener(j.ActivityEnd,t,i)}onData(t,i){this.addEventListener(j.ActivityData,t,i)}onWarmupStart(t,i){this.addEventListener(j.GameWarmupStart,t,i)}onWarmupEnd(t,i){this.addEventListener(j.GameWarmupEnd,t,i)}addEventListener(t,i,n){const c={type:t,activityUuid:this.uuid,callback:i};n?.replaceExisting&&(this.eventListeners=this.eventListeners.filter(h=>!(h.activityUuid===c.activityUuid&&h.type===c.type))),this.eventListeners.push(c)}raiseActivityEventOnListeners(t,i){i&&(t={...t,...i}),this.eventListeners.filter(n=>n.type===t.type).forEach(n=>{n.callback(t)})}raiseEventOnListeningNodes(t,i,n){t.eventListeners.filter(c=>c.type===i.type).forEach(c=>{if(c.nodeUuid===t.uuid){switch(i.target=t,i.type){case j.PointerDown:case j.PointerMove:case j.PointerUp:case j.PointerLeave:i.point=this.calculatePointWithinNodeFromDomPointerEvent(t,n),i.buttons=n.buttons,c.callback(i);break;case j.TapDown:case j.TapUp:case j.TapUpAny:case j.TapLeave:i.point=this.calculatePointWithinNodeFromDomPointerEvent(t,n),i.buttons=n.buttons,c.callback(i);break;case j.DragStart:case j.Drag:case j.DragEnd:i.position={x:t.position.x,y:t.position.y},i.buttons=n.buttons,c.callback(i);break}t.suppressEvents||this.eventStore.addEvent(i)}})}sceneCanReceiveUserInteraction(t){return!!(t._active&&t._transitioning===!1)}IsCanvasPointWithinNodeBounds(t,i,n){if(!t.isDrawable)throw"only drawable nodes can receive pointer events";if(t.type===lt.Shape&&t.shapeType===Wt.Circle){const h=Y.calculateNodeAbsoluteBoundingBox(t),C=t.circleOfRadius;if(!C)throw"circleOfRadius is undefined";const T={x:h.xMin+C*t.absoluteScale,y:h.yMin+C*t.absoluteScale};return Math.sqrt(Math.pow(i-T.x,2)+Math.pow(n-T.y,2))<=C*t.absoluteScale}if(t.size.width===0||t.size.height===0||t.type===lt.TextLine&&isNaN(t.size.width))return!1;const c=Y.calculateRotatedPoints(t);return t.isUserInteractionEnabled&&Y.isPointInsideRectangle({x:i,y:n},c)}}function fa(){globalThis.m2c2Globals={now:performance.now(),iso8601Now:"",deltaTime:NaN,canvasScale:NaN,rootScale:1,canvasCssWidth:NaN,canvasCssHeight:NaN,m2NodeClassRegistry:{},__sequence:0,get eventSequence(){return m2c2Globals.__sequence++,m2c2Globals.__sequence-1},addedScriptUrls:[]}}fa();const Gn=class Hn{constructor(t){this.startTime=NaN,this.stopTime=NaN,this.stopped=!0,this.cumulativeElapsed=NaN,this.name=t}static now(){return window.performance.now()}static start(t){let i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)i=new Hn(t),i.cumulativeElapsed=0,this._timers.push(i);else if(i.stopped==!1)throw new Error(`can't start timer. timer with name ${t} is already started`);i.startTime=window.performance.now(),i.stopped=!1}static stop(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't stop timer. timer with name ${t} does not exist`);if(i.stopped===!0)throw new Error(`can't stop timer. timer with name ${t} is already stopped`);i.stopTime=window.performance.now(),i.cumulativeElapsed=i.cumulativeElapsed+i.stopTime-i.startTime,i.stopped=!0}static restart(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't restart timer. timer with name ${t} does not exist`);i.startTime=window.performance.now(),i.cumulativeElapsed=0,i.stopped=!1}static elapsed(t){const i=this._timers.filter(n=>n.name===t).find(Boolean);if(i===void 0)throw new Error(`can't get elapsed time. timer with name ${t} does not exist`);return i.stopped?i.cumulativeElapsed:i.cumulativeElapsed+window.performance.now()-i.startTime}static remove(t){if(this._timers.filter(n=>n.name===t).find(Boolean)===void 0)throw new Error(`can't remove timer. timer with name ${t} does not exist`);this._timers=this._timers.filter(n=>n.name!=t)}static removeAll(){this._timers=new Array}static exists(t){return this._timers.some(i=>i.name===t)}};Gn._timers=new Array;let pa=Gn;class gr{static SingleFromRange(t,i){return Math.floor(Math.random()*(i-t+1))+t}static FromRangeWithoutReplacement(t,i,n){if(t>n-i+1)throw new Error(`number of requested draws (n = ${t}) is greater than number of integers in range [ ${i}, ${n}]`);const c=new Array;for(let h=0;h<t;h++){const C=gr.SingleFromRange(i,n);c.includes(C)?t++:c.push(C)}return c}static FromGridWithoutReplacement(t,i,n,c){const h=new Array,C=i*n-1,T=this.FromRangeWithoutReplacement(t,0,C);let B=0,$=NaN;for(;B<t;){const it=T[B]%n,ct=(T[B]-it)/n;if(c===void 0||c(ct,it))h.push({row:ct,column:it}),B++;else{do $=this.FromRangeWithoutReplacement(1,0,C)[0];while(T.includes($));T[B]=$}}return h}}class ma extends ae{constructor(t){super(t),this.type=lt.SoundPlayer,this.isDrawable=!1,this.soundName=t.soundName}initialize(){}dispose(){}duplicate(t){throw new Error("Method not implemented.")}}class ga extends ae{constructor(t){if(super(t),this.type=lt.SoundRecorder,this.isDrawable=!1,this._isRecording=!1,this._isPaused=!1,this.audioChunks=[],this.timerUuid="",t?.mimeType){const i=this.getMediaRecorderSupportedAudioMimeTypes();if(i.includes(t.mimeType))this.mimeType=t.mimeType;else if(console.warn(`Unsupported MIME type in SoundRecorderOptions: ${t.mimeType}. Supported types are: ${i}.`),t.backupMimeTypes){const n=this.getSupportedBackupMimeType(t.backupMimeTypes);n&&(this.mimeType=n,console.log(`Using backup MIME type: ${n}.`))}}t?.audioTrackConstraints&&(this.audioTrackConstraints=t.audioTrackConstraints),t?.maximumDuration&&(this.maximumDuration=t.maximumDuration)}initialize(){}async start(){if(this.isRecording)throw new Error("cannot start SoundRecorder because it is already started.");const t=this.getMediaRecorderSupportedAudioMimeTypes();if(t.length===0)throw new Error("SoundRecorder found no supported MIME types for MediaRecorder.");this.mimeType||(this.mimeType=t[0],console.log(`Using MIME type: ${this.mimeType}.`));let i;try{i=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints?this.audioTrackConstraints:!0})}catch{throw new Error("Error getting user media.")}if(!i)throw new Error("no stream.");const n=i.getAudioTracks();this.mediaTrackSettings=n?.map(c=>c.getSettings()),this.mediaRecorder=new MediaRecorder(i,{mimeType:this.mimeType}),this.mediaRecorder.ondataavailable=c=>{this.audioChunks.push(c.data)},this.mediaRecorder.onerror=c=>{throw new Error(`MediaRecorder error: ${c?.error?.message} ${c?.message}`)},this.mediaRecorder.start(),this.beginIso8601Timestamp=new Date().toISOString(),this.timerUuid=Ue.generate(),Gt.startNew(this.timerUuid),this._isRecording=!0,this._isPaused=!1}async stop(){if(!this.isRecording)throw new Error("cannot stop SoundRecorder because it has not started.");return new Promise(t=>{if(!this.mediaRecorder)throw new Error("no media recorder");this.mediaRecorder.onstop=async()=>{if(!this.mimeType)throw new Error("no mimeType");this._isRecording=!1,this._isPaused=!1;const i=new Blob(this.audioChunks,{type:this.getMimeTypeWithoutCodecs(this.mimeType)}),n=await this.blobToBase64(i);t({mimeType:this.mimeType,beginIso8601Timestamp:this.beginIso8601Timestamp??"",endIso8601Timestamp:this.endIso8601Timestamp??"",duration:Gt.elapsed(this.timerUuid),audioTrackSettings:this.mediaTrackSettings,audioBase64:n,audioBlob:i})},this.mediaRecorder.stop(),this.endIso8601Timestamp=new Date().toISOString(),this.isPaused||Gt.stop(this.timerUuid)})}pause(){if(!this.isRecording)throw new Error("cannot pause SoundRecorder because it is not started.");if(this.isPaused)throw new Error("cannot pause SoundRecorder because it is already paused.");this.mediaRecorder?.pause(),this._isPaused=!0,Gt.stop(this.timerUuid)}resume(){if(!this.isRecording)throw new Error("cannot resume SoundRecorder because it is not started.");if(!this.isPaused)throw new Error("cannot resume SoundRecorder because it is not paused.");this.mediaRecorder?.resume(),this._isPaused=!1,Gt.start(this.timerUuid)}get isRecording(){return this._isRecording}get isPaused(){return this._isPaused}update(){if(super.update(),this.isRecording&&!this.isPaused&&this.maximumDuration!==void 0&&Gt.elapsed(this.timerUuid)>this.maximumDuration){this.pause();return}}getMediaRecorderSupportedAudioMimeTypes(){const t=["audio"],i=["webm","ogg","mp3","mp4","x-matroska","3gpp","3gpp2","3gp2","quicktime","mpeg","aac","flac","x-flac","wave","wav","x-wav","x-pn-wav","not-supported"],n=["vp9","vp9.0","vp8","vp8.0","avc1","av1","h265","h.265","h264","h.264","opus","vorbis","pcm","aac","mpeg","mp4a","rtx","red","ulpfec","g722","pcmu","pcma","cn","telephone-event","not-supported"];return[...new Set(i.flatMap(c=>t.flatMap(h=>[`${h}/${c}`]))),...new Set(i.flatMap(c=>n.flatMap(h=>t.flatMap(C=>[`${C}/${c};codecs=${h}`])))),...new Set(i.flatMap(c=>n.flatMap(h=>n.flatMap(C=>t.flatMap(T=>[`${T}/${c};codecs="${h}, ${C}"`])))))].filter(c=>MediaRecorder.isTypeSupported(c))}blobToBase64(t){return new Promise((i,n)=>{const c=new FileReader;c.onloadend=()=>{const h=c.result?.toString().split(",").pop();if(h===void 0)throw new Error("base64WithoutPrefix is undefined.");i(h)},c.onerror=n,c.readAsDataURL(t)})}getMimeTypeWithoutCodecs(t){const i=t.match(/^[^;]+/);return i?i[0]:""}getSupportedBackupMimeType(t){const i=this.getMediaRecorderSupportedAudioMimeTypes();for(const n of t)if(i.includes(n))return n}dispose(){}duplicate(t){throw new Error(`Method not implemented. ${t}`)}}class ya{static create(t){return new Array}}console.log("\u26AA @m2c2kit/core version 0.3.25 (af00d1f0)");export{q as Action,oi as ActivityType,xt as CanvasKitHelpers,qs as ColorfulMutablePath,Xs as Composite,X as Constants,Bt as ConstraintType,gn as CustomAction,Cn as Dimensions,Re as Easings,H as Equal,Qs as Equals,En as EventStore,de as EventStoreMode,bn as FadeAlphaAction,Tn as FontManager,da as Game,pn as GroupAction,Ni as I18n,lr as ImageManager,Ii as Label,$e as LabelHorizontalAlignmentMode,An as LayoutConstraint,pa as LegacyTimer,j as M2EventType,Qt as M2ImageStatus,ae as M2Node,_n as M2NodeFactory,lt as M2NodeType,Ut as M2SoundStatus,Y as M2c2KitHelpers,wn as MoveAction,Oi as MutablePath,zn as NoneTransition,yn as PlayAction,gr as RandomDraws,ar as RepeatAction,mn as RepeatForeverAction,Pn as RotateAction,Sn as ScaleAction,Ge as Scene,Un as SceneTransition,fn as SequenceAction,li as Shape,Wt as ShapeType,Bn as SlideTransition,Wn as SoundManager,ma as SoundPlayer,ga as SoundRecorder,hi as Sprite,ya as Story,Li as TextLine,Gt as Timer,We as Transition,ye as TransitionDirection,ge as TransitionType,Ue as Uuid,vn as WaitAction,x as WebColors,mr as WebGlInfo,Ne as handleInterfaceOptions};