excalibur 0.26.0-alpha.310 → 0.26.0-alpha.314
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/CHANGELOG.md +9 -2
- package/build/dist/Actor.js +3 -1
- package/build/dist/Actor.js.map +1 -1
- package/build/dist/Collision/Detection/DynamicTreeCollisionProcessor.d.ts +2 -2
- package/build/dist/Collision/Detection/DynamicTreeCollisionProcessor.js +9 -26
- package/build/dist/Collision/Detection/DynamicTreeCollisionProcessor.js.map +1 -1
- package/build/dist/Collision/Detection/Pair.d.ts +5 -0
- package/build/dist/Collision/Detection/Pair.js +19 -0
- package/build/dist/Collision/Detection/Pair.js.map +1 -1
- package/build/dist/Debug/Debug.d.ts +16 -0
- package/build/dist/Debug/Debug.js +35 -0
- package/build/dist/Debug/Debug.js.map +1 -1
- package/build/dist/Drawing/Animation.js +10 -1
- package/build/dist/Drawing/Animation.js.map +1 -1
- package/build/dist/Drawing/Polygon.js +11 -1
- package/build/dist/Drawing/Polygon.js.map +1 -1
- package/build/dist/Drawing/Sprite.js +24 -25
- package/build/dist/Drawing/Sprite.js.map +1 -1
- package/build/dist/Drawing/Texture.js +25 -36
- package/build/dist/Drawing/Texture.js.map +1 -1
- package/build/dist/Engine.d.ts +34 -1
- package/build/dist/Engine.js +114 -60
- package/build/dist/Engine.js.map +1 -1
- package/build/dist/EntityComponentSystem/SystemManager.d.ts +6 -0
- package/build/dist/EntityComponentSystem/SystemManager.js +12 -5
- package/build/dist/EntityComponentSystem/SystemManager.js.map +1 -1
- package/build/dist/Graphics/Animation.js +7 -1
- package/build/dist/Graphics/Animation.js.map +1 -1
- package/build/dist/Graphics/Canvas.js +5 -1
- package/build/dist/Graphics/Canvas.js.map +1 -1
- package/build/dist/Graphics/Circle.js +5 -1
- package/build/dist/Graphics/Circle.js.map +1 -1
- package/build/dist/Graphics/Context/ExcaliburGraphicsContextWebGL.js +4 -4
- package/build/dist/Graphics/Context/ExcaliburGraphicsContextWebGL.js.map +1 -1
- package/build/dist/Graphics/Font.js +14 -2
- package/build/dist/Graphics/Font.js.map +1 -1
- package/build/dist/Graphics/GraphicsComponent.js +6 -3
- package/build/dist/Graphics/GraphicsComponent.js.map +1 -1
- package/build/dist/Graphics/GraphicsGroup.js +4 -1
- package/build/dist/Graphics/GraphicsGroup.js.map +1 -1
- package/build/dist/Graphics/ImageSource.js +25 -36
- package/build/dist/Graphics/ImageSource.js.map +1 -1
- package/build/dist/Graphics/Polygon.js +5 -1
- package/build/dist/Graphics/Polygon.js.map +1 -1
- package/build/dist/Graphics/Rectangle.js +6 -1
- package/build/dist/Graphics/Rectangle.js.map +1 -1
- package/build/dist/Graphics/Sprite.js +6 -1
- package/build/dist/Graphics/Sprite.js.map +1 -1
- package/build/dist/Graphics/SpriteSheet.js +2 -2
- package/build/dist/Graphics/SpriteSheet.js.map +1 -1
- package/build/dist/Loader.d.ts +4 -1
- package/build/dist/Loader.js +47 -45
- package/build/dist/Loader.js.map +1 -1
- package/build/dist/Particles.js +1 -1
- package/build/dist/Particles.js.map +1 -1
- package/build/dist/Resources/Gif.js +8 -19
- package/build/dist/Resources/Gif.js.map +1 -1
- package/build/dist/Resources/Sound/Sound.js +42 -59
- package/build/dist/Resources/Sound/Sound.js.map +1 -1
- package/build/dist/Scene.js +1 -0
- package/build/dist/Scene.js.map +1 -1
- package/build/dist/Screen.js +3 -3
- package/build/dist/Screen.js.map +1 -1
- package/build/dist/ScreenElement.js +1 -1
- package/build/dist/ScreenElement.js.map +1 -1
- package/build/dist/Trigger.js +4 -1
- package/build/dist/Trigger.js.map +1 -1
- package/build/dist/Util/Clock.d.ts +117 -0
- package/build/dist/Util/Clock.js +209 -0
- package/build/dist/Util/Clock.js.map +1 -0
- package/build/dist/Util/Decorators.js +7 -2
- package/build/dist/Util/Decorators.js.map +1 -1
- package/build/dist/Util/Fps.d.ts +40 -0
- package/build/dist/Util/Fps.js +47 -0
- package/build/dist/Util/Fps.js.map +1 -0
- package/build/dist/Util/Util.d.ts +6 -1
- package/build/dist/Util/Util.js +9 -3
- package/build/dist/Util/Util.js.map +1 -1
- package/build/dist/Util/WebAudio.js.map +1 -1
- package/build/dist/excalibur.js +743 -346
- package/build/dist/excalibur.js.map +1 -1
- package/build/dist/excalibur.min.js +1 -1
- package/build/dist/excalibur.min.js.LICENSE.txt +1 -1
- package/build/dist/excalibur.min.js.map +1 -1
- package/build/dist/index.d.ts +3 -0
- package/build/dist/index.js +5 -2
- package/build/dist/index.js.map +1 -1
- package/build/esm/Collision/Detection/DynamicTreeCollisionProcessor.d.ts +2 -2
- package/build/esm/Collision/Detection/Pair.d.ts +5 -0
- package/build/esm/Debug/Debug.d.ts +16 -0
- package/build/esm/Engine.d.ts +34 -1
- package/build/esm/EntityComponentSystem/SystemManager.d.ts +6 -0
- package/build/esm/Loader.d.ts +4 -1
- package/build/esm/Util/Clock.d.ts +117 -0
- package/build/esm/Util/Fps.d.ts +40 -0
- package/build/esm/Util/Util.d.ts +6 -1
- package/build/esm/excalibur.js +749 -347
- package/build/esm/excalibur.js.map +1 -1
- package/build/esm/excalibur.min.js +1 -1
- package/build/esm/excalibur.min.js.LICENSE.txt +1 -1
- package/build/esm/excalibur.min.js.map +1 -1
- package/build/esm/index.d.ts +3 -0
- package/package.json +4 -4
- package/wallaby.js +1 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/*! For license information please see excalibur.min.js.LICENSE.txt */
|
|
2
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ex=e():t.ex=e()}(self,(function(){return(()=>{var t={4662:(t,e,i)=>{i(3430);var s=i(8791);t.exports=s("Array","sort")},8343:(t,e,i)=>{i(4769);var s=i(9276);t.exports=s.Object.keys},7111:(t,e,i)=>{var s=i(9859),n=i(6733),r=i(9821),o=s.TypeError;t.exports=function(t){if(n(t))return t;throw o(r(t)+" is not a function")}},1176:(t,e,i)=>{var s=i(9859),n=i(5052),r=s.String,o=s.TypeError;t.exports=function(t){if(n(t))return t;throw o(r(t)+" is not an object")}},9540:(t,e,i)=>{var s=i(905),n=i(3231),r=i(9646),o=function(t){return function(e,i,o){var a,h=s(e),l=r(h),c=n(o,l);if(t&&i!=i){for(;l>c;)if((a=h[c++])!=a)return!0}else for(;l>c;c++)if((t||c in h)&&h[c]===i)return t||c||0;return!t&&-1}};t.exports={includes:o(!0),indexOf:o(!1)}},6038:(t,e,i)=>{"use strict";var s=i(4229);t.exports=function(t,e){var i=[][t];return!!i&&s((function(){i.call(null,e||function(){throw 1},1)}))}},1909:(t,e,i)=>{var s=i(5968);t.exports=s([].slice)},3867:(t,e,i)=>{var s=i(1909),n=Math.floor,r=function(t,e){var i=t.length,h=n(i/2);return i<8?o(t,e):a(t,r(s(t,0,h),e),r(s(t,h),e),e)},o=function(t,e){for(var i,s,n=t.length,r=1;r<n;){for(s=r,i=t[r];s&&e(t[s-1],i)>0;)t[s]=t[--s];s!==r++&&(t[s]=i)}return t},a=function(t,e,i,s){for(var n=e.length,r=i.length,o=0,a=0;o<n||a<r;)t[o+a]=o<n&&a<r?s(e[o],i[a])<=0?e[o++]:i[a++]:o<n?e[o++]:i[a++];return t};t.exports=r},7079:(t,e,i)=>{var s=i(5968),n=s({}.toString),r=s("".slice);t.exports=function(t){return r(n(t),8,-1)}},1589:(t,e,i)=>{var s=i(9859),n=i(1601),r=i(6733),o=i(7079),a=i(95)("toStringTag"),h=s.Object,l="Arguments"==o(function(){return arguments}());t.exports=n?o:function(t){var e,i,s;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=h(t),a))?i:l?o(e):"Object"==(s=o(e))&&r(e.callee)?"Arguments":s}},7081:(t,e,i)=>{var s=i(8270),n=i(4826),r=i(7933),o=i(1787);t.exports=function(t,e){for(var i=n(e),a=o.f,h=r.f,l=0;l<i.length;l++){var c=i[l];s(t,c)||a(t,c,h(e,c))}}},5762:(t,e,i)=>{var s=i(7400),n=i(1787),r=i(5358);t.exports=s?function(t,e,i){return n.f(t,e,r(1,i))}:function(t,e,i){return t[e]=i,t}},5358:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},7400:(t,e,i)=>{var s=i(4229);t.exports=!s((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},2635:(t,e,i)=>{var s=i(9859),n=i(5052),r=s.document,o=n(r)&&n(r.createElement);t.exports=function(t){return o?r.createElement(t):{}}},2671:(t,e,i)=>{var s=i(598).match(/firefox\/(\d+)/i);t.exports=!!s&&+s[1]},8506:(t,e,i)=>{var s=i(598);t.exports=/MSIE|Trident/.test(s)},598:(t,e,i)=>{var s=i(1333);t.exports=s("navigator","userAgent")||""},6358:(t,e,i)=>{var s,n,r=i(9859),o=i(598),a=r.process,h=r.Deno,l=a&&a.versions||h&&h.version,c=l&&l.v8;c&&(n=(s=c.split("."))[0]>0&&s[0]<4?1:+(s[0]+s[1])),!n&&o&&(!(s=o.match(/Edge\/(\d+)/))||s[1]>=74)&&(s=o.match(/Chrome\/(\d+)/))&&(n=+s[1]),t.exports=n},9811:(t,e,i)=>{var s=i(598).match(/AppleWebKit\/(\d+)\./);t.exports=!!s&&+s[1]},8791:(t,e,i)=>{var s=i(9859),n=i(5968);t.exports=function(t,e){return n(s[t].prototype[e])}},3837:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},3103:(t,e,i)=>{var s=i(9859),n=i(7933).f,r=i(5762),o=i(7487),a=i(2079),h=i(7081),l=i(6541);t.exports=function(t,e){var i,c,d,u,p,g=t.target,_=t.global,f=t.stat;if(i=_?s:f?s[g]||a(g,{}):(s[g]||{}).prototype)for(c in e){if(u=e[c],d=t.noTargetGet?(p=n(i,c))&&p.value:i[c],!l(_?c:g+(f?".":"#")+c,t.forced)&&void 0!==d){if(typeof u==typeof d)continue;h(u,d)}(t.sham||d&&d.sham)&&r(u,"sham",!0),o(i,c,u,t)}}},4229:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},266:t=>{var e=Function.prototype.call;t.exports=e.bind?e.bind(e):function(){return e.apply(e,arguments)}},1805:(t,e,i)=>{var s=i(7400),n=i(8270),r=Function.prototype,o=s&&Object.getOwnPropertyDescriptor,a=n(r,"name"),h=a&&"something"===function(){}.name,l=a&&(!s||s&&o(r,"name").configurable);t.exports={EXISTS:a,PROPER:h,CONFIGURABLE:l}},5968:t=>{var e=Function.prototype,i=e.bind,s=e.call,n=i&&i.bind(s);t.exports=i?function(t){return t&&n(s,t)}:function(t){return t&&function(){return s.apply(t,arguments)}}},1333:(t,e,i)=>{var s=i(9859),n=i(6733),r=function(t){return n(t)?t:void 0};t.exports=function(t,e){return arguments.length<2?r(s[t]):s[t]&&s[t][e]}},5300:(t,e,i)=>{var s=i(7111);t.exports=function(t,e){var i=t[e];return null==i?void 0:s(i)}},9859:(t,e,i)=>{var s=function(t){return t&&t.Math==Math&&t};t.exports=s("object"==typeof globalThis&&globalThis)||s("object"==typeof window&&window)||s("object"==typeof self&&self)||s("object"==typeof i.g&&i.g)||function(){return this}()||Function("return this")()},8270:(t,e,i)=>{var s=i(5968),n=i(2991),r=s({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,e){return r(n(t),e)}},5977:t=>{t.exports={}},4394:(t,e,i)=>{var s=i(7400),n=i(4229),r=i(2635);t.exports=!s&&!n((function(){return 7!=Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a}))},9337:(t,e,i)=>{var s=i(9859),n=i(5968),r=i(4229),o=i(7079),a=s.Object,h=n("".split);t.exports=r((function(){return!a("z").propertyIsEnumerable(0)}))?function(t){return"String"==o(t)?h(t,""):a(t)}:a},8511:(t,e,i)=>{var s=i(5968),n=i(6733),r=i(5353),o=s(Function.toString);n(r.inspectSource)||(r.inspectSource=function(t){return o(t)}),t.exports=r.inspectSource},6407:(t,e,i)=>{var s,n,r,o=i(8694),a=i(9859),h=i(5968),l=i(5052),c=i(5762),d=i(8270),u=i(5353),p=i(4399),g=i(5977),_="Object already initialized",f=a.TypeError,m=a.WeakMap;if(o||u.state){var y=u.state||(u.state=new m),w=h(y.get),v=h(y.has),x=h(y.set);s=function(t,e){if(v(y,t))throw new f(_);return e.facade=t,x(y,t,e),e},n=function(t){return w(y,t)||{}},r=function(t){return v(y,t)}}else{var b=p("state");g[b]=!0,s=function(t,e){if(d(t,b))throw new f(_);return e.facade=t,c(t,b,e),e},n=function(t){return d(t,b)?t[b]:{}},r=function(t){return d(t,b)}}t.exports={set:s,get:n,has:r,enforce:function(t){return r(t)?n(t):s(t,{})},getterFor:function(t){return function(e){var i;if(!l(e)||(i=n(e)).type!==t)throw f("Incompatible receiver, "+t+" required");return i}}}},6733:t=>{t.exports=function(t){return"function"==typeof t}},6541:(t,e,i)=>{var s=i(4229),n=i(6733),r=/#|\.prototype\./,o=function(t,e){var i=h[a(t)];return i==c||i!=l&&(n(e)?s(e):!!e)},a=o.normalize=function(t){return String(t).replace(r,".").toLowerCase()},h=o.data={},l=o.NATIVE="N",c=o.POLYFILL="P";t.exports=o},5052:(t,e,i)=>{var s=i(6733);t.exports=function(t){return"object"==typeof t?null!==t:s(t)}},4231:t=>{t.exports=!1},9395:(t,e,i)=>{var s=i(9859),n=i(1333),r=i(6733),o=i(1321),a=i(6969),h=s.Object;t.exports=a?function(t){return"symbol"==typeof t}:function(t){var e=n("Symbol");return r(e)&&o(e.prototype,h(t))}},9646:(t,e,i)=>{var s=i(4237);t.exports=function(t){return s(t.length)}},3839:(t,e,i)=>{var s=i(6358),n=i(4229);t.exports=!!Object.getOwnPropertySymbols&&!n((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&s&&s<41}))},8694:(t,e,i)=>{var s=i(9859),n=i(6733),r=i(8511),o=s.WeakMap;t.exports=n(o)&&/native code/.test(r(o))},1787:(t,e,i)=>{var s=i(9859),n=i(7400),r=i(4394),o=i(1176),a=i(9310),h=s.TypeError,l=Object.defineProperty;e.f=n?l:function(t,e,i){if(o(t),e=a(e),o(i),r)try{return l(t,e,i)}catch(t){}if("get"in i||"set"in i)throw h("Accessors not supported");return"value"in i&&(t[e]=i.value),t}},7933:(t,e,i)=>{var s=i(7400),n=i(266),r=i(9195),o=i(5358),a=i(905),h=i(9310),l=i(8270),c=i(4394),d=Object.getOwnPropertyDescriptor;e.f=s?d:function(t,e){if(t=a(t),e=h(e),c)try{return d(t,e)}catch(t){}if(l(t,e))return o(!n(r.f,t,e),t[e])}},8151:(t,e,i)=>{var s=i(140),n=i(3837).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return s(t,n)}},894:(t,e)=>{e.f=Object.getOwnPropertySymbols},1321:(t,e,i)=>{var s=i(5968);t.exports=s({}.isPrototypeOf)},140:(t,e,i)=>{var s=i(5968),n=i(8270),r=i(905),o=i(9540).indexOf,a=i(5977),h=s([].push);t.exports=function(t,e){var i,s=r(t),l=0,c=[];for(i in s)!n(a,i)&&n(s,i)&&h(c,i);for(;e.length>l;)n(s,i=e[l++])&&(~o(c,i)||h(c,i));return c}},5632:(t,e,i)=>{var s=i(140),n=i(3837);t.exports=Object.keys||function(t){return s(t,n)}},9195:(t,e)=>{"use strict";var i={}.propertyIsEnumerable,s=Object.getOwnPropertyDescriptor,n=s&&!i.call({1:2},1);e.f=n?function(t){var e=s(this,t);return!!e&&e.enumerable}:i},2914:(t,e,i)=>{var s=i(9859),n=i(266),r=i(6733),o=i(5052),a=s.TypeError;t.exports=function(t,e){var i,s;if("string"===e&&r(i=t.toString)&&!o(s=n(i,t)))return s;if(r(i=t.valueOf)&&!o(s=n(i,t)))return s;if("string"!==e&&r(i=t.toString)&&!o(s=n(i,t)))return s;throw a("Can't convert object to primitive value")}},4826:(t,e,i)=>{var s=i(1333),n=i(5968),r=i(8151),o=i(894),a=i(1176),h=n([].concat);t.exports=s("Reflect","ownKeys")||function(t){var e=r.f(a(t)),i=o.f;return i?h(e,i(t)):e}},9276:(t,e,i)=>{var s=i(9859);t.exports=s},7487:(t,e,i)=>{var s=i(9859),n=i(6733),r=i(8270),o=i(5762),a=i(2079),h=i(8511),l=i(6407),c=i(1805).CONFIGURABLE,d=l.get,u=l.enforce,p=String(String).split("String");(t.exports=function(t,e,i,h){var l,d=!!h&&!!h.unsafe,g=!!h&&!!h.enumerable,_=!!h&&!!h.noTargetGet,f=h&&void 0!==h.name?h.name:e;n(i)&&("Symbol("===String(f).slice(0,7)&&(f="["+String(f).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),(!r(i,"name")||c&&i.name!==f)&&o(i,"name",f),(l=u(i)).source||(l.source=p.join("string"==typeof f?f:""))),t!==s?(d?!_&&t[e]&&(g=!0):delete t[e],g?t[e]=i:o(t,e,i)):g?t[e]=i:a(e,i)})(Function.prototype,"toString",(function(){return n(this)&&d(this).source||h(this)}))},8885:(t,e,i)=>{var s=i(9859).TypeError;t.exports=function(t){if(null==t)throw s("Can't call method on "+t);return t}},2079:(t,e,i)=>{var s=i(9859),n=Object.defineProperty;t.exports=function(t,e){try{n(s,t,{value:e,configurable:!0,writable:!0})}catch(i){s[t]=e}return e}},4399:(t,e,i)=>{var s=i(3036),n=i(1441),r=s("keys");t.exports=function(t){return r[t]||(r[t]=n(t))}},5353:(t,e,i)=>{var s=i(9859),n=i(2079),r="__core-js_shared__",o=s[r]||n(r,{});t.exports=o},3036:(t,e,i)=>{var s=i(4231),n=i(5353);(t.exports=function(t,e){return n[t]||(n[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.19.1",mode:s?"pure":"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})},3231:(t,e,i)=>{var s=i(3329),n=Math.max,r=Math.min;t.exports=function(t,e){var i=s(t);return i<0?n(i+e,0):r(i,e)}},905:(t,e,i)=>{var s=i(9337),n=i(8885);t.exports=function(t){return s(n(t))}},3329:t=>{var e=Math.ceil,i=Math.floor;t.exports=function(t){var s=+t;return s!=s||0===s?0:(s>0?i:e)(s)}},4237:(t,e,i)=>{var s=i(3329),n=Math.min;t.exports=function(t){return t>0?n(s(t),9007199254740991):0}},2991:(t,e,i)=>{var s=i(9859),n=i(8885),r=s.Object;t.exports=function(t){return r(n(t))}},2066:(t,e,i)=>{var s=i(9859),n=i(266),r=i(5052),o=i(9395),a=i(5300),h=i(2914),l=i(95),c=s.TypeError,d=l("toPrimitive");t.exports=function(t,e){if(!r(t)||o(t))return t;var i,s=a(t,d);if(s){if(void 0===e&&(e="default"),i=n(s,t,e),!r(i)||o(i))return i;throw c("Can't convert object to primitive value")}return void 0===e&&(e="number"),h(t,e)}},9310:(t,e,i)=>{var s=i(2066),n=i(9395);t.exports=function(t){var e=s(t,"string");return n(e)?e:e+""}},1601:(t,e,i)=>{var s={};s[i(95)("toStringTag")]="z",t.exports="[object z]"===String(s)},3326:(t,e,i)=>{var s=i(9859),n=i(1589),r=s.String;t.exports=function(t){if("Symbol"===n(t))throw TypeError("Cannot convert a Symbol value to a string");return r(t)}},9821:(t,e,i)=>{var s=i(9859).String;t.exports=function(t){try{return s(t)}catch(t){return"Object"}}},1441:(t,e,i)=>{var s=i(5968),n=0,r=Math.random(),o=s(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+o(++n+r,36)}},6969:(t,e,i)=>{var s=i(3839);t.exports=s&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},95:(t,e,i)=>{var s=i(9859),n=i(3036),r=i(8270),o=i(1441),a=i(3839),h=i(6969),l=n("wks"),c=s.Symbol,d=c&&c.for,u=h?c:c&&c.withoutSetter||o;t.exports=function(t){if(!r(l,t)||!a&&"string"!=typeof l[t]){var e="Symbol."+t;a&&r(c,t)?l[t]=c[t]:l[t]=h&&d?d(e):u(e)}return l[t]}},3430:(t,e,i)=>{"use strict";var s=i(3103),n=i(5968),r=i(7111),o=i(2991),a=i(9646),h=i(3326),l=i(4229),c=i(3867),d=i(6038),u=i(2671),p=i(8506),g=i(6358),_=i(9811),f=[],m=n(f.sort),y=n(f.push),w=l((function(){f.sort(void 0)})),v=l((function(){f.sort(null)})),x=d("sort"),b=!l((function(){if(g)return g<70;if(!(u&&u>3)){if(p)return!0;if(_)return _<603;var t,e,i,s,n="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(s=0;s<47;s++)f.push({k:e+s,v:i})}for(f.sort((function(t,e){return e.v-t.v})),s=0;s<f.length;s++)e=f[s].k.charAt(0),n.charAt(n.length-1)!==e&&(n+=e);return"DGBEFHACIJK"!==n}}));s({target:"Array",proto:!0,forced:w||!v||!x||!b},{sort:function(t){void 0!==t&&r(t);var e=o(this);if(b)return void 0===t?m(e):m(e,t);var i,s,n=[],l=a(e);for(s=0;s<l;s++)s in e&&y(n,e[s]);for(c(n,function(t){return function(e,i){return void 0===i?-1:void 0===e?1:void 0!==t?+t(e,i)||0:h(e)>h(i)?1:-1}}(t)),i=n.length,s=0;s<i;)e[s]=n[s++];for(;s<l;)delete e[s++];return e}})},4769:(t,e,i)=>{var s=i(3103),n=i(2991),r=i(5632);s({target:"Object",stat:!0,forced:i(4229)((function(){r(1)}))},{keys:function(t){return r(n(t))}})},1388:(t,e,i)=>{"use strict";i.d(e,{Z:()=>a});var s=i(272),n=i.n(s),r=i(2609),o=i.n(r)()(n());o.push([t.id,"/* Buttons styles start */\n\nbutton#excalibur-play {\n display: inline-block;\n position: relative;\n z-index: 999;\n border-radius: 6px;\n border: none;\n /*border: 3px solid;\n border-color: white;\n box-shadow: 0 0 10px #ccc;*/\n padding: 1rem 1.5rem 1rem 4rem;\n margin: 0;\n text-decoration: none;\n background: #00b233;\n color: #ffffff;\n font-family: sans-serif;\n font-size: 2rem;\n white-space: nowrap;\n line-height: 1;\n cursor: pointer;\n text-align: center;\n transition: background 250ms ease-in-out, transform 150ms ease;\n -webkit-appearance: none;\n -moz-appearance: none;\n\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\n animation: excalibur-button-fadein 200ms;\n}\n\n/*\nbutton#excalibur-play {\n display: none;\n}*/\n\nbutton#excalibur-play:after {\n position: absolute;\n content: '';\n border: 8px solid;\n border-color: transparent transparent transparent white;\n left: 35px;\n top: 24px;\n width: 0;\n height: 0;\n}\n\nbutton#excalibur-play:before {\n position: absolute;\n content: '';\n border: 3px solid;\n left: 19px;\n top: 14px;\n border-radius: 20px;\n width: 30px;\n height: 30px;\n}\n\nbutton#excalibur-play:hover,\nbutton#excalibur-play:focus {\n background: #00982c;\n}\n\nbutton#excalibur-play:focus {\n outline: 1px solid #fff;\n outline-offset: -4px;\n}\n\nbutton#excalibur-play:active {\n transform: scale(0.99);\n}\n\n@keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Firefox < 16 */\n@-moz-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Safari, Chrome and Opera > 12.1 */\n@-webkit-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Internet Explorer */\n@-ms-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Opera < 12.1 */\n@-o-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n","",{version:3,sources:["webpack://./Loader.css"],names:[],mappings:"AAAA,yBAAyB;;AAEzB;EACE,qBAAqB;EACrB,kBAAkB;EAClB,YAAY;EACZ,kBAAkB;EAClB,YAAY;EACZ;;+BAE6B;EAC7B,8BAA8B;EAC9B,SAAS;EACT,qBAAqB;EACrB,mBAAmB;EACnB,cAAc;EACd,uBAAuB;EACvB,eAAe;EACf,mBAAmB;EACnB,cAAc;EACd,eAAe;EACf,kBAAkB;EAClB,8DAA8D;EAC9D,wBAAwB;EACxB,qBAAqB;;EAErB,gDAAgD,EAAE,oCAAoC;EACtF,6CAA6C,EAAE,iBAAiB;EAChE,4CAA4C,EAAE,sBAAsB;EACpE,2CAA2C,EAAE,iBAAiB;EAC9D,wCAAwC;AAC1C;;AAEA;;;EAGE;;AAEF;EACE,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,uDAAuD;EACvD,UAAU;EACV,SAAS;EACT,QAAQ;EACR,SAAS;AACX;;AAEA;EACE,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,WAAW;EACX,YAAY;AACd;;AAEA;;EAEE,mBAAmB;AACrB;;AAEA;EACE,uBAAuB;EACvB,oBAAoB;AACtB;;AAEA;EACE,sBAAsB;AACxB;;AAEA;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,iBAAiB;AACjB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,oCAAoC;AACpC;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,sBAAsB;AACtB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,iBAAiB;AACjB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF",sourcesContent:["/* Buttons styles start */\n\nbutton#excalibur-play {\n display: inline-block;\n position: relative;\n z-index: 999;\n border-radius: 6px;\n border: none;\n /*border: 3px solid;\n border-color: white;\n box-shadow: 0 0 10px #ccc;*/\n padding: 1rem 1.5rem 1rem 4rem;\n margin: 0;\n text-decoration: none;\n background: #00b233;\n color: #ffffff;\n font-family: sans-serif;\n font-size: 2rem;\n white-space: nowrap;\n line-height: 1;\n cursor: pointer;\n text-align: center;\n transition: background 250ms ease-in-out, transform 150ms ease;\n -webkit-appearance: none;\n -moz-appearance: none;\n\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\n animation: excalibur-button-fadein 200ms;\n}\n\n/*\nbutton#excalibur-play {\n display: none;\n}*/\n\nbutton#excalibur-play:after {\n position: absolute;\n content: '';\n border: 8px solid;\n border-color: transparent transparent transparent white;\n left: 35px;\n top: 24px;\n width: 0;\n height: 0;\n}\n\nbutton#excalibur-play:before {\n position: absolute;\n content: '';\n border: 3px solid;\n left: 19px;\n top: 14px;\n border-radius: 20px;\n width: 30px;\n height: 30px;\n}\n\nbutton#excalibur-play:hover,\nbutton#excalibur-play:focus {\n background: #00982c;\n}\n\nbutton#excalibur-play:focus {\n outline: 1px solid #fff;\n outline-offset: -4px;\n}\n\nbutton#excalibur-play:active {\n transform: scale(0.99);\n}\n\n@keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Firefox < 16 */\n@-moz-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Safari, Chrome and Opera > 12.1 */\n@-webkit-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Internet Explorer */\n@-ms-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Opera < 12.1 */\n@-o-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n"],sourceRoot:""}]);const a=o},2609:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var i="",s=void 0!==e[5];return e[4]&&(i+="@supports (".concat(e[4],") {")),e[2]&&(i+="@media ".concat(e[2]," {")),s&&(i+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),i+=t(e),s&&(i+="}"),e[2]&&(i+="}"),e[4]&&(i+="}"),i})).join("")},e.i=function(t,i,s,n,r){"string"==typeof t&&(t=[[null,t,void 0]]);var o={};if(s)for(var a=0;a<this.length;a++){var h=this[a][0];null!=h&&(o[h]=!0)}for(var l=0;l<t.length;l++){var c=[].concat(t[l]);s&&o[c[0]]||(void 0!==r&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=r),i&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=i):c[2]=i),n&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=n):c[4]="".concat(n)),e.push(c))}},e}},272:t=>{"use strict";t.exports=function(t){var e=t[1],i=t[3];if(!i)return e;if("function"==typeof btoa){var s=btoa(unescape(encodeURIComponent(JSON.stringify(i)))),n="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(s),r="/*# ".concat(n," */"),o=i.sources.map((function(t){return"/*# sourceURL=".concat(i.sourceRoot||"").concat(t," */")}));return[e].concat(o).concat([r]).join("\n")}return[e].join("\n")}}},e={};function i(s){var n=e[s];if(void 0!==n)return n.exports;var r=e[s]={id:s,exports:{}};return t[s](r,r.exports,i),r.exports}i.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return i.d(e,{a:e}),e},i.d=(t,e)=>{for(var s in e)i.o(e,s)&&!i.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var s={};return(()=>{"use strict";i.r(s),i.d(s,{ActionContext:()=>As,ActionQueue:()=>as,ActionsComponent:()=>Ss,ActionsSystem:()=>Sn,ActivateEvent:()=>ie,Actor:()=>Es,AddedComponent:()=>ji,AddedEntity:()=>Zs,Animation:()=>fn,AnimationDirection:()=>pn,AnimationStrategy:()=>gn,ArcadeSolver:()=>ln,AudioContextFactory:()=>Ze,Axis:()=>Ds,BaseAlign:()=>Ie,BinaryTreeNode:()=>Or,Blink:()=>ys,BodyComponent:()=>Wi,BoundingBox:()=>B,BroadphaseStrategy:()=>ci,BrowserComponent:()=>Xn,BrowserEvents:()=>qn,Camera:()=>Vs,Canvas:()=>Ct,Cell:()=>Ls,Circle:()=>is,CircleCollider:()=>Fi,Class:()=>Qe,ClosestLine:()=>Di,ClosestLineJumpTable:()=>Mi,Collider:()=>Ti,ColliderComponent:()=>Hi,CollisionContact:()=>ki,CollisionEndEvent:()=>te,CollisionGroup:()=>vi,CollisionGroupManager:()=>ur,CollisionJumpTable:()=>Li,CollisionPostSolveEvent:()=>$t,CollisionPreSolveEvent:()=>Qt,CollisionResolutionStrategy:()=>li,CollisionSolver:()=>hn,CollisionStartEvent:()=>Jt,CollisionSystem:()=>un,CollisionType:()=>hi,Color:()=>T,ColorBlindCorrector:()=>On,ColorBlindFlags:()=>zn,ColorBlindness:()=>Pn,Component:()=>_i,CompositeCollider:()=>Ri,Configurable:()=>be,ConsoleAppender:()=>f,ContactConstraintPoint:()=>cn,ContactEndEvent:()=>Yt,ContactStartEvent:()=>Zt,CoordPlane:()=>mi,CullingBox:()=>Vi,DeactivateEvent:()=>se,Debug:()=>Un,DebugSystem:()=>Cn,DebugText:()=>Ve,DegreeOfFreedom:()=>Ni,Detector:()=>ai,Die:()=>xs,Direction:()=>Oe,DisplayMode:()=>Xe,DynamicTree:()=>Si,DynamicTreeCollisionProcessor:()=>Ei,EX_VERSION:()=>Vr,EaseTo:()=>ms,EasingFunctions:()=>os,EdgeCollider:()=>Oi,ElasticToActorStrategy:()=>Hs,EmitterType:()=>_n,Engine:()=>sr,EnterTriggerEvent:()=>oe,EnterViewPortEvent:()=>re,Entity:()=>Zi,EntityManager:()=>Js,EventDispatcher:()=>he,EventTypes:()=>At,Events:()=>t,ExResponse:()=>_r,ExcaliburGraphicsContext2DCanvas:()=>Zn,ExcaliburGraphicsContextWebGL:()=>je,ExitTriggerEvent:()=>ae,ExitViewPortEvent:()=>ne,Experiments:()=>l,Fade:()=>ws,Flags:()=>p,Follow:()=>bs,Font:()=>hr,FontStyle:()=>Le,FontUnit:()=>Fe,FrameStats:()=>Hn,GameEvent:()=>St,GameStartEvent:()=>Rt,GameStopEvent:()=>Bt,GamepadAxisEvent:()=>Wt,GamepadButtonEvent:()=>Nt,GamepadConnectEvent:()=>Ut,GamepadDisconnectEvent:()=>Ht,Gif:()=>Rr,GlobalCoordinates:()=>Yn,Graphic:()=>wt,GraphicsComponent:()=>ts,GraphicsGroup:()=>mn,GraphicsLayer:()=>$i,GraphicsLayers:()=>Ji,GraphicsSystem:()=>xn,HiddenEvent:()=>Xt,ImageSource:()=>Re,InitializeEvent:()=>ee,Input:()=>o,Integrator:()=>di,KillEvent:()=>Pt,Label:()=>dr,Legacy:()=>c,LegacyDrawing:()=>r,LimitCameraBoundsStrategy:()=>Ws,Line:()=>Bi,Loader:()=>ri,LockCameraToActorAxisStrategy:()=>Us,LockCameraToActorStrategy:()=>zs,LogLevel:()=>d,Logger:()=>_,Matrix:()=>tt,MatrixLocations:()=>$,MediaEvent:()=>rr,Meet:()=>Cs,MockedElement:()=>zr,MotionComponent:()=>wi,MotionSystem:()=>an,MoveBy:()=>cs,MoveTo:()=>ds,NativeSoundEvent:()=>or,NativeSoundProcessedEvent:()=>ar,Observable:()=>xi,Pair:()=>bi,ParseGif:()=>Fr,Particle:()=>wn,ParticleEmitter:()=>vn,Physics:()=>pi,PhysicsStats:()=>Nn,PointerComponent:()=>ss,Polygon:()=>kr,PolygonCollider:()=>zi,Pool:()=>ot,PostCollisionEvent:()=>Kt,PostDebugDrawEvent:()=>kt,PostDrawEvent:()=>Mt,PostFrameEvent:()=>zt,PostKillEvent:()=>Tt,PostUpdateEvent:()=>Lt,PreCollisionEvent:()=>qt,PreDebugDrawEvent:()=>Ft,PreDrawEvent:()=>Dt,PreFrameEvent:()=>Ot,PreKillEvent:()=>Et,PreUpdateEvent:()=>It,Projection:()=>Ci,Promise:()=>Wr,PromiseState:()=>Hr,Query:()=>en,QueryManager:()=>sn,RadiusAroundActorStrategy:()=>Ns,Random:()=>M,Raster:()=>bt,Ray:()=>Pi,RealisticSolver:()=>dn,Rectangle:()=>es,RemovedComponent:()=>qi,RemovedEntity:()=>Qs,Repeat:()=>hs,RepeatForever:()=>ls,Resolution:()=>qe,Resource:()=>le,RotateBy:()=>ps,RotateTo:()=>us,RotationType:()=>ns,ScaleBy:()=>_s,ScaleTo:()=>gs,Scene:()=>Ln,Screen:()=>Ke,ScreenAppender:()=>m,ScreenElement:()=>Ts,ScrollPreventionMode:()=>er,Shape:()=>Ui,Side:()=>P,SortedList:()=>Lr,Sound:()=>Er,Sprite:()=>Ee,SpriteFont:()=>We,SpriteSheet:()=>Ne,StrategyContainer:()=>Os,Stream:()=>Mr,SubscribeEvent:()=>Vt,System:()=>Ks,SystemManager:()=>nn,SystemType:()=>qs,TagComponent:()=>fi,Text:()=>lr,TextAlign:()=>ke,TileMap:()=>ks,Timer:()=>Bs,Traits:()=>a,TransformComponent:()=>yi,TreeNode:()=>Ai,Trigger:()=>Xs,UnsubscribeEvent:()=>Gt,Util:()=>h,Vector:()=>A,VectorView:()=>gi,VisibleEvent:()=>jt,WebAudioInstance:()=>Ar,World:()=>rn,canonicalizeAngle:()=>U,clamp:()=>L,createId:()=>g,hasGraphicsTick:()=>Qi,hasOnInitialize:()=>mr,hasOnPostUpdate:()=>xr,hasOnPreUpdate:()=>wr,hasPostDraw:()=>Cr,hasPreDraw:()=>br,has_initialize:()=>fr,has_postupdate:()=>vr,has_preupdate:()=>yr,isAddedComponent:()=>Xi,isAddedSystemEntity:()=>Ys,isRemoveSystemEntity:()=>$s,isRemovedComponent:()=>Ki,maxMessages:()=>y,obsolete:()=>b,randomInRange:()=>O,randomIntInRange:()=>z,range:()=>Y,resetObsoleteCounter:()=>v,toDegrees:()=>H,toRadians:()=>N,vec:()=>S});var t={};i.r(t),i.d(t,{ActivateEvent:()=>ie,CollisionEndEvent:()=>te,CollisionPostSolveEvent:()=>$t,CollisionPreSolveEvent:()=>Qt,CollisionStartEvent:()=>Jt,ContactEndEvent:()=>Yt,ContactStartEvent:()=>Zt,DeactivateEvent:()=>se,EnterTriggerEvent:()=>oe,EnterViewPortEvent:()=>re,EventTypes:()=>At,ExitTriggerEvent:()=>ae,ExitViewPortEvent:()=>ne,GameEvent:()=>St,GameStartEvent:()=>Rt,GameStopEvent:()=>Bt,GamepadAxisEvent:()=>Wt,GamepadButtonEvent:()=>Nt,GamepadConnectEvent:()=>Ut,GamepadDisconnectEvent:()=>Ht,HiddenEvent:()=>Xt,InitializeEvent:()=>ee,KillEvent:()=>Pt,PostCollisionEvent:()=>Kt,PostDebugDrawEvent:()=>kt,PostDrawEvent:()=>Mt,PostFrameEvent:()=>zt,PostKillEvent:()=>Tt,PostUpdateEvent:()=>Lt,PreCollisionEvent:()=>qt,PreDebugDrawEvent:()=>Ft,PreDrawEvent:()=>Dt,PreFrameEvent:()=>Ot,PreKillEvent:()=>Et,PreUpdateEvent:()=>It,SubscribeEvent:()=>Vt,UnsubscribeEvent:()=>Gt,VisibleEvent:()=>jt});var e={};i.r(e),i.d(e,{Colorize:()=>ge,Darken:()=>fe,Desaturate:()=>ye,Fill:()=>we,Grayscale:()=>de,Invert:()=>ue,Lighten:()=>_e,Opacity:()=>pe,Saturate:()=>me});var n={};i.r(n),i.d(n,{circle:()=>ii,line:()=>$e,point:()=>Je,roundRect:()=>ei,vector:()=>ti});var r={};i.r(r),i.d(r,{Animation:()=>Me,CanvasDrawComponent:()=>Yi,CanvasDrawingSystem:()=>bn,Effects:()=>e,Polygon:()=>gr,Sprite:()=>Pe,SpriteFont:()=>He,SpriteSheet:()=>Ue,Texture:()=>xe});var o={};i.r(o),i.d(o,{Axes:()=>Bn,Buttons:()=>Rn,Gamepad:()=>jn,Gamepads:()=>Gn,KeyEvent:()=>Wn,Keyboard:()=>Vn,Keys:()=>Tn,NativePointerButton:()=>Mn,PointerButton:()=>Fn,PointerComponent:()=>ss,PointerEvent:()=>Qn,PointerEventReceiver:()=>tr,PointerScope:()=>En,PointerSystem:()=>An,PointerType:()=>kn,WheelDeltaMode:()=>Dn,WheelEvent:()=>$n});var a={};i.r(a),i.d(a,{OffscreenCulling:()=>Gi});var h={};i.r(h),i.d(h,{Collection:()=>K,ConsoleAppender:()=>f,DrawUtil:()=>n,EasingFunctions:()=>os,LogLevel:()=>d,Logger:()=>_,Observable:()=>xi,ScreenAppender:()=>m,TwoPI:()=>F,addItemToArray:()=>V,base64Encode:()=>k,canonicalizeAngle:()=>U,clamp:()=>L,contains:()=>j,delay:()=>Q,fail:()=>Z,getOppositeSide:()=>X,getPosition:()=>W,getSideFromDirection:()=>q,nullish:()=>I,randomInRange:()=>O,randomIntInRange:()=>z,range:()=>Y,removeItemFromArray:()=>G,toDegrees:()=>H,toRadians:()=>N});var l,c,d;i(4662),i(8343);function u(){if("undefined"==typeof window&&(window={audioContext:function(){}}),"undefined"==typeof window||window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(t){window.setInterval(t,1e3/60)}),"undefined"==typeof window||window.cancelAnimationFrame||(window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(){}),"undefined"!=typeof window&&!window.AudioContext){if(window.webkitAudioContext){const t=window.webkitAudioContext.prototype.decodeAudioData;window.webkitAudioContext.prototype.decodeAudioData=function(e){return new Promise(((i,s)=>{t.call(this,e,i,s)}))}}window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext}"undefined"==typeof window||window.devicePixelRatio||(window.devicePixelRatio=window.devicePixelRatio||1)}!function(t){t.WebGL="use-webgl"}(l||(l={})),function(t){t.Canvas="use-canvas-context",t.LegacyDrawing="use-legacy-drawing"}(c||(c={}));class p{static freeze(){p._FROZEN=!0}static _reset(){p._FROZEN=!1,p._FLAGS={}}static useWebGL(){p.enable(l.WebGL)}static useCanvasGraphicsContext(){p.enable(c.Canvas)}static useLegacyDrawing(){p.enable(c.LegacyDrawing)}static enable(t){if(this._FROZEN)throw Error("Feature flags can only be enabled before Engine constructor time");p._FLAGS[t]=!0}static disable(t){if(this._FROZEN)throw Error("Feature flags can only be disabled before Engine constructor time");p._FLAGS[t]=!1}static isEnabled(t){return!!p._FLAGS[t]}static show(){return Object.keys(p._FLAGS)}}function g(t,e){return{type:t,value:e}}p._FROZEN=!1,p._FLAGS={},function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error",t[t.Fatal=4]="Fatal"}(d||(d={}));class _{constructor(){if(this._appenders=[],this.defaultLevel=d.Info,_._INSTANCE)throw new Error("Logger is a singleton");return _._INSTANCE=this,_._INSTANCE.addAppender(new f),_._INSTANCE}static getInstance(){return null==_._INSTANCE&&(_._INSTANCE=new _),_._INSTANCE}addAppender(t){this._appenders.push(t)}clearAppenders(){this._appenders.length=0}_log(t,e){null==t&&(t=this.defaultLevel);const i=this._appenders.length;for(let s=0;s<i;s++)t>=this.defaultLevel&&this._appenders[s].log(t,e)}debug(...t){this._log(d.Debug,t)}info(...t){this._log(d.Info,t)}warn(...t){this._log(d.Warn,t)}error(...t){this._log(d.Error,t)}fatal(...t){this._log(d.Fatal,t)}}_._INSTANCE=null;class f{log(t,e){if(!console&&!console.log&&console.warn&&console.error)return;const i=[];i.unshift.apply(i,e),i.unshift("["+d[t]+"] : "),t<d.Warn?console.log.apply?console.log.apply(console,i):console.log(i.join(" ")):t<d.Error?console.warn.apply?console.warn.apply(console,i):console.warn(i.join(" ")):console.error.apply?console.error.apply(console,i):console.error(i.join(" "))}}class m{constructor(t,e){this._messages=[],this._canvas=document.createElement("canvas"),this._canvas.width=t||window.innerWidth,this._canvas.height=e||window.innerHeight,this._canvas.style.position="absolute",this._ctx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)}log(t,e){const i=e.join(",");this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._messages.unshift("["+d[t]+"] : "+i);let s=10,n=1;for(let t=0;t<this._messages.length;t++)this._ctx.fillStyle="rgba(255,255,255,"+n.toFixed(2)+")",this._ctx.fillText(this._messages[t],200,s),s+=10,n=n>0?n-.05:0}}const y=5,w={},v=()=>{for(const t in w)w[t]=0},x=(t,e)=>{const i=p.isEnabled("suppress-obsolete-message");w[t]<y&&!i&&(_.getInstance().warn(t),console.trace&&e.showStackTrace&&console.trace()),w[t]++};function b(t){return t=Object.assign({message:"This feature will be removed in future versions of Excalibur.",alternateMethod:null,showStackTrace:!1},t),function(e,i,s){if(s&&"function"!=typeof s.value&&"function"!=typeof s.get&&"function"!=typeof s.set)throw new SyntaxError("Only classes/functions/getters/setters can be marked as obsolete");const n=`${`${e.name||""}${e.name&&i?".":""}${i||""}`} is marked obsolete: ${t.message}`+(t.alternateMethod?` Use ${t.alternateMethod} instead`:"");w[n]||(w[n]=0);const r=s?Object.assign({},s):e;if(!s){class e extends r{constructor(...e){x(n,t),super(...e)}}return e}return s&&s.value?(r.value=function(){return x(n,t),s.value.apply(this,arguments)},r):(s&&s.get&&(r.get=function(){return x(n,t),s.get.apply(this,arguments)}),s&&s.set&&(r.set=function(){return x(n,t),s.set.apply(this,arguments)}),r)}}var C=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class A{constructor(t,e){this._x=0,this._y=0,this._x=t,this._y=e}static get Zero(){return new A(0,0)}static get One(){return new A(1,1)}static get Half(){return new A(.5,.5)}static get Up(){return new A(0,-1)}static get Down(){return new A(0,1)}static get Left(){return new A(-1,0)}static get Right(){return new A(1,0)}static fromAngle(t){return new A(Math.cos(t),Math.sin(t))}static isValid(t){return null!=t&&(!isNaN(t.x)&&!isNaN(t.y)&&(t.x!==1/0&&t.y!==1/0&&t.x!==-1/0&&t.y!==-1/0))}static distance(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}setTo(t,e){this.x=t,this.y=e}equals(t,e=.001){return Math.abs(this.x-t.x)<=e&&Math.abs(this.y-t.y)<=e}distance(t){return t||(t=A.Zero),Math.sqrt(Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2))}squareDistance(t){return t||(t=A.Zero),Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2)}magnitude(){return this.distance()}get size(){return this.distance()}set size(t){const e=this.normalize().scale(t);this.setTo(e.x,e.y)}normalize(){const t=this.distance();return t>0?new A(this.x/t,this.y/t):new A(0,1)}average(t){return this.add(t).scale(.5)}scale(t){return t instanceof A?new A(this.x*t.x,this.y*t.y):new A(this.x*t,this.y*t)}add(t){return new A(this.x+t.x,this.y+t.y)}sub(t){return new A(this.x-t.x,this.y-t.y)}addEqual(t){return this.setTo(this.x+t.x,this.y+t.y),this}subEqual(t){return this.setTo(this.x-t.x,this.y-t.y),this}scaleEqual(t){return this.setTo(this.x*t,this.y*t),this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return t instanceof A?this.x*t.y-this.y*t.x:"number"==typeof t?new A(t*this.y,-t*this.x):void 0}static cross(t,e){return new A(-t*e.y,t*e.x)}perpendicular(){return new A(this.y,-this.x)}normal(){return this.perpendicular().normalize()}negate(){return this.scale(-1)}toAngle(){return Math.atan2(this.y,this.x)}rotate(t,e){e||(e=new A(0,0));const i=Math.sin(t),s=Math.cos(t),n=s*(this.x-e.x)-i*(this.y-e.y)+e.x,r=i*(this.x-e.x)+s*(this.y-e.y)+e.y;return new A(n,r)}clone(){return new A(this.x,this.y)}toString(t){return t?`(${this.x.toFixed(t)}, ${this.y.toFixed(t)})`:`(${this.x}, ${this.y})`}}function S(t,e){return new A(t,e)}C([b({message:"will be removed in favour of `.size` in version 0.25.0"})],A.prototype,"magnitude",null);var P,E=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class T{constructor(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=null!=s?s:1}static fromRGB(t,e,i,s){return new T(t,e,i,s)}static fromRGBString(t){let e=null;if(e=t.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i)){const t=parseInt(e[1],10),i=parseInt(e[2],10),s=parseInt(e[3],10);let n=1;return e[4]&&(n=parseFloat(e[4])),new T(t,i,s,n)}throw new Error("Invalid rgb/a string: "+t)}static fromHex(t){let e=null;if(e=t.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i)){const t=parseInt(e[1],16),i=parseInt(e[2],16),s=parseInt(e[3],16);let n=1;return e[4]&&(n=parseInt(e[4],16)/255),new T(t,i,s,n)}throw new Error("Invalid hex string: "+t)}static fromHSL(t,e,i,s=1){return new R(t,e,i,s).toRGBA()}lighten(t=.1){const e=R.fromRGBA(this.r,this.g,this.b,this.a);return e.l+=(1-e.l)*t,e.toRGBA()}darken(t=.1){const e=R.fromRGBA(this.r,this.g,this.b,this.a);return e.l-=e.l*t,e.toRGBA()}saturate(t=.1){const e=R.fromRGBA(this.r,this.g,this.b,this.a);return e.s+=e.s*t,e.toRGBA()}desaturate(t=.1){const e=R.fromRGBA(this.r,this.g,this.b,this.a);return e.s-=e.s*t,e.toRGBA()}multiply(t){const e=t.r/255*this.r/255*255,i=t.g/255*this.g/255*255,s=t.b/255*this.b/255*255,n=t.a*this.a;return new T(e,i,s,n)}mulitiply(t){return this.multiply(t)}screen(t){const e=t.invert(),i=t.invert();return e.multiply(i).invert()}invert(){return new T(255-this.r,255-this.g,255-this.b,1-this.a)}average(t){const e=(t.r+this.r)/2,i=(t.g+this.g)/2,s=(t.b+this.b)/2,n=(t.a+this.a)/2;return new T(e,i,s,n)}equal(t){return this.toString()===t.toString()}toString(t="rgb"){switch(t){case"rgb":return this.toRGBA();case"hsl":return this.toHSLA();case"hex":return this.toHex();default:throw new Error("Invalid Color format")}}_componentToHex(t){const e=t.toString(16);return 1===e.length?"0"+e:e}toHex(){return"#"+this._componentToHex(this.r)+this._componentToHex(this.g)+this._componentToHex(this.b)}toRGBA(){const t=String(this.r.toFixed(0))+", "+String(this.g.toFixed(0))+", "+String(this.b.toFixed(0));return void 0!==this.a||null!==this.a?"rgba("+t+", "+String(this.a)+")":"rgb("+t+")"}toHSLA(){return R.fromRGBA(this.r,this.g,this.b,this.a).toString()}fillStyle(){return this.toString()}clone(){return new T(this.r,this.g,this.b,this.a)}static get Black(){return T.fromHex("#000000")}static get White(){return T.fromHex("#FFFFFF")}static get Gray(){return T.fromHex("#808080")}static get LightGray(){return T.fromHex("#D3D3D3")}static get DarkGray(){return T.fromHex("#A9A9A9")}static get Yellow(){return T.fromHex("#FFFF00")}static get Orange(){return T.fromHex("#FFA500")}static get Red(){return T.fromHex("#FF0000")}static get Vermilion(){return T.fromHex("#FF5B31")}static get Vermillion(){return T.Vermilion}static get Rose(){return T.fromHex("#FF007F")}static get Magenta(){return T.fromHex("#FF00FF")}static get Violet(){return T.fromHex("#7F00FF")}static get Blue(){return T.fromHex("#0000FF")}static get Azure(){return T.fromHex("#007FFF")}static get Cyan(){return T.fromHex("#00FFFF")}static get Viridian(){return T.fromHex("#59978F")}static get Green(){return T.fromHex("#00FF00")}static get Chartreuse(){return T.fromHex("#7FFF00")}static get Transparent(){return T.fromHex("#FFFFFF00")}static get ExcaliburBlue(){return T.fromHex("#176BAA")}}E([b({message:"Alias for incorrect spelling used in older versions, use multiply instead, will be removed in v0.25.0"})],T.prototype,"mulitiply",null),E([b({message:"Alias for incorrect spelling used in older versions",alternateMethod:"Vermilion"})],T,"Vermillion",null);class R{constructor(t,e,i,s){this.h=t,this.s=e,this.l=i,this.a=s}static hue2rgb(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}static fromRGBA(t,e,i,s){t/=255,e/=255,i/=255;const n=Math.max(t,e,i),r=Math.min(t,e,i);let o,a;const h=(n+r)/2;if(n===r)o=a=0;else{const s=n-r;switch(a=h>.5?s/(2-n-r):s/(n+r),n){case t:o=(e-i)/s+(e<i?6:0);break;case e:o=(i-t)/s+2;break;case i:o=(t-e)/s+4}o/=6}return new R(o,a,h,s)}toRGBA(){let t,e,i;if(0===this.s)t=e=i=this.l;else{const s=this.l<.5?this.l*(1+this.s):this.l+this.s-this.l*this.s,n=2*this.l-s;t=R.hue2rgb(n,s,this.h+1/3),e=R.hue2rgb(n,s,this.h),i=R.hue2rgb(n,s,this.h-1/3)}return new T(255*t,255*e,255*i,this.a)}toString(){return`hsla(${this.h.toFixed(0)}, ${this.s.toFixed(0)}, ${this.l.toFixed(0)}, ${this.a.toFixed(0)})`}}!function(t){t.None="None",t.Top="Top",t.Bottom="Bottom",t.Left="Left",t.Right="Right"}(P||(P={})),function(t){t.getOpposite=function(e){return e===t.Top?t.Bottom:e===t.Bottom?t.Top:e===t.Left?t.Right:e===t.Right?t.Left:t.None},t.fromDirection=function(e){const i=[A.Left,A.Right,A.Up,A.Down],s=[t.Left,t.Right,t.Top,t.Bottom];let n=-Number.MAX_VALUE,r=-1;for(let t=0;t<i.length;t++)i[t].dot(e)>n&&(n=i[t].dot(e),r=t);return s[r]}}(P||(P={}));class B{constructor(t=0,e=0,i=0,s=0){"object"==typeof t?(this.left=t.left,this.top=t.top,this.right=t.right,this.bottom=t.bottom):"number"==typeof t&&(this.left=t,this.top=e,this.right=i,this.bottom=s)}static getSideFromIntersection(t){return t&&t?Math.abs(t.x)>Math.abs(t.y)?t.x<0?P.Right:P.Left:t.y<0?P.Bottom:P.Top:P.None}static fromPoints(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(let r=0;r<t.length;r++)t[r].x<e&&(e=t[r].x),t[r].x>s&&(s=t[r].x),t[r].y<i&&(i=t[r].y),t[r].y>n&&(n=t[r].y);return new B(e,i,s,n)}static fromDimension(t,e,i=A.Half,s=A.Zero){return new B(-t*i.x+s.x,-e*i.y+s.y,t-t*i.x+s.x,e-e*i.y+s.y)}get width(){return this.right-this.left}get height(){return this.bottom-this.top}hasZeroDimensions(){return 0===this.width||0===this.height}get center(){return new A((this.left+this.right)/2,(this.top+this.bottom)/2)}translate(t){return new B(this.left+t.x,this.top+t.y,this.right+t.x,this.bottom+t.y)}rotate(t,e=A.Zero){const i=this.getPoints().map((i=>i.rotate(t,e)));return B.fromPoints(i)}scale(t,e=A.Zero){const i=this.translate(e);return new B(i.left*t.x,i.top*t.y,i.right*t.x,i.bottom*t.y)}transform(t){const e=this.getPoints().map((e=>t.multv(e)));return B.fromPoints(e)}getPerimeter(){return 2*(this.width+this.height)}getPoints(){const t=[];return t.push(new A(this.left,this.top)),t.push(new A(this.right,this.top)),t.push(new A(this.right,this.bottom)),t.push(new A(this.left,this.bottom)),t}rayCast(t,e=1/0){let i=-1/0,s=1/0;const n=0===t.dir.x?Number.MAX_VALUE:1/t.dir.x,r=0===t.dir.y?Number.MAX_VALUE:1/t.dir.y,o=(this.left-t.pos.x)*n,a=(this.right-t.pos.x)*n;i=Math.min(o,a),s=Math.max(o,a);const h=(this.top-t.pos.y)*r,l=(this.bottom-t.pos.y)*r;return i=Math.max(i,Math.min(h,l)),s=Math.min(s,Math.max(h,l)),s>=Math.max(0,i)&&i<e}rayCastTime(t,e=1/0){let i=-1/0,s=1/0;const n=0===t.dir.x?Number.MAX_VALUE:1/t.dir.x,r=0===t.dir.y?Number.MAX_VALUE:1/t.dir.y,o=(this.left-t.pos.x)*n,a=(this.right-t.pos.x)*n;i=Math.min(o,a),s=Math.max(o,a);const h=(this.top-t.pos.y)*r,l=(this.bottom-t.pos.y)*r;return i=Math.max(i,Math.min(h,l)),s=Math.min(s,Math.max(h,l)),s>=Math.max(0,i)&&i<e?i:-1}contains(t){return t instanceof A?this.left<=t.x&&this.top<=t.y&&this.bottom>=t.y&&this.right>=t.x:t instanceof B&&(this.left<t.left&&this.top<t.top&&t.bottom<this.bottom&&t.right<this.right)}combine(t){return new B(Math.min(this.left,t.left),Math.min(this.top,t.top),Math.max(this.right,t.right),Math.max(this.bottom,t.bottom))}get dimensions(){return new A(this.width,this.height)}intersect(t){const e=this.combine(t);if(e.width<t.width+this.width&&e.height<t.height+this.height&&!e.dimensions.equals(t.dimensions)&&!e.dimensions.equals(this.dimensions)){let e=0;e=this.right>=t.left&&this.right<=t.right?t.left-this.right:t.right-this.left;let i=0;return i=this.top<=t.bottom&&this.top>=t.top?t.bottom-this.top:t.top-this.bottom,Math.abs(e)<Math.abs(i)?new A(e,0):new A(0,i)}if(e.dimensions.equals(t.dimensions)||e.dimensions.equals(this.dimensions)){let e=0;e=this.width-t.width>=0?this.right-t.right<=t.left-this.left?t.left-this.right:t.right-this.left:t.right-this.right<=this.left-t.left?this.left-t.right:this.right-t.left;let i=0;return i=this.height-t.height>=0?this.bottom-t.bottom<=t.top-this.top?t.top-this.bottom:t.bottom-this.top:t.bottom-this.bottom<=this.top-t.top?this.top-t.bottom:this.bottom-t.top,Math.abs(e)<Math.abs(i)?new A(e,0):new A(0,i)}return null}intersectWithSide(t){const e=this.intersect(t);return B.getSideFromIntersection(e)}debugDraw(t,e=T.Yellow){t.strokeStyle=e.toString(),t.strokeRect(this.left,this.top,this.width,this.height)}draw(t,e=T.Yellow){t.debug.drawRect(this.left,this.top,this.width,this.height,{color:e})}}const D=4294967295;class M{constructor(t){this.seed=t,this._lowerMask=2147483647,this._upperMask=2147483648,this._w=32,this._n=624,this._m=397,this._a=2567483615,this._u=11,this._s=7,this._b=2636928640,this._t=15,this._c=4022730752,this._l=18,this._f=1812433253,this._mt=new Array(this._n),this._mt[0]=(t||Date.now())>>>0;for(let t=1;t<this._n;t++){const e=this._mt[t-1]^this._mt[t-1]>>>this._w-2;this._mt[t]=(this._f*((4294901760&e)>>>16)<<16)+this._f*(65535&e)+t>>>0}this._index=this._n}_twist(){const t=[0,this._a];let e=0,i=0;for(;i<this._n-this._m;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+this._m]^e>>>1^t[1&e]&D;for(;i<this._n-1;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+(this._m-this._n)]^e>>>1^t[1&e]&D;e=this._mt[this._n-1]&this._upperMask|this._mt[0]&this._lowerMask,this._mt[this._n-1]=this._mt[this._m-1]^e>>>1^t[1&e]&D,this._index=0}nextInt(){this._index>=this._n&&this._twist();let t=this._mt[this._index++];return t^=t>>>this._u,t^=t<<this._s&this._b,t^=t<<this._t&this._c,t^=t>>>this._l,t>>>0}next(){return this.nextInt()*(1/4294967296)}floating(t,e){return(e-t)*this.next()+t}integer(t,e){return Math.floor((e-t+1)*this.next()+t)}bool(t=.5){return this.next()<=t}pickOne(t){return t[this.integer(0,t.length-1)]}pickSet(t,e,i=!1){return i?this._pickSetWithDuplicates(t,e):this._pickSetWithoutDuplicates(t,e)}_pickSetWithoutDuplicates(t,e){if(e>t.length||e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 < n <= length");if(e===t.length)return t;const i=new Array(e);let s=0;const n=t.slice(0);for(;s<e;){const t=this.integer(0,n.length-1);i[s++]=n[t],n.splice(t,1)}return i}_pickSetWithDuplicates(t,e){if(e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 <= n < MAX_INT");const i=new Array(e);for(let s=0;s<e;s++)i[s]=this.pickOne(t);return i}shuffle(t){const e=t.slice(0);let i=null;for(let t=0;t<e.length-2;t++){const s=this.integer(t,e.length-1);i=e[t],e[t]=e[s],e[s]=i}return e}range(t,e,i){const s=new Array(t);for(let n=0;n<t;n++)s[n]=this.integer(e,i);return s}d4(){return this.integer(1,4)}d6(){return this.integer(1,6)}d8(){return this.integer(1,8)}d10(){return this.integer(1,10)}d12(){return this.integer(1,12)}d20(){return this.integer(1,20)}}const F=2*Math.PI;function k(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i="",s=0;for(;s<t.length;){const n=255&t.charCodeAt(s++),r=255&t.charCodeAt(s++),o=255&t.charCodeAt(s++),a=n>>2,h=(3&n)<<4|r>>4;let l,c;isNaN(r)?l=c=64:(l=(15&r)<<2|o>>6,c=isNaN(o)?64:63&o),i+=e.charAt(a)+e.charAt(h)+e.charAt(l)+e.charAt(c)}return i}function I(t,e){return null!=t?t:e}function L(t,e,i){return Math.min(Math.max(e,t),i)}function O(t,e,i=new M){return i?i.floating(t,e):t+Math.random()*(e-t)}function z(t,e,i=new M){return i?i.integer(t,e):Math.round(O(t,e))}function U(t){let e=t;if(t>F)for(;e>F;)e-=F;if(t<0)for(;e<0;)e+=F;return e}function H(t){return 180/Math.PI*t}function N(t){return t/180*Math.PI}function W(t){let e=0,i=0;const s=t=>{e+=t.offsetLeft,t.offsetParent&&s(t.offsetParent)},n=t=>{i+=t.offsetTop,t.offsetParent&&n(t.offsetParent)};return s(t),n(t),new A(e,i)}function V(t,e){return-1===e.indexOf(t)&&(e.push(t),!0)}function G(t,e){let i=-1;return(i=e.indexOf(t))>-1&&(e.splice(i,1),!0)}function j(t,e){for(let i=0;i<t.length;i++)if(t[i]===e)return!0;return!1}function X(t){return t===P.Top?P.Bottom:t===P.Bottom?P.Top:t===P.Left?P.Right:t===P.Right?P.Left:P.None}function q(t){const e=[A.Left,A.Right,A.Up,A.Down],i=[P.Left,P.Right,P.Top,P.Bottom];let s=-Number.MAX_VALUE,n=-1;for(let i=0;i<e.length;i++)e[i].dot(t)>s&&(s=e[i].dot(t),n=i);return i[n]}class K{constructor(t=K.DefaultSize){this._internalArray=null,this._endPointer=0,this._internalArray=new Array(t)}_resize(){const t=2*this._internalArray.length,e=new Array(t),i=this.count();for(let t=0;t<i;t++)e[t]=this._internalArray[t];delete this._internalArray,this._internalArray=e}push(t){return this._endPointer===this._internalArray.length&&this._resize(),this._internalArray[this._endPointer++]=t}pop(){return this._endPointer=this._endPointer-1<0?0:this._endPointer-1,this._internalArray[this._endPointer]}count(){return this._endPointer}clear(){this._endPointer=0}internalSize(){return this._internalArray.length}elementAt(t){if(t>=this.count())throw new Error("Invalid index "+t);return this._internalArray[t]}insert(t,e){return t>=this.count()&&this._resize(),this._internalArray[t]=e}remove(t){const e=this.count();if(0===e)throw new Error("Invalid parameter "+t);const i=this._internalArray[t];for(let i=t;i<e;i++)this._internalArray[i]=this._internalArray[i+1];return this._endPointer--,i}removeElement(t){const e=this._internalArray.indexOf(t);this.remove(e)}toArray(){return this._internalArray.slice(0,this._endPointer)}forEach(t){let e=0;const i=this.count();for(;e<i;e++)t.call(this,this._internalArray[e],e)}map(t){const e=this.count();for(let i=0;i<e;i++)this._internalArray[i]=t.call(this,this._internalArray[i],i)}}function Z(t){throw new Error(t)}K.DefaultSize=200;const Y=(t,e)=>Array.from(new Array(e-t+1),((e,i)=>i+t));function Q(t){return new Promise((e=>{setTimeout((()=>{e()}),t)}))}var $;!function(t){t[t.X=12]="X",t[t.Y=13]="Y"}($||($={}));const J=t=>0===t?0:t<0?-1:1;class tt{constructor(){this.data=new Float32Array(16),this._scaleSignX=1,this._scaleSignY=1}static ortho(t,e,i,s,n,r){const o=new tt;return o.data[0]=2/(e-t),o.data[1]=0,o.data[2]=0,o.data[3]=0,o.data[4]=0,o.data[5]=2/(s-i),o.data[6]=0,o.data[7]=0,o.data[8]=0,o.data[9]=0,o.data[10]=-2/(r-n),o.data[11]=0,o.data[12]=-(e+t)/(e-t),o.data[13]=-(s+i)/(s-i),o.data[14]=-(r+n)/(r-n),o.data[15]=1,o}clone(){const t=new tt;return t.data[0]=this.data[0],t.data[1]=this.data[1],t.data[2]=this.data[2],t.data[3]=this.data[3],t.data[4]=this.data[4],t.data[5]=this.data[5],t.data[6]=this.data[6],t.data[7]=this.data[7],t.data[8]=this.data[8],t.data[9]=this.data[9],t.data[10]=this.data[10],t.data[11]=this.data[11],t.data[12]=this.data[12],t.data[13]=this.data[13],t.data[14]=this.data[14],t.data[15]=this.data[15],t}static identity(){const t=new tt;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}static translation(t,e){const i=tt.identity();return i.data[12]=t,i.data[13]=e,i}static scale(t,e){const i=tt.identity();return i.data[0]=t,i.data[5]=e,i.data[10]=1,i.data[15]=1,i}static rotation(t){const e=tt.identity();return e.data[0]=Math.cos(t),e.data[4]=-Math.sin(t),e.data[1]=Math.sin(t),e.data[5]=Math.cos(t),e}multv(t){if(t instanceof A)return new A(t.x*this.data[0]+t.y*this.data[4]+0*this.data[6]+1*this.data[12],t.x*this.data[1]+t.y*this.data[5]+0*this.data[9]+1*this.data[13]);return[t[0]*this.data[0]+t[1]*this.data[4]+0*this.data[6]+1*this.data[12],t[0]*this.data[1]+t[1]*this.data[5]+0*this.data[9]+1*this.data[13]]}multm(t){const e=new tt,i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=this.data[8],d=this.data[9],u=this.data[10],p=this.data[11],g=this.data[12],_=this.data[13],f=this.data[14],m=this.data[15],y=t.data[0],w=t.data[1],v=t.data[2],x=t.data[3],b=t.data[4],C=t.data[5],A=t.data[6],S=t.data[7],P=t.data[8],E=t.data[9],T=t.data[10],R=t.data[11],B=t.data[12],D=t.data[13],M=t.data[14],F=t.data[15];e.data[0]=i*y+o*w+c*v+g*x,e.data[1]=s*y+a*w+d*v+_*x,e.data[2]=n*y+h*w+u*v+f*x,e.data[3]=r*y+l*w+p*v+m*x,e.data[4]=i*b+o*C+c*A+g*S,e.data[5]=s*b+a*C+d*A+_*S,e.data[6]=n*b+h*C+u*A+f*S,e.data[7]=r*b+l*C+p*A+m*S,e.data[8]=i*P+o*E+c*T+g*R,e.data[9]=s*P+a*E+d*T+_*R,e.data[10]=n*P+h*E+u*T+f*R,e.data[11]=r*P+l*E+p*T+m*R,e.data[12]=i*B+o*D+c*M+g*F,e.data[13]=s*B+a*D+d*M+_*F,e.data[14]=n*B+h*D+u*M+f*F,e.data[15]=r*B+l*D+p*M+m*F;const k=this.getScale();return e._scaleSignX=J(k.x)*J(e._scaleSignX),e._scaleSignY=J(k.y)*J(e._scaleSignY),e}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=this.data[8],d=this.data[9],u=this.data[10],p=this.data[11],g=this.data[12],_=this.data[13],f=this.data[14],m=this.data[15];return this.data[12]=i*t+o*e+0*c+1*g,this.data[13]=s*t+a*e+0*d+1*_,this.data[14]=n*t+h*e+0*u+1*f,this.data[15]=r*t+l*e+0*p+1*m,this}setPosition(t,e){this.data[12]=t,this.data[13]=e}getPosition(){return S(this.data[12],this.data[13])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],r=this.data[4],o=this.data[5],a=this.data[6],h=this.data[7],l=Math.sin(t),c=Math.cos(t);return this.data[0]=c*e+l*r,this.data[1]=c*i+l*o,this.data[2]=c*s+l*a,this.data[3]=c*n+l*h,this.data[4]=c*r-l*e,this.data[5]=c*o-l*i,this.data[6]=c*a-l*s,this.data[7]=c*h-l*n,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*t,this.data[3]=r*t,this.data[4]=o*e,this.data[5]=a*e,this.data[6]=h*e,this.data[7]=l*e,this}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[4]=-i*e.x,this.data[5]=s*e.y}getRotation(){return U(Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX()))}getScaleX(){const t=S(this.data[0],this.data[4]).size;return this._scaleSignX*t}getScaleY(){const t=S(this.data[1],this.data[5]).size;return this._scaleSignY*t}getScale(){return S(this.getScaleX(),this.getScaleY())}setScaleX(t){this._scaleSignX=J(t);const e=S(this.data[0]*this._scaleSignX,this.data[4]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[4]=e.y*t}setScaleY(t){this._scaleSignY=J(t);const e=S(this.data[1]*this._scaleSignY,this.data[5]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[5]=e.y*t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}getBasisDeterminant(){return this.data[0]*this.data[5]-this.data[1]*this.data[4]}getAffineInverse(){const t=1/this.getBasisDeterminant(),e=this.data[0],i=this.data[4],s=this.data[1],n=this.data[5],r=tt.identity();r.data[0]=n*t,r.data[1]=-s*t,r.data[4]=-i*t,r.data[5]=e*t;const o=this.data[12],a=this.data[13];return r.data[12]=-(o*r.data[0]+a*r.data[4]),r.data[13]=-(o*r.data[1]+a*r.data[5]),r}isIdentity(){return 1===this.data[0]&&0===this.data[1]&&0===this.data[2]&&0===this.data[3]&&0===this.data[4]&&1===this.data[5]&&0===this.data[6]&&0===this.data[7]&&0===this.data[8]&&0===this.data[9]&&1===this.data[10]&&0===this.data[11]&&0===this.data[12]&&0===this.data[13]&&0===this.data[14]&&1===this.data[15]}toString(){return`\n[${this.data[0]} ${this.data[4]} ${this.data[8]} ${this.data[12]}]\n[${this.data[1]} ${this.data[5]} ${this.data[9]} ${this.data[13]}]\n[${this.data[2]} ${this.data[6]} ${this.data[10]} ${this.data[14]}]\n[${this.data[3]} ${this.data[7]} ${this.data[11]} ${this.data[15]}]\n`}}class et{constructor(){this._transforms=[],this._currentTransform=tt.identity()}save(){this._transforms.push(this._currentTransform),this._currentTransform=this._currentTransform.clone()}restore(){this._currentTransform=this._transforms.pop()}translate(t,e){return this._currentTransform.translate(t,e)}rotate(t){return this._currentTransform.rotate(t)}scale(t,e){return this._currentTransform.scale(t,e)}set current(t){this._currentTransform=t}get current(){return this._currentTransform}}class it{constructor(){this._states=[],this._currentState=this._getDefaultState()}_getDefaultState(){return{opacity:1}}_cloneState(){return{opacity:this._currentState.opacity}}save(){this._states.push(this._currentState),this._currentState=this._cloneState()}restore(){this._currentState=this._states.pop()}get current(){return this._currentState}}class st{constructor(t,e,i){this._gl=t,this._vertexSource=e,this._fragmentSource=i,this.program=null,this.uniforms={},this.attributes={},this.layout=[],this.compile(t)}_createProgram(t,e,i){const s=t.createProgram();if(null===s)throw Error("Could not create graphics shader program");t.attachShader(s,e),t.attachShader(s,i),t.linkProgram(s);if(!t.getProgramParameter(s,t.LINK_STATUS))throw Error(`Could not link the program: [${t.getProgramInfoLog(s)}]`);return s}_compileShader(t,e,i){const s=t.createShader(i);if(null===s)throw Error(`Could not build shader: [${e}]`);t.shaderSource(s,e),t.compileShader(s);if(!t.getShaderParameter(s,t.COMPILE_STATUS))throw Error(`Could not compile shader [${t.getShaderInfoLog(s)}]`);return s}compile(t){const e=this._compileShader(t,this._vertexSource,t.VERTEX_SHADER),i=this._compileShader(t,this._fragmentSource,t.FRAGMENT_SHADER),s=this._createProgram(t,e,i);return this.program=s}addUniformMatrix(t,e){if(!e)throw Error(`Shader Uniform Matrix '${t}' was set to null or undefined`);const i=this._gl;this.uniforms[t]={name:t,type:"matrix",location:i.getUniformLocation(this.program,t),data:e}}addUniformIntegerArray(t,e){if(!e)throw Error(`Shader Uniform Integery Array '${t}' was set to null or undefined`);const i=this._gl;this.uniforms[t]={name:t,type:"numbers",location:i.getUniformLocation(this.program,t),data:e}}addAttribute(t,e,i,s=!1){const n=this._gl.getAttribLocation(this.program,t);this.attributes[t]={name:t,size:e,glType:i,normalized:s,location:n},this.layout.push(this.attributes[t])}get vertexAttributeSize(){let t=0;for(const e of this.layout)t+=e.size;return t}get totalVertexSizeBytes(){let t=0;for(const e of this.layout){let i=1;if(e.glType===this._gl.FLOAT)i=4;else i=1;t+=i*e.size}return t}getAttributeSize(t){let e=1;if(this.attributes[t].glType===this._gl.FLOAT)e=4;else e=1;return e*this.attributes[t].size}use(){const t=this._gl;t.useProgram(this.program);let e=0;for(const i of this.layout)t.vertexAttribPointer(i.location,i.size,i.glType,i.normalized,this.totalVertexSizeBytes,e),t.enableVertexAttribArray(i.location),e+=this.getAttributeSize(i.name);for(const e in this.uniforms){const i=this.uniforms[e];switch(i.type){case"matrix":t.uniformMatrix4fv(i.location,!1,i.data);break;case"numbers":t.uniform1iv(i.location,i.data)}}}}class nt{constructor(t){this.max=t,this._pool=void 0,this.commands=[]}isFull(){return this.commands.length>=this.max}canAdd(){return!this.isFull()}add(t){this.commands.push(t)}dispose(){return this.commands.length=0,this}}class rt{static clear(){rt.DrawCallCount=0,rt.DrawnImagesCount=0}}rt.DrawCallCount=0,rt.DrawnImagesCount=0;class ot{constructor(t,e,i=100){this.builder=t,this.recycler=e,this.maxObjects=i,this.totalAllocations=0,this.index=0,this.objects=[],this._logger=_.getInstance()}using(t){const e=t(this);return e?this.done(...e):this.done()}borrow(t){t(this.get()),this.index--}get(...t){if(this.index===this.maxObjects&&(this._logger.warn("Max pooled objects reached, possible memory leak? Doubling"),this.maxObjects=2*this.maxObjects),this.objects[this.index])return this.recycler(this.objects[this.index++],...t);{this.totalAllocations++;const e=this.objects[this.index++]=this.builder(...t);return e._pool=this,e}}done(...t){this.index=0;for(const e of t){const t=this.objects.indexOf(e);this.objects[t]=this.builder(),this.objects[t]._pool=this,this.totalAllocations++,e._pool=void 0}return t}}class at{constructor(t){var e,i,s;this.priority=0,this._buffer=null,this._maxCommandsPerBatch=2e3,this._batches=[],this._gl=t.gl;const n=t.command;this._verticesPerCommand=null!==(e=null==t?void 0:t.verticesPerCommand)&&void 0!==e?e:1,this._maxCommandsPerBatch=null!==(i=null==t?void 0:t.maxCommandsPerBatch)&&void 0!==i?i:this._maxCommandsPerBatch;const r=null!==(s=null==t?void 0:t.batchFactory)&&void 0!==s?s:()=>new nt(this._maxCommandsPerBatch);this.commands=new ot((()=>new n),(t=>t.dispose()),this._maxCommandsPerBatch),this._batchPool=new ot(r,(t=>t.dispose()),100)}init(){const t=this._gl;this.shader=this.buildShader(t),this._vertices=new Float32Array(this.shader.vertexAttributeSize*this._verticesPerCommand*this._maxCommandsPerBatch),this._buffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._buffer),t.bufferData(t.ARRAY_BUFFER,this._vertices,t.DYNAMIC_DRAW)}get vertexSize(){return this.shader.vertexAttributeSize}addCommand(t){0===this._batches.length&&this._batches.push(this._batchPool.get());const e=this._batches[this._batches.length-1];if(e.canAdd())e.add(t);else{const e=this._batchPool.get();e.add(t),this._batches.push(e)}}render(){const t=this._gl;t.bindBuffer(t.ARRAY_BUFFER,this._buffer),this.shader.use();let e=0,i=0;for(const s of this._batches){const n=this.buildBatchVertices(this._vertices,s);t.bufferSubData(t.ARRAY_BUFFER,0,this._vertices),this.renderBatch(t,s,n),i+=s.commands.length,e++}this.commands.done(),this._batchPool.done(),this._batches.length=0,rt.DrawCallCount+=e,rt.DrawnImagesCount+=i}}class ht{constructor(){this.color=T.Black,this.start=A.Zero,this.end=A.Zero}dispose(){return this.color.r=0,this.color.g=0,this.color.b=0,this.color.a=1,this.start.setTo(0,0),this.end.setTo(0,0),this}}class lt extends at{constructor(t,e){super({gl:t,command:ht,verticesPerCommand:2}),this._contextInfo=e,this.init()}buildShader(t){const e=new st(t,"attribute vec4 a_position;\nattribute vec4 a_color;\n\nvarying lowp vec4 v_color;\n\nuniform mat4 u_matrix;\n\n\nvoid main() {\n // Set the vertex position using the ortho transform matrix\n gl_Position = u_matrix * a_position;\n\n // Passthrough the color\n v_color = a_color;\n}","precision mediump float;\n\n// Color\nvarying lowp vec4 v_color;\n\n\nvoid main() {\n gl_FragColor = v_color;\n}");return e.addAttribute("a_position",2,t.FLOAT),e.addAttribute("a_color",4,t.FLOAT),e.addUniformMatrix("u_matrix",this._contextInfo.matrix.data),e}addLine(t,e,i){const s=this.commands.get();s.start=this._contextInfo.transform.current.multv(t),s.end=this._contextInfo.transform.current.multv(e),s.color.r=i.r,s.color.g=i.g,s.color.b=i.b,s.color.a=s.color.a*this._contextInfo.state.current.opacity,this.addCommand(s)}buildBatchVertices(t,e){let i=0;for(const s of e.commands)t[i++]=s.start.x,t[i++]=s.start.y,t[i++]=s.color.r/255,t[i++]=s.color.g/255,t[i++]=s.color.b/255,t[i++]=s.color.a,t[i++]=s.end.x,t[i++]=s.end.y,t[i++]=s.color.r/255,t[i++]=s.color.g/255,t[i++]=s.color.b/255,t[i++]=s.color.a;return i/this.vertexSize}renderBatch(t,e,i){t.drawArrays(t.LINES,0,i)}}var ct;!function(t){t.Image="image",t.Line="line",t.Rectangle="rectangle",t.Circle="circle"}(ct||(ct={}));class dt{constructor(t,e,i,s,n,r,o,a,h){this._pool=void 0,this.snapToPixel=!0,this.type=ct.Image,this.opacity=1,this.width=0,this.height=0,this.dest=[0,0],this.view=[0,0,0,0],this._geom=[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],this.init(t,e,i,s,n,r,o,a,h)}init(t,e,i,s,n,r,o,a,h){this.type=ct.Image,this.image=t,this.width=(null==t?void 0:t.width)||s||0,this.height=(null==t?void 0:t.height)||n||0,this.view=[0,0,null!=s?s:null==t?void 0:t.width,null!=n?n:null==t?void 0:t.height],this.dest=[e,i],void 0!==r&&void 0!==o&&void 0!==a&&void 0!==h&&(this.view=[e,i,null!=s?s:null==t?void 0:t.width,null!=n?n:null==t?void 0:t.height],this.dest=[r,o],this.width=a,this.height=h);let l=0;if(this._geom[l++]=[this.dest[0],this.dest[1]],this._geom[l++]=[this.dest[0],this.dest[1]+this.height],this._geom[l++]=[this.dest[0]+this.width,this.dest[1]],this._geom[l++]=[this.dest[0]+this.width,this.dest[1]],this._geom[l++]=[this.dest[0],this.dest[1]+this.height],this._geom[l++]=[this.dest[0]+this.width,this.dest[1]+this.height],this.snapToPixel)for(const t of this._geom)t[0]=~~t[0],t[1]=~~t[1];return this}initRect(t,e,i,s){this.type=ct.Rectangle,this.color=t,this.width=i,this.height=s;let n=0;if(this._geom[n++]=[e.x,e.y],this._geom[n++]=[e.x,e.y+this.height],this._geom[n++]=[e.x+this.width,e.y],this._geom[n++]=[e.x+this.width,e.y],this._geom[n++]=[e.x,e.y+this.height],this._geom[n++]=[e.x+this.width,e.y+this.height],this.snapToPixel)for(const t of this._geom)t[0]=~~t[0],t[1]=~~t[1];return this}initLine(t,e,i,s){this.type=ct.Line,this.color=t;const n=i.sub(e).normalize().perpendicular(),r=s/2,o=n.scale(r).add(e),a=n.scale(-r).add(e),h=n.scale(r).add(i),l=n.scale(-r).add(i);let c=0;if(this._geom[c++]=[o.x,o.y],this._geom[c++]=[h.x,h.y],this._geom[c++]=[a.x,a.y],this._geom[c++]=[a.x,a.y],this._geom[c++]=[h.x,h.y],this._geom[c++]=[l.x,l.y],this.snapToPixel)for(const t of this._geom)t[0]=~~t[0],t[1]=~~t[1];return this}initCircle(t,e,i){this.type=ct.Circle,this.color=i;const s=t.add(S(-e,-e)),n=t.add(S(e,-e)),r=t.add(S(e,e)),o=t.add(S(-e,e));let a=0;if(this._geom[a++]=[s.x,s.y],this._geom[a++]=[n.x,n.y],this._geom[a++]=[o.x,o.y],this._geom[a++]=[o.x,o.y],this._geom[a++]=[n.x,n.y],this._geom[a++]=[r.x,r.y],this.snapToPixel)for(const t of this._geom)t[0]=~~t[0],t[1]=~~t[1];return this}dispose(){this.image=null,this.width=0,this.height=0,this.view=[0,0,0,0],this.dest=[0,0];let t=0;return this._geom[t++]=[this.dest[0],this.dest[1]],this._geom[t++]=[this.dest[0],this.dest[1]+this.height],this._geom[t++]=[this.dest[0]+this.width,this.dest[1]],this._geom[t++]=[this.dest[0]+this.width,this.dest[1]],this._geom[t++]=[this.dest[0],this.dest[1]+this.height],this._geom[t++]=[this.dest[0]+this.width,this.dest[1]+this.height],this}applyTransform(t,e){if(t)for(let e=0;e<this._geom.length;e++)this._geom[e]=t.multv(this._geom[e]),this.snapToPixel&&(this._geom[e]=[~~this._geom[e][0],~~this._geom[e][1]]);this.opacity=e}get geometry(){return this._geom}}function ut(t){return 0==(t&t-1)}function pt(t){return ut(t)?t:function(t){--t;for(let e=1;e<32;e<<=1)t|=t>>e;return t+1}(t)}class gt{static registerContext(t){gt._GL=t}static get(t){return gt._TEXTURE_MAP.get(t)}static has(t){return gt._TEXTURE_MAP.has(t)}static load(t,e=!1){const i=gt._GL;if(!i)return null;let s=null;if(gt.has(t)&&(s=gt.get(t)),s){if(e){i.bindTexture(i.TEXTURE_2D,s);const e=gt.toPowerOfTwoImage(t);i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,e)}return s}s=i.createTexture();const n=gt.toPowerOfTwoImage(t);return i.bindTexture(i.TEXTURE_2D,s),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,n),gt._TEXTURE_MAP.set(t,s),s}static toPowerOfTwoImage(t){const e=gt._POT_CANVAS,i=gt._POT_CTX;return ut(t.width)&&ut(t.height)||(e.width=pt(t.width),e.height=pt(t.height),i.imageSmoothingEnabled=!1,i.clearRect(0,0,e.width,e.height),i.drawImage(t,0,0,t.width,t.height),t=e),t}}gt._POT_CANVAS=document.createElement("canvas"),gt._POT_CTX=gt._POT_CANVAS.getContext("2d"),gt._TEXTURE_MAP=new Map;class _t extends nt{constructor(t,e){super(t),this.maxDraws=t,this.maxTextures=e,this.textures=[],this.commands=[],this._graphicMap={}}isFull(){return this.commands.length>=this.maxDraws||this.textures.length>=this.maxTextures}canAdd(){return!(this.commands.length>=this.maxDraws)&&this.textures.length<this.maxTextures}_isCommandFull(){return this.commands.length>=this.maxDraws}_isTextureFull(){return this.textures.length>=this.maxTextures}_wouldAddTexture(t){return!this._graphicMap[t.image.id]}maybeAdd(t){return(!this._isCommandFull()&&!this._isTextureFull()||!this._wouldAddTexture(t))&&(this.add(t),!0)}add(t){if(t.type===ct.Image){const e=gt.load(t.image);-1===this.textures.indexOf(e)&&this.textures.push(e)}this.commands.push(t)}bindTextures(t){for(let e=0;e<this.maxTextures;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this.textures[e]||this.textures[0])}getBatchTextureId(t){return t.image?this.textures.indexOf(gt.get(t.image)):-1}dispose(){return this.clear(),this}clear(){this.commands.length=0,this.textures.length=0,this._graphicMap={}}}class ft extends at{constructor(t,e){super({gl:t,command:dt,verticesPerCommand:6,maxCommandsPerBatch:2e3,batchFactory:()=>new _t(2e3,t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS))}),this._contextInfo=e,gt.registerContext(t),this.init()}buildShader(t){const e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),i=new st(t,"attribute vec4 a_position;\n\n// Opacity \nattribute float a_opacity;\nvarying float v_opacity;\n\nattribute vec4 a_color;\nvarying vec4 v_color;\n\n// UV coordinate\nattribute vec2 a_texcoord;\nvarying vec2 v_texcoord;\n\n// Texture number\nattribute lowp float a_textureIndex;\nvarying lowp float v_textureIndex;\n\nuniform mat4 u_matrix;\n\n\nvoid main() {\n // Set the vertex position using the ortho transform matrix\n gl_Position = u_matrix * a_position;\n\n // Pass through the Opacity to the fragment shader\n v_opacity = a_opacity;\n // Pass through the UV coord to the fragment shader\n v_texcoord = a_texcoord;\n // Pass through the texture number to the fragment shader\n v_textureIndex = a_textureIndex;\n // Pass through the color to the fragment shader\n v_color = a_color;\n}",this._transformFragmentSource("#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision mediump float;\n\n// UV coord\nvarying vec2 v_texcoord;\n\n// Texture index\nvarying lowp float v_textureIndex;\n\n// Color coord to blend with image\nvarying lowp vec4 v_color;\n\n// Opacity\nvarying float v_opacity;\n\nuniform sampler2D u_textures[%%count%%];\n\nfloat circle(in vec2 st, in float radius) {\n vec2 dist = st - vec2(0.5);\n float r = dot(dist, dist) * 4.0;\n float delta = fwidth(r);\n return 1.0 - smoothstep(radius - delta, radius + delta, r);\n}\n\nvoid main() {\n float r = 0.0, delta = 0.0, alpha = 1.0;\n // In order to support the most efficient sprite batching, we have multiple\n // textures loaded into the gpu (usually 8) this picker logic skips over textures\n // that do not apply to a particular sprite.\n\n vec4 color;\n // -1 If there is no texture to sample we are drawing a solid geometry (rectangles)\n if (v_textureIndex == -1.0) {\n color = v_color;\n color.w = color.w * v_opacity;\n // -2 If there is no texture we are drawing a circle\n } else if (v_textureIndex == -2.0) {\n color = v_color;\n color.a = color.a * circle(v_texcoord, .95);\n } else {\n // GLSL is templated out to pick the right texture and set the vec4 color\n %%texture_picker%%\n }\n color.w = color.w * v_opacity;\n gl_FragColor = color;\n}",e));return i.addAttribute("a_position",3,t.FLOAT),i.addAttribute("a_texcoord",2,t.FLOAT),i.addAttribute("a_textureIndex",1,t.FLOAT),i.addAttribute("a_opacity",1,t.FLOAT),i.addAttribute("a_color",4,t.FLOAT),i.addUniformMatrix("u_matrix",this._contextInfo.matrix.data),i.addUniformIntegerArray("u_textures",[...Array(e)].map(((t,e)=>e))),i}_transformFragmentSource(t,e){let i=t.replace("%%count%%",e.toString()),s="";for(let t=0;t<e;t++)s+=0===t?`if (v_textureIndex <= ${t}.5) {\n`:` else if (v_textureIndex <= ${t}.5) {\n`,s+=` color = texture2D(u_textures[${t}], v_texcoord);\n`,s+=" }\n";return i=i.replace("%%texture_picker%%",s),i}addCircle(t,e,i){const s=this.commands.get().initCircle(t,e,i);s.applyTransform(this._contextInfo.transform.current,this._contextInfo.state.current.opacity),this.addCommand(s)}addRectangle(t,e,i,s){const n=this.commands.get().initRect(t,e,i,s);n.applyTransform(this._contextInfo.transform.current,this._contextInfo.state.current.opacity),this.addCommand(n)}addLine(t,e,i,s=1){const n=this.commands.get().initLine(t,e,i,s);n.applyTransform(this._contextInfo.transform.current,this._contextInfo.state.current.opacity),this.addCommand(n)}addImage(t,e,i,s,n,r,o,a,h){const l=this.commands.get().init(t,e,i,s,n,r,o,a,h);l.applyTransform(this._contextInfo.transform.current,this._contextInfo.state.current.opacity),this.addCommand(l)}renderBatch(t,e,i){e.bindTextures(t),t.drawArrays(t.TRIANGLES,0,i)}buildBatchVertices(t,e){var i,s;let n=0,r=0,o=0,a=0,h=0,l=1,c=1,d=0,u=T.Transparent;for(const p of e.commands){r=p.view[0],o=p.view[1],a=p.view[2],h=p.view[3],l=pt((null===(i=p.image)||void 0===i?void 0:i.width)||p.width),c=pt((null===(s=p.image)||void 0===s?void 0:s.height)||p.height),d=e.getBatchTextureId(p),p.type!==ct.Line&&p.type!==ct.Rectangle||(d=-1,u=p.color),p.type===ct.Circle&&(d=-2,u=p.color);let g=r/l,_=o/c,f=(r+a)/l,m=(o+h)/c;-2===d&&(g=0,_=0,f=1,m=1),t[n++]=p.geometry[0][0],t[n++]=p.geometry[0][1],t[n++]=0,t[n++]=g,t[n++]=_,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[1][0],t[n++]=p.geometry[1][1],t[n++]=0,t[n++]=g,t[n++]=m,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[2][0],t[n++]=p.geometry[2][1],t[n++]=0,t[n++]=f,t[n++]=_,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[3][0],t[n++]=p.geometry[3][1],t[n++]=0,t[n++]=f,t[n++]=_,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[4][0],t[n++]=p.geometry[4][1],t[n++]=0,t[n++]=g,t[n++]=m,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[5][0],t[n++]=p.geometry[5][1],t[n++]=0,t[n++]=f,t[n++]=m,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a}return n/this.vertexSize}}class mt{constructor(){this.point=A.Zero,this.color=T.Black,this.size=1}dispose(){return this.point.setTo(0,0),this.color.r=0,this.color.g=0,this.color.b=0,this.color.a=1,this.size=1,this}}class yt extends at{constructor(t,e){super({gl:t,command:mt,verticesPerCommand:1}),this._contextInfo=e,this.init()}buildShader(t){t.getExtension("OES_standard_derivatives");const e=new st(t,"attribute vec4 a_position;\nattribute vec4 a_color;\nattribute float a_size;\nvarying lowp vec4 v_color;\nuniform mat4 u_matrix;\n\nvoid main() {\n gl_Position = u_matrix * a_position;\n gl_PointSize = a_size * 2.0;\n v_color = a_color;\n}","#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n\nprecision mediump float;\nvarying lowp vec4 v_color;\n\nvoid main() {\n float r = 0.0, delta = 0.0, alpha = 1.0;\n vec2 cxy = 2.0 * gl_PointCoord - 1.0;\n r = dot(cxy, cxy);\n \n#ifdef GL_OES_standard_derivatives\n delta = fwidth(r);\n alpha = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r);\n#else\n if (r > 1.0) {\n discard;\n }\n#endif\n gl_FragColor = vec4(v_color.rgb, v_color.a * alpha);\n}");return e.addAttribute("a_position",2,t.FLOAT),e.addAttribute("a_color",4,t.FLOAT),e.addAttribute("a_size",1,t.FLOAT),e.addUniformMatrix("u_matrix",this._contextInfo.matrix.data),e}addPoint(t,e,i){const s=this.commands.get();s.point=this._contextInfo.transform.current.multv(t),s.color.r=e.r,s.color.g=e.g,s.color.b=e.b,s.color.a=e.a*this._contextInfo.state.current.opacity,s.size=i*Math.max(this._contextInfo.transform.current.getScaleX(),this._contextInfo.transform.current.getScaleY()),this.addCommand(s)}buildBatchVertices(t,e){let i=0;for(const s of e.commands)t[i++]=s.point.x,t[i++]=s.point.y,t[i++]=s.color.r/255,t[i++]=s.color.g/255,t[i++]=s.color.b/255,t[i++]=s.color.a,t[i++]=s.size;return i/this.vertexSize}renderBatch(t,e,i){t.drawArrays(t.POINTS,0,i)}}class wt{constructor(t){var e,i,s,n,r,o;this.id=wt._ID++,this.showDebug=!1,this.flipHorizontal=!1,this.flipVertical=!1,this.rotation=0,this.opacity=1,this.scale=A.One,this.origin=null,this._width=0,this._height=0,t&&(this.origin=null!==(e=t.origin)&&void 0!==e?e:this.origin,this.flipHorizontal=null!==(i=t.flipHorizontal)&&void 0!==i?i:this.flipHorizontal,this.flipVertical=null!==(s=t.flipVertical)&&void 0!==s?s:this.flipVertical,this.rotation=null!==(n=t.rotation)&&void 0!==n?n:this.rotation,this.opacity=null!==(r=t.opacity)&&void 0!==r?r:this.opacity,this.scale=null!==(o=t.scale)&&void 0!==o?o:this.scale)}cloneGraphicOptions(){return{origin:this.origin?this.origin.clone():null,flipHorizontal:this.flipHorizontal,flipVertical:this.flipVertical,rotation:this.rotation,opacity:this.opacity,scale:this.scale?this.scale.clone():null}}get width(){return Math.abs(this._width*this.scale.x)}get height(){return Math.abs(this._height*this.scale.y)}set width(t){this._width=t}set height(t){this._height=t}get localBounds(){return B.fromDimension(this.width,this.height,A.Zero)}draw(t,e,i){this._preDraw(t,e,i),this._drawImage(t,0,0),this._postDraw(t)}_preDraw(t,e,i){t.save(),t.translate(e,i),t.scale(Math.abs(this.scale.x),Math.abs(this.scale.y)),this._rotate(t),this._flip(t),t.opacity=t.opacity*this.opacity}_rotate(t){var e;const i=this.scale.x>0?1:-1,s=this.scale.y>0?1:-1,n=null!==(e=this.origin)&&void 0!==e?e:S(this.width/2,this.height/2);t.translate(n.x,n.y),t.rotate(this.rotation),t.scale(i,s),t.translate(-n.x,-n.y)}_flip(t){this.flipHorizontal&&(t.translate(this.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,this.height/this.scale.y),t.scale(1,-1))}_postDraw(t){this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}}function vt(t,e){return t&&void 0===t.__isProxy?new Proxy(t,{set:(t,i,s)=>(t[i]!==s&&(t[i]=s,"string"==typeof i&&"_"!==i[0]&&e(t)),!0),get:(t,e)=>"__isProxy"===e||t[e]}):t}function xt(t,e){return t&&void 0===t.__isProxy?new Proxy(t,{set:(t,i,s)=>(t[i]=s,"string"==typeof i&&"_"!==i[0]&&e(t),!0),get:(t,e)=>"__isProxy"===e||t[e]}):t}wt._ID=0;class bt extends wt{constructor(t){var e,i,s,n,r,o,a;super(t),this._dirty=!0,this._smoothing=!1,this._color=vt(T.Black,(()=>this.flagDirty())),this._lineWidth=1,this._lineDash=[],this._padding=0,t&&(this.color=null!==(e=t.color)&&void 0!==e?e:T.Black,this.strokeColor=null==t?void 0:t.strokeColor,this.smoothing=null!==(i=t.smoothing)&&void 0!==i?i:this.smoothing,this.lineWidth=null!==(s=t.lineWidth)&&void 0!==s?s:this.lineWidth,this.lineDash=null!==(n=t.lineDash)&&void 0!==n?n:this.lineDash,this.padding=null!==(r=t.padding)&&void 0!==r?r:this.padding),this._bitmap=document.createElement("canvas");const h=null!==(o=null==t?void 0:t.width)&&void 0!==o?o:this._bitmap.width,l=null!==(a=null==t?void 0:t.height)&&void 0!==a?a:this._bitmap.height;this.width=pt(h),this.height=pt(l);const c=this._bitmap.getContext("2d");if(!c)throw new Error("Browser does not support 2d canvas drawing, cannot create Raster graphic");this._ctx=c}cloneRasterOptions(){return{color:this.color?this.color.clone():null,strokeColor:this.strokeColor?this.strokeColor.clone():null,smoothing:this.smoothing,lineWidth:this.lineWidth,lineDash:this.lineDash,padding:this.padding}}get dirty(){return this._dirty}flagDirty(){this._dirty=!0}get width(){return this._getTotalWidth()}set width(t){this._bitmap.width=t,this._originalWidth=t,this.flagDirty()}get height(){return this._getTotalHeight()}set height(t){this._bitmap.height=t,this._originalHeight=t,this.flagDirty()}_getTotalWidth(){var t;return(null!==(t=this._originalWidth)&&void 0!==t?t:this._bitmap.width)+2*this.padding}_getTotalHeight(){var t;return(null!==(t=this._originalHeight)&&void 0!==t?t:this._bitmap.height)+2*this.padding}get localBounds(){return B.fromDimension(this._getTotalWidth()*this.scale.x,this._getTotalHeight()*this.scale.y,A.Zero)}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this.flagDirty()}get color(){return this._color}set color(t){var e;(null===(e=this._color)||void 0===e?void 0:e.equal(t))||this.flagDirty(),this._color=vt(t,(()=>this.flagDirty()))}get strokeColor(){return this._strokeColor}set strokeColor(t){var e;(null===(e=this._strokeColor)||void 0===e?void 0:e.equal(t))||this.flagDirty(),this._strokeColor=vt(t,(()=>this.flagDirty()))}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t,this.flagDirty()}get lineDash(){return this._lineDash}set lineDash(t){this._lineDash=t,this.flagDirty()}get padding(){return this._padding}set padding(t){this._padding=t,this.flagDirty()}rasterize(){this._dirty=!1,this._ctx.clearRect(0,0,this._getTotalWidth(),this._getTotalHeight()),this._ctx.save(),this._applyRasterProperites(this._ctx),this.execute(this._ctx),this._ctx.restore(),gt.load(this._bitmap,!0)}_applyRasterProperites(t){var e,i,s;this._bitmap.width=this._getTotalWidth(),this._bitmap.height=this._getTotalHeight(),t.translate(this.padding,this.padding),t.imageSmoothingEnabled=this.smoothing,t.lineWidth=this.lineWidth,t.setLineDash(null!==(e=this.lineDash)&&void 0!==e?e:t.getLineDash()),t.strokeStyle=null===(i=this.strokeColor)||void 0===i?void 0:i.toString(),t.fillStyle=null===(s=this.color)||void 0===s?void 0:s.toString()}_drawImage(t,e,i){this._dirty&&this.rasterize(),t.drawImage(this._bitmap,e,i)}}class Ct extends bt{constructor(t){super(t),this._options=t}get ctx(){return this._ctx}clone(){return new Ct(Object.assign(Object.assign(Object.assign({},this._options),this.cloneGraphicOptions()),this.cloneRasterOptions()))}execute(t){var e,i;(null===(e=this._options)||void 0===e?void 0:e.draw)&&(null===(i=this._options)||void 0===i||i.draw(t)),this._options.cache||this.flagDirty()}}var At;!function(t){t.Kill="kill",t.PreKill="prekill",t.PostKill="postkill",t.PreDraw="predraw",t.PostDraw="postdraw",t.PreDebugDraw="predebugdraw",t.PostDebugDraw="postdebugdraw",t.PreUpdate="preupdate",t.PostUpdate="postupdate",t.PreFrame="preframe",t.PostFrame="postframe",t.PreCollision="precollision",t.CollisionStart="collisionstart",t.CollisionEnd="collisionend",t.PostCollision="postcollision",t.Initialize="initialize",t.Activate="activate",t.Deactivate="deactivate",t.ExitViewport="exitviewport",t.EnterViewport="enterviewport",t.ExitTrigger="exit",t.EnterTrigger="enter",t.Connect="connect",t.Disconnect="disconnect",t.Button="button",t.Axis="axis",t.Subscribe="subscribe",t.Unsubscribe="unsubscribe",t.Visible="visible",t.Hidden="hidden",t.Start="start",t.Stop="stop",t.PointerUp="pointerup",t.PointerDown="pointerdown",t.PointerMove="pointermove",t.PointerEnter="pointerenter",t.PointerLeave="pointerleave",t.PointerCancel="pointercancel",t.PointerWheel="pointerwheel",t.Up="up",t.Down="down",t.Move="move",t.Enter="enter",t.Leave="leave",t.Cancel="cancel",t.Wheel="wheel",t.Press="press",t.Release="release",t.Hold="hold",t.PointerDragStart="pointerdragstart",t.PointerDragEnd="pointerdragend",t.PointerDragEnter="pointerdragenter",t.PointerDragLeave="pointerdragleave",t.PointerDragMove="pointerdragmove"}(At||(At={}));class St{constructor(){this._bubbles=!0}get bubbles(){return this._bubbles}set bubbles(t){this._bubbles=t}stopPropagation(){this.bubbles=!1}}class Pt extends St{constructor(t){super(),this.target=t}}class Et extends St{constructor(t){super(),this.target=t}}class Tt extends St{constructor(t){super(),this.target=t}}class Rt extends St{constructor(t){super(),this.target=t}}class Bt extends St{constructor(t){super(),this.target=t}}class Dt extends St{constructor(t,e,i){super(),this.ctx=t,this.delta=e,this.target=i}}class Mt extends St{constructor(t,e,i){super(),this.ctx=t,this.delta=e,this.target=i}}class Ft extends St{constructor(t,e){super(),this.ctx=t,this.target=e}}class kt extends St{constructor(t,e){super(),this.ctx=t,this.target=e}}class It extends St{constructor(t,e,i){super(),this.engine=t,this.delta=e,this.target=i}}class Lt extends St{constructor(t,e,i){super(),this.engine=t,this.delta=e,this.target=i}}class Ot extends St{constructor(t,e){super(),this.engine=t,this.prevStats=e,this.target=t}}class zt extends St{constructor(t,e){super(),this.engine=t,this.stats=e,this.target=t}}class Ut extends St{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class Ht extends St{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class Nt extends St{constructor(t,e,i){super(),this.button=t,this.value=e,this.target=i}}class Wt extends St{constructor(t,e,i){super(),this.axis=t,this.value=e,this.target=i}}class Vt extends St{constructor(t,e){super(),this.topic=t,this.handler=e}}class Gt extends St{constructor(t,e){super(),this.topic=t,this.handler=e}}class jt extends St{constructor(t){super(),this.target=t}}class Xt extends St{constructor(t){super(),this.target=t}}class qt extends St{constructor(t,e,i,s){super(),this.other=e,this.side=i,this.intersection=s,this.target=t}}class Kt extends St{constructor(t,e,i,s){super(),this.other=e,this.side=i,this.intersection=s,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class Zt{constructor(t,e,i){this.target=t,this.other=e,this.contact=i}}class Yt{constructor(t,e){this.target=t,this.other=e}}class Qt{constructor(t,e,i,s,n){this.target=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class $t{constructor(t,e,i,s,n){this.target=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class Jt extends St{constructor(t,e,i){super(),this.other=e,this.contact=i,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class te extends St{constructor(t,e){super(),this.other=e,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class ee extends St{constructor(t,e){super(),this.engine=t,this.target=e}}class ie extends St{constructor(t,e){super(),this.oldScene=t,this.target=e}}class se extends St{constructor(t,e){super(),this.newScene=t,this.target=e}}class ne extends St{constructor(t){super(),this.target=t}}class re extends St{constructor(t){super(),this.target=t}}class oe extends St{constructor(t,e){super(),this.target=t,this.actor=e}}class ae extends St{constructor(t,e){super(),this.target=t,this.actor=e}}class he{constructor(){this._handlers={},this._wiredEventDispatchers=[]}clear(){this._handlers={},this._wiredEventDispatchers=[]}emit(t,e){if(!t)return;let i,s;if(t=t.toLowerCase(),e||(e=new St),this._handlers[t])for(i=0,s=this._handlers[t].length;i<s;i++)this._handlers[t][i](e);for(i=0,s=this._wiredEventDispatchers.length;i<s;i++)this._wiredEventDispatchers[i].emit(t,e)}on(t,e){t=t.toLowerCase(),this._handlers[t]||(this._handlers[t]=[]),this._handlers[t].push(e),"unsubscribe"!==t&&"subscribe"!==t&&this.emit("subscribe",new Vt(t,e))}off(t,e){t=t.toLowerCase();const i=this._handlers[t];if(i)if(e){const s=i.indexOf(e);this._handlers[t].splice(s,1)}else this._handlers[t].length=0;"unsubscribe"!==t&&"subscribe"!==t&&this.emit("unsubscribe",new Gt(t,e))}once(t,e){this.on(t,(i=>{const s=i||new St;this.off(t,e),e(s)}))}wire(t){t._wiredEventDispatchers.push(this)}unwire(t){const e=t._wiredEventDispatchers.indexOf(this);e>-1&&t._wiredEventDispatchers.splice(e,1)}}class le{constructor(t,e,i=!0){this.path=t,this.responseType=e,this.bustCache=i,this.data=null,this.logger=_.getInstance(),this.events=new he}isLoaded(){return null!==this.data}_cacheBust(t){return/\?\w*=\w*/.test(t)?t+="&__="+Date.now():t+="?__="+Date.now(),t}load(){return new Promise(((t,e)=>{if(null!==this.data)return this.logger.debug("Already have data for resource",this.path),this.events.emit("complete",this.data),void t(this.data);const i=new XMLHttpRequest;i.open("GET",this.bustCache?this._cacheBust(this.path):this.path,!0),i.responseType=this.responseType,i.addEventListener("loadstart",(t=>this.events.emit("loadstart",t))),i.addEventListener("progress",(t=>this.events.emit("progress",t))),i.addEventListener("error",(t=>this.events.emit("error",t))),i.addEventListener("load",(t=>this.events.emit("load",t))),i.addEventListener("load",(()=>{if(0!==i.status&&200!==i.status)return this.logger.error("Failed to load resource ",this.path," server responded with error code",i.status),this.events.emit("error",i.response),void e(new Error(i.statusText));this.data=i.response,this.events.emit("complete",this.data),this.logger.debug("Completed loading resource",this.path),t(this.data)})),i.send()}))}}var ce=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};let de=class{updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=(n[s+0]+n[s+1]+n[s+2])/3;n[s+0]=r,n[s+1]=r,n[s+2]=r}};de=ce([b({message:"Grayscale will be removed in v0.26.0"})],de);let ue=class{updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data;n[s+0]=255-n[s+0],n[s+1]=255-n[s+1],n[s+2]=255-n[s+2]}};ue=ce([b({message:"Invert will be removed in v0.26.0"})],ue);let pe=class{constructor(t){this.opacity=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data;0!==n[s+3]&&(n[s+3]=Math.round(this.opacity*n[s+3]))}};pe=ce([b({message:"Opacity will be removed in v0.26.0"})],pe);let ge=class{constructor(t){this.color=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data;0!==n[s+3]&&(n[s+0]=(n[s+0]+this.color.r)/2,n[s+1]=(n[s+1]+this.color.g)/2,n[s+2]=(n[s+2]+this.color.b)/2)}};ge=ce([b({message:"Colorize will be removed in v0.26.0"})],ge);let _e=class{constructor(t=.1){this.factor=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=T.fromRGB(n[s+0],n[s+1],n[s+2],n[s+3]).lighten(this.factor);n[s+0]=r.r,n[s+1]=r.g,n[s+2]=r.b,n[s+3]=r.a}};_e=ce([b({message:"Lighten will be removed in v0.26.0"})],_e);let fe=class{constructor(t=.1){this.factor=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=T.fromRGB(n[s+0],n[s+1],n[s+2],n[s+3]).darken(this.factor);n[s+0]=r.r,n[s+1]=r.g,n[s+2]=r.b,n[s+3]=r.a}};fe=ce([b({message:"Darken will be removed v0.26.0"})],fe);let me=class{constructor(t=.1){this.factor=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=T.fromRGB(n[s+0],n[s+1],n[s+2],n[s+3]).saturate(this.factor);n[s+0]=r.r,n[s+1]=r.g,n[s+2]=r.b,n[s+3]=r.a}};me=ce([b({message:"Saturate will be removed in v0.26.0"})],me);let ye=class{constructor(t=.1){this.factor=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=T.fromRGB(n[s+0],n[s+1],n[s+2],n[s+3]).desaturate(this.factor);n[s+0]=r.r,n[s+1]=r.g,n[s+2]=r.b,n[s+3]=r.a}};ye=ce([b({message:"Desaturate will be removed in v0.26.0"})],ye);let we=class{constructor(t){this.color=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data;0!==n[s+3]&&(n[s+0]=this.color.r,n[s+1]=this.color.g,n[s+2]=this.color.b)}};we=ce([b({message:"Fill will be removed in v0.26.0"})],we);var ve=function(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((s=s.apply(t,e||[])).next())}))};class xe{constructor(t,e=!0){this.path=t,this.bustCache=e,this._sprite=null,this.loaded=new Promise((t=>{this._loadedResolve=t})),this._resource=new le(t,"blob",e),this._sprite=new Pe(this,0,0,0,0)}get image(){return this.data}isLoaded(){return!!this.data}load(){return ve(this,void 0,void 0,(function*(){try{let t;if(this.path.includes("data:image/"))t=this.path;else{const e=yield this._resource.load();t=URL.createObjectURL(e)}const e=new Image;e.src=t,yield e.decode(),this.data=e,this.width=this._sprite.width=e.naturalWidth,this.height=this._sprite.height=e.naturalHeight,this._sprite=new Pe(this,0,0,this.width,this.height)}catch(t){yield Promise.reject("Error loading texture")}return this._loadedResolve(this.data),this.data}))}asSprite(){return this._sprite}}function be(t){return class extends t{assign(t){for(const e in t)"function"!=typeof this[e]&&(this[e]=t[e])}constructor(...t){super(...t);1!==t.filter((function(t){return void 0!==t})).length||!t[0]||"object"!=typeof t[0]||t[0]instanceof Array||this.assign(t[0])}}}var Ce=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o},Ae=function(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((s=s.apply(t,e||[])).next())}))};class Se{constructor(t,e,i,s,n){this.x=0,this.y=0,this.rotation=0,this.anchor=A.Half,this.offset=A.Zero,this.scale=A.One,this.drawAroundAnchor=!1,this.logger=_.getInstance(),this.flipVertical=!1,this.flipHorizontal=!1,this.effects=[],this.width=0,this.height=0,this._spriteCanvas=null,this._spriteCtx=null,this._pixelData=null,this._pixelsLoaded=!1,this._dirtyEffect=!0,this._opacity=1;let r=t;if(t&&!(t instanceof xe)&&(e=0|t.x,i=0|t.y,s=0|t.width,n=0|t.height,r=t.image,!r)){throw new Error("An image texture is required to construct a sprite")}this.x=e||0,this.y=i||0,this.texture=r,this._spriteCanvas=document.createElement("canvas"),this._spriteCanvas.width=s,this._spriteCanvas.height=n,this._spriteCtx=this._spriteCanvas.getContext("2d"),this._initPixelsFromTexture(),this.width=s,this.height=n}get drawWidth(){return Math.abs(this.width*this.scale.x)}get drawHeight(){return Math.abs(this.height*this.scale.y)}_initPixelsFromTexture(){return Ae(this,void 0,void 0,(function*(){try{const t=yield this.texture.loaded;this.width=this.width||t.naturalWidth,this.height=this.height||t.naturalHeight,this._spriteCanvas.width=this._spriteCanvas.width||t.naturalWidth,this._spriteCanvas.height=this._spriteCanvas.height||t.naturalHeight,this._loadPixels(),this._dirtyEffect=!0}catch(t){this.logger.error("Error loading texture ",this.texture.path,t)}}))}_loadPixels(){if(this.texture.isLoaded()&&!this._pixelsLoaded){const t=this.texture.image.naturalWidth||0,e=this.texture.image.naturalHeight||0;if(this.width>t&&this.logger.warn(`The sprite width ${this.width} exceeds the width \n ${t} of the backing texture ${this.texture.path}`),this.width<=0||t<=0)throw new Error(`The width of a sprite cannot be 0 or negative, sprite width: ${this.width}, original width: ${t}`);if(this.height>e&&this.logger.warn(`The sprite height ${this.height} exceeds the height \n ${e} of the backing texture ${this.texture.path}`),this.height<=0||e<=0)throw new Error(`The height of a sprite cannot be 0 or negative, sprite height: ${this.height}, original height: ${e}`);this._flushTexture(),this._pixelsLoaded=!0}}_flushTexture(){const t=this.texture.image.naturalWidth||0,e=this.texture.image.naturalHeight||0;this._spriteCtx.clearRect(0,0,this.width,this.height),this._spriteCtx.drawImage(this.texture.image,L(this.x,0,t),L(this.y,0,e),L(this.width,0,t),L(this.height,0,e),0,0,this.width,this.height)}opacity(t){this._opacity=t}grayscale(){this.addEffect(new de)}invert(){this.addEffect(new ue)}fill(t){this.addEffect(new we(t))}colorize(t){this.addEffect(new ge(t))}lighten(t=.1){this.addEffect(new _e(t))}darken(t=.1){this.addEffect(new fe(t))}saturate(t=.1){this.addEffect(new me(t))}desaturate(t=.1){this.addEffect(new ye(t))}addEffect(t){this.effects.push(t),this.texture.isLoaded()&&this._pixelsLoaded?this._applyEffects():this._dirtyEffect=!0}removeEffect(t){let e=-1;e="number"==typeof t?t:this.effects.indexOf(t),e<0||e>=this.effects.length||(this.effects.splice(e,1),this.texture.isLoaded()&&this._pixelsLoaded?this._applyEffects():this._dirtyEffect=!0)}_applyEffects(){if(this._flushTexture(),this.effects.length>0){this._pixelData=this._spriteCtx.getImageData(0,0,this.width,this.height);const t=this.effects.length;for(let e=0;e<t;e++)for(let t=0;t<this.height;t++)for(let i=0;i<this.width;i++)this.effects[e].updatePixel(i,t,this._pixelData);this._spriteCtx.clearRect(0,0,this.width,this.height),this._spriteCtx.putImageData(this._pixelData,0,0)}this._dirtyEffect=!1}clearEffects(){this.effects.length=0,this._applyEffects()}reset(){}debugDraw(t,e,i){t.save(),t.translate(e,i),t.rotate(this.rotation);const s=this.drawWidth*this.anchor.x,n=this.drawHeight*this.anchor.y;t.strokeStyle=T.Black.toString(),t.strokeRect(-s,-n,this.drawWidth,this.drawHeight),t.restore()}draw(t,e,i){t instanceof CanvasRenderingContext2D?this._drawWithOptions({ctx:t,x:e,y:i}):this._drawWithOptions(t)}_drawWithOptions(t){var e,i,s,n,r,o,a,h,l;const{ctx:c,x:d,y:u,rotation:p,drawWidth:g,drawHeight:_,anchor:f,offset:m,opacity:y,flipHorizontal:w,flipVertical:v}=Object.assign(Object.assign({},t),{rotation:null!==(e=t.rotation)&&void 0!==e?e:this.rotation,drawWidth:null!==(i=t.drawWidth)&&void 0!==i?i:this.width,drawHeight:null!==(s=t.drawHeight)&&void 0!==s?s:this.height,flipHorizontal:null!==(n=t.flipHorizontal)&&void 0!==n?n:this.flipHorizontal,flipVertical:null!==(r=t.flipVertical)&&void 0!==r?r:this.flipVertical,anchor:null!==(o=t.anchor)&&void 0!==o?o:this.anchor,offset:null!==(a=t.offset)&&void 0!==a?a:this.offset,opacity:(null!==(h=t.opacity)&&void 0!==h?h:1)*(null!==(l=this._opacity)&&void 0!==l?l:1)});this._dirtyEffect&&this._applyEffects();const x=g*f.x+m.x,b=_*f.y+m.y,C=this.scale.x>0?1:-1,A=this.scale.y>0?1:-1;c.save(),c.translate(d,u),c.scale(Math.abs(this.scale.x),Math.abs(this.scale.y)),this.drawAroundAnchor&&c.translate(-x,-b),c.translate(x,b),c.rotate(p),c.scale(C,A),c.translate(-x,-b),w&&(c.translate(g,0),c.scale(-1,1)),v&&(c.translate(0,_),c.scale(1,-1));const S=c.globalAlpha;c.globalAlpha=y,c.drawImage(this._spriteCanvas,0,0,this.width,this.height,0,0,this.width,this.height),c.globalAlpha=S,c.restore()}clone(){const t=new Pe(this.texture,this.x,this.y,this.width,this.height);t.anchor=this.anchor.clone(),t.scale=this.scale.clone(),t.rotation=this.rotation,t.flipHorizontal=this.flipHorizontal,t.flipVertical=this.flipVertical;const e=this.effects.length;for(let i=0;i<e;i++)t.addEffect(this.effects[i]);return t}}let Pe=class extends(be(Se)){constructor(t,e,i,s,n){super(t,e,i,s,n)}};Pe=Ce([b({message:"Label.clearTextShadow will be removed in v0.26.0",alternateMethod:"Use Label.font.shadow"})],Pe);class Ee extends wt{constructor(t){var e,i;super(t),this.image=t.image;const{width:s,height:n}=t;this.sourceView=null!==(e=t.sourceView)&&void 0!==e?e:{x:0,y:0,width:null!=s?s:0,height:null!=n?n:0},this.destSize=null!==(i=t.destSize)&&void 0!==i?i:{width:null!=s?s:0,height:null!=n?n:0},this._updateSpriteDimensions(),this.image.ready.then((()=>{this._updateSpriteDimensions()}))}static from(t){return new Ee({image:t})}get width(){return this.destSize.width}get height(){return this.destSize.height}set width(t){this.destSize.width=t,super.width=Math.ceil(this.destSize.width)}set height(t){this.destSize.height=t,super.height=Math.ceil(this.destSize.height)}_updateSpriteDimensions(){var t,e,i,s,n,r;const{width:o,height:a}=this.image;this.sourceView.width=(null===(t=this.sourceView)||void 0===t?void 0:t.width)||o,this.sourceView.height=(null===(e=this.sourceView)||void 0===e?void 0:e.height)||a,this.destSize.width=(null===(i=this.destSize)||void 0===i?void 0:i.width)||(null===(s=this.sourceView)||void 0===s?void 0:s.width)||o,this.destSize.height=(null===(n=this.destSize)||void 0===n?void 0:n.height)||(null===(r=this.sourceView)||void 0===r?void 0:r.height)||a,this.width=Math.ceil(this.destSize.width),this.height=Math.ceil(this.destSize.height)}_preDraw(t,e,i){this.image.isLoaded()&&this._updateSpriteDimensions(),super._preDraw(t,e,i)}_drawImage(t,e,i){this.image.isLoaded()&&(this._updateSpriteDimensions(),t.drawImage(this.image.image,this.sourceView.x,this.sourceView.y,this.sourceView.width,this.sourceView.height,e,i,this.destSize.width,this.destSize.height))}static fromLegacySprite(t){const e=t.texture,i=Re.fromLegacyTexture(e);return new Ee({image:i,sourceView:{x:t.x,y:t.y,width:t.width,height:t.height}})}static toLegacySprite(t){const e=t.image,i=new xe(e.path);return i.data=e.image,new Pe(i,t.sourceView.x,t.sourceView.y,t.sourceView.width,t.sourceView.height)}clone(){return new Ee(Object.assign({image:this.image,sourceView:Object.assign({},this.sourceView),destSize:Object.assign({},this.destSize)},this.cloneGraphicOptions()))}}var Te=function(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((s=s.apply(t,e||[])).next())}))};class Re{constructor(t,e=!1){this.path=t,this._logger=_.getInstance(),this.data=new Image,this._resource=new le(t,"blob",e),(t.endsWith(".svg")||t.endsWith(".gif"))&&this._logger.warn(`Image type is not fully supported, you may have mixed results ${t}. Fully supported: jpg, bmp, and png`),this.ready=new Promise((t=>{this._loadedResolve=t}))}get width(){return this.image.naturalWidth}get height(){return this.image.naturalHeight}isLoaded(){return!!this.data.src}get image(){return this.data}load(){return Te(this,void 0,void 0,(function*(){if(this.isLoaded())return this.data;try{let t;if(this.path.includes("data:image/"))t=this.path;else{const e=yield this._resource.load();t=URL.createObjectURL(e)}const e=new Image;e.src=t,yield e.decode(),this.data=e}catch(t){throw`Error loading ImageSource from path '${this.path}' with error [${t.message}]`}return this._loadedResolve(this.data),this.data}))}toSprite(){return Ee.from(this)}static fromLegacyTexture(t){const e=new Re(t.path);return t.isLoaded()?e.data=t.data:t.loaded.then((()=>{e.data=t.data})),e}unload(){this.data=new Image}}var Be=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class De{constructor(t,e,i,s){this.sprites=[],this.currentFrame=0,this._timeLeftInFrame=0,this._idempotencyToken=-1,this.anchor=A.Zero,this.rotation=0,this.scale=A.One,this.loop=!0,this.freezeFrame=-1,this.flipVertical=!1,this.flipHorizontal=!1,this.drawWidth=0,this.drawHeight=0,this.width=0,this.height=0,this._opacity=1;let n=t;if(t&&!(t instanceof sr)){const r=t;n=r.engine,e=r.sprites,i=r.speed,s=r.loop}this.sprites=e,this.speed=i,this._engine=n,this._timeLeftInFrame=this.speed,null!=s&&(this.loop=s),e&&e[0]&&(this.drawHeight=e[0]?e[0].drawHeight:0,this.drawWidth=e[0]?e[0].drawWidth:0,this.width=e[0]?e[0].width:0,this.height=e[0]?e[0].height:0,this.freezeFrame=e.length-1)}opacity(t){this._opacity=t}grayscale(){this.addEffect(new de)}invert(){this.addEffect(new ue)}fill(t){this.addEffect(new we(t))}colorize(t){this.addEffect(new ge(t))}lighten(t=.1){this.addEffect(new _e(t))}darken(t=.1){this.addEffect(new fe(t))}saturate(t=.1){this.addEffect(new me(t))}desaturate(t=.1){this.addEffect(new ye(t))}addEffect(t){for(const e in this.sprites)this.sprites[e].addEffect(t)}removeEffect(t){for(const e in this.sprites)this.sprites[e].removeEffect(t)}clearEffects(){for(const t in this.sprites)this.sprites[t].clearEffects()}_setAnchor(t){for(const e in this.sprites)this.sprites[e].anchor.setTo(t.x,t.y)}_setRotation(t){for(const e in this.sprites)this.sprites[e].rotation=t}_setScale(t){for(const e in this.sprites)this.sprites[e].scale=t}reset(){this.currentFrame=0}isDone(){return!this.loop&&this.currentFrame>=this.sprites.length}tick(t,e){if(this._idempotencyToken===e)return;this._idempotencyToken=e,this._timeLeftInFrame-=t,this._timeLeftInFrame<=0&&(this.currentFrame=this.loop?(this.currentFrame+1)%this.sprites.length:this.currentFrame+1,this._timeLeftInFrame=this.speed),this._updateValues();const i=this.sprites[this.currentFrame];i&&(this.width=i.width,this.height=i.height,this.drawWidth=i.drawWidth,this.drawHeight=i.drawHeight)}_updateValues(){this._setAnchor(this.anchor),this._setRotation(this.rotation),this._setScale(this.scale)}skip(t){this.currentFrame=(this.currentFrame+t)%this.sprites.length}draw(t,e,i){t instanceof CanvasRenderingContext2D?this._drawWithOptions({ctx:t,x:e,y:i}):this._drawWithOptions(t)}_drawWithOptions(t){var e,i,s,n,r,o,a,h;const l=Object.assign(Object.assign({},t),{rotation:null!==(e=t.rotation)&&void 0!==e?e:this.rotation,drawWidth:null!==(i=t.drawWidth)&&void 0!==i?i:this.drawWidth,drawHeight:null!==(s=t.drawHeight)&&void 0!==s?s:this.drawHeight,flipHorizontal:null!==(n=t.flipHorizontal)&&void 0!==n?n:this.flipHorizontal,flipVertical:null!==(r=t.flipVertical)&&void 0!==r?r:this.flipVertical,anchor:null!==(o=t.anchor)&&void 0!==o?o:this.anchor,opacity:(null!==(a=t.opacity)&&void 0!==a?a:1)*(null!==(h=this._opacity)&&void 0!==h?h:1)});let c;this._updateValues(),this.currentFrame<this.sprites.length&&(c=this.sprites[this.currentFrame],c.draw(l)),-1!==this.freezeFrame&&this.currentFrame>=this.sprites.length&&(c=this.sprites[L(this.freezeFrame,0,this.sprites.length-1)],c.draw(l)),c&&(this.drawWidth=c.drawWidth,this.drawHeight=c.drawHeight)}play(t,e){this.reset(),this._engine.playAnimation(this,t,e)}}let Me=class extends(be(De)){constructor(t,e,i,s){super(t,e,i,s)}};var Fe,ke,Ie,Le,Oe;Me=Be([b({message:"Animation will be removed in v0.26.0",alternateMethod:"Use Graphics.Animation"})],Me),function(t){t.Em="em",t.Rem="rem",t.Px="px",t.Pt="pt",t.Percent="%"}(Fe||(Fe={})),function(t){t.Left="left",t.Right="right",t.Center="center",t.Start="start",t.End="end"}(ke||(ke={})),function(t){t.Top="top",t.Hanging="hanging",t.Middle="middle",t.Alphabetic="alphabetic",t.Ideographic="ideographic",t.Bottom="bottom"}(Ie||(Ie={})),function(t){t.Normal="normal",t.Italic="italic",t.Oblique="oblique"}(Le||(Le={})),function(t){t.LeftToRight="ltr",t.RightToLeft="rtl"}(Oe||(Oe={}));var ze=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Ue{constructor(t,e,i,s,n,r){this._sprites=[],this._image=null,this._columns=0,this._rows=0,this._spWidth=0,this._spHeight=0,this._spacing=0;let o=!1;if(t instanceof Array?this._sprites=t:(!t||t instanceof xe?(this._image=t,this._columns=e,this._rows=i,this._spWidth=s,this._spHeight=n,this._spacing=r||0):(this._columns=t.columns,this._rows=t.rows,this._spWidth=t.spWidth,this._spHeight=t.spHeight,this._image=t.image,this._spacing=t.spacing||0),this._sprites=new Array(this._columns*this._rows),o=!0),this.image instanceof xe){let t=!1,e=!1;if(this.image.isLoaded()){if(t=this.spWidth*this.columns>this.image.image.naturalWidth,e=this.spHeight*this.rows>this.image.image.naturalHeight,t)throw new RangeError(`SpriteSheet specified is wider, ${this.columns} cols x ${this.spWidth} pixels > ${this.image.image.naturalWidth} pixels than image width`);if(e)throw new RangeError(`SpriteSheet specified is taller, ${this.rows} rows x ${this.spHeight} pixels > ${this.image.image.naturalHeight} pixels than image height`)}}if(o){const t=this.getSpacingDimensions();for(let e=0;e<this.rows;e++)for(let i=0;i<this.columns;i++)this._sprites[i+e*this.columns]=new Pe(this.image,i*this.spWidth+t.margin*i+t.left,e*this.spHeight+t.margin*e+t.top,this.spWidth,this.spHeight)}}get spacing(){return this._spacing}get sprites(){return[...this._sprites]}get image(){return this._image}get columns(){return this._columns}get rows(){return this._rows}get spWidth(){return this._spWidth}get spHeight(){return this._spHeight}getSpacingDimensions(){var t,e,i;return"number"==typeof this.spacing?{left:this.spacing,top:this.spacing,margin:this.spacing}:{left:null!==(t=this.spacing.left)&&void 0!==t?t:0,top:null!==(e=this.spacing.top)&&void 0!==e?e:0,margin:null!==(i=this.spacing.margin)&&void 0!==i?i:0}}getAnimationByIndices(t,e,i){let s=e.map((t=>this.sprites[t]));return s=s.map((function(t){return t.clone()})),new Me(t,s,i)}getAnimationBetween(t,e,i,s){let n=this.sprites.slice(e,i);return n=n.map((function(t){return t.clone()})),new Me(t,n,s)}getAnimationForAll(t,e){const i=this.sprites.map((function(t){return t.clone()}));return new Me(t,i,e)}getSprite(t){if(t>=0&&t<this.sprites.length)return this.sprites[t];throw new Error("Invalid index: "+t)}getAnimationByCoords(t,e,i){let s=0,n=0;const r=new Array(e.length);for(let t=0;t<e.length;t++){const i=e[t];i.image=i.image||this.image,s=Math.max(s,i.drawWidth),n=Math.max(n,i.drawHeight),r[t]=new Pe(i)}const o=new Me(t,r,i);return o.drawWidth=s,o.drawHeight=n,o}}let He=class extends Ue{constructor(t,e,i,s,n,r,o,a){super(t instanceof xe?{image:t,spWidth:r,spHeight:o,rows:n,columns:s,spacing:a||0}:t),this._currentColor=T.Black,this._currentOpacity=1,this._spriteRecord={},this._textShadowOn=!1,this._textShadowDirty=!0,this._textShadowColor=T.Black,this._textShadowSprites={},this._shadowOffsetX=5,this._shadowOffsetY=5,!t||t instanceof xe||(e=t.alphabet,i=t.caseInsensitive),this.alphabet=e,this.caseInsensitive=i,this._spriteRecord=this.getTextSprites()}getTextSprites(){const t={};for(let e=0;e<this.alphabet.length;e++){let i=this.alphabet[e];this.caseInsensitive&&(i=i.toLowerCase()),t[i]=this.sprites[e].clone()}return t}setTextShadow(t,e,i){this._textShadowOn=!0,this._shadowOffsetX=t,this._shadowOffsetY=e,this._textShadowColor=i.clone(),this._textShadowDirty=!0;for(const t in this._spriteRecord)this._textShadowSprites[t]=this._spriteRecord[t].clone()}useTextShadow(t){this._textShadowOn=t,t&&this.setTextShadow(5,5,this._textShadowColor)}draw(t,e,i,s,n){if(n=this._parseOptions(n),this._currentColor.toString()!==n.color.toString()||this._currentOpacity!==n.opacity){this._currentOpacity=n.opacity,this._currentColor=n.color;for(const t in this._spriteRecord)this._spriteRecord[t].clearEffects(),this._spriteRecord[t].fill(n.color),this._spriteRecord[t].opacity(n.opacity)}if(this._textShadowOn&&this._textShadowDirty&&this._textShadowColor){for(const t in this._textShadowSprites)this._textShadowSprites[t].clearEffects(),this._textShadowSprites[t].addEffect(new we(this._textShadowColor.clone()));this._textShadowDirty=!1}const r=this.sprites[0],o=r.height,a=n.fontSize/o,h=e.length*r.width*a+e.length*n.letterSpacing;let l=i;n.textAlign===ke.Left||n.textAlign===ke.Start?l=i:n.textAlign===ke.Right||n.textAlign===ke.End?l=i-h:n.textAlign===ke.Center&&(l=i-h/2);let c=s-o*a;n.baseAlign===Ie.Top||n.baseAlign===Ie.Hanging?c=s:n.baseAlign===Ie.Ideographic||n.baseAlign===Ie.Bottom||n.baseAlign===Ie.Alphabetic?c=s-o*a:n.baseAlign===Ie.Middle&&(c=s-o*a/2);for(let i=0;i<e.length;i++){let s=e[i];this.caseInsensitive&&(s=s.toLowerCase());try{this._textShadowOn&&(this._textShadowSprites[s].drawAroundAnchor=!1,this._textShadowSprites[s].scale=S(a,a),this._textShadowSprites[s].draw(t,l+this._shadowOffsetX,c+this._shadowOffsetY));const e=this._spriteRecord[s];e.drawAroundAnchor=!1,e.scale=S(a,a),e.draw(t,l,c),l+=e.drawWidth+n.letterSpacing}catch(t){_.getInstance().error(`SpriteFont Error drawing char ${s}`)}}}_parseOptions(t){return{fontSize:t.fontSize||10,letterSpacing:t.letterSpacing||0,color:t.color||T.Black,textAlign:void 0===typeof t.textAlign?ke.Left:t.textAlign,baseAlign:void 0===typeof t.baseAlign?Ie.Bottom:t.baseAlign,maxWidth:t.maxWidth||-1,opacity:t.opacity||0}}};He=ze([b({message:"SpriteSheet will be removed in v0.26.0",alternateMethod:"Use Graphics.SpriteSheet"})],He);class Ne{constructor(t){this._logger=_.getInstance(),this.sprites=[];const{sprites:e,rows:i,columns:s}=t;this.sprites=e,this.rows=null!=i?i:1,this.columns=null!=s?s:this.sprites.length}getSprite(t,e){if(t>=this.columns||t<0)return this._logger.warn(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1}`),null;if(e>=this.rows||e<0)return this._logger.warn(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1}`),null;const i=t+e*this.columns;return this.sprites[i]}static fromLegacySpriteSheet(t){const e=t.sprites.map((t=>Ee.fromLegacySprite(t)));return new Ne({sprites:e})}static toLegacySpriteSheet(t){const e=t.sprites.map((t=>Ee.toLegacySprite(t)));return new Ue(e)}static fromImageSource(t){var e;const i=[];t.spacing=null!==(e=t.spacing)&&void 0!==e?e:{};const{image:s,grid:{rows:n,columns:r,spriteWidth:o,spriteHeight:a},spacing:{originOffset:h,margin:l}}=t,c=Object.assign({x:0,y:0},h),d=Object.assign({x:0,y:0},l);for(let t=0;t<r;t++)for(let e=0;e<n;e++)i[t+e*r]=new Ee({image:s,sourceView:{x:t*o+d.x*t+c.x,y:e*a+d.y*e+c.y,width:o,height:a},destSize:{height:a,width:o}});return new Ne({sprites:i,rows:n,columns:r})}}class We extends wt{constructor(t){super(t),this._text="",this._dirty=!0,this.alphabet="",this.shadow=null,this.caseInsensitive=!1,this.spacing=0,this._logger=_.getInstance(),this._sprites=[];const{alphabet:e,spriteSheet:i,caseInsensitive:s,spacing:n,shadow:r}=t;this.alphabet=e,this.spriteSheet=i,this.caseInsensitive=null!=s?s:this.caseInsensitive,this.spacing=null!=n?n:this.spacing,this.shadow=null!=r?r:this.shadow,this.spriteSheet.sprites[0].image.ready.then((()=>{this._updateDimensions()}))}static fromLegacySpriteFont(t){const e=t.sprites.map(Ee.fromLegacySprite);return new We({alphabet:t.alphabet,spacing:0,caseInsensitive:t.caseInsensitive,spriteSheet:new Ne({sprites:e})})}_getCharacterSprites(t){if(!this._dirty)return this._sprites;const e=[],i=this.caseInsensitive?t.toLocaleLowerCase():t,s=this.caseInsensitive?this.alphabet.toLocaleLowerCase():this.alphabet;for(let t=0;t<i.length;t++){const n=i[t];let r=s.indexOf(n);-1===r&&(r=0,this._logger.warn(`SpriteFont - Cannot find letter '${n}' in configured alphabet '${s}'`));const o=this.spriteSheet.sprites[r];o?e.push(o):this._logger.warn(`SpriteFont - Cannot find sprite for '${n}' at index '${r}' in configured SpriteSheet`)}return this._dirty=!1,this._sprites=e}_updateDimensions(){const t=this._getCharacterSprites(this._text);let e=0,i=0;for(const s of t)e+=s.width+this.spacing,i=Math.max(i,s.height);this.width=e,this.height=i}updateText(t){this._text!==t&&(this._dirty=!0,this._text=t,this._updateDimensions())}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,e,i)}_drawImage(t,e,i){let s=0;for(const n of this._getCharacterSprites(this._text))n.draw(t,e+s,i),s+=n.width+this.spacing}render(t,e,i,s){this._text!==e&&(this._dirty=!0,this._text=e),this.shadow&&(t.save(),t.translate(this.shadow.offset.x,this.shadow.offset.y),this.draw(t,i,s),t.restore()),this.draw(t,i,s)}clone(){return new We({alphabet:this.alphabet,spriteSheet:this.spriteSheet,spacing:this.spacing})}}class Ve{constructor(){this.fontSheet="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAAwCAYAAAD+f6R/AAAAAXNSR0IArs4c6QAABcJJREFUeJztnemu7CgMhGE07//KmT9NhrAFVzkQndQntXRP3/bCZkwCSQhCCCGEEEIIIYQQQog/TRz953Ecx/nDGIe/vdNhlc9tIz605Fk/ZmWfsO1hn9Gxuv1KHbvb3iL/VN+d1WORbyr7yR/5b9M4vjNeqko6jPJHq5wGHU151o9J2Udse9hndCxuv0rH7rY3yD/Wdyf13MrnQeDfkZIUSGKM4ff3cWN82pEZuTyQGX2IxeyR63va//8VNCYCq+1yEkLtWyagXv1P1r1H+110gP3PzT4gT8uW/mdQ8mUG8E9DqOz4MS9ICKGbXpS2BpnIrRzYeS96cll08INlCMl2/glzdcfazuuPqQO03lmqrBHsf272Q6NODXj6zzZIJd/LAHYTg3Mays5gBi7ZR27fOgs0yj8rm36DLMFiPgkAdXHKOwUQeMCQ/adSh/qBQrT/tPxbAwA9+DOZEILPAATSuHMgTv7+Auk/df2lHPCZLvMSLJe34LkEQ9PwXF1SRTllMYgvIaflqyVAjLGbsiCDcOK76jflxZ+sINPyROc5071yKWK5CJTV3dMp6+tBlyCtNlhAq/+XbWoBDcRNXYBMzD4VvQygSuPYC2jGGaSSOxXfy3dTUEsanIvNeepm38N/hssSALTPZnAXfwIYRJn2b7UBcw0FKX+nDdAMpm2j9WVnxrUa7TXaVAca/B+TgaAVh6R/rH0P/5m01dt/RLYViJn+w/bhVX2P7f/duqom5qb02pRLCLGIMgBU1wCEEN9BAUCID6MAIMSHUQAQ4sMoAAjxYRQAhPgwd1uB0fuZ7H3cnn2P+9mr/Pe4B8/eB/fwP4eRtci/0f6OfTCPt/9oHwC6G6y19RHZDumxmwzR4eE/s/2Tte/q/+XLdc9DeJ19diesQc/j7Z8fCe4tAS4CxZ7sp7eiJi7HiZmjmOTGJs+93CbS3nP0XIPH3vW8/qz6QPnX2QdsV/1uw/iZYvg8ACeHd28rpPzfNfhL+7vkw/4Ou9s+Onhbv91elpKZ48Dl6bzpwwibHigRArf+Ptk9+L3Y1Q5OB4LgCeSBw1iuB3GeJh1/HrX/zF0A9Mk+u45zMkc3r4rWPomma5+p/514LB+Zo93MErJ1JHxXPzByGa/licRYVKbpeQCoQ6Q8yxuCwJF9IPsoDkHAo/3Tx26cvA4EtJ/n04w8QOq/mrR7ddfLAC5BYFNlVI/0CnOVUflOpvJUQMx9AIMIW/nWDM67/qw0+95v9goBqD9j+72u/KD9U89IbnQbMIR2Zbneh5zUY7Hdk7XIP3UffVb+r+wDYAZLq+1n1+C7y3/ny2r7p5yeByDEh9HzAIQQJwoAQnwYBQAhPowCgBBjoNu3hNxSFACE6INuKvPajPZ4EFEAEKINcybGYzOd247WEd3TgA2jlmjEyrd+j9hvfVbD2PWQ3ZmGlu2HyO8og8eBuNUvNYWoDgMVpwHTJoLWdz1Y+ZYOy5uF7t6PPruZxANrud1lQXkP0jsGz/Yz+vGGMuygFyhSPcJnc1pMnQZElc+cRnoAlxdTvoDuK7puqF7uCQy+3fyFMiA02/vJQHh7DQDogMPTSGFNA56HTzbZ9yAfBOb1Zyo3qGM3MfMZ3f76huXf6xlmAHknMlLNXsBBBvbljIz9Uyz5Y5TzIBLR/qy/rNyrZ8+L/0BZ0m+tgXD0OK5XZxC/9P7I/g4hVFvzXf1/6i5A7+3AlijMPBLMZfCvuAp7A9rY56ApHitmLQc7c8bOv6ftAxlM9Xp35nkEK7nJetBsaMhtAAAuOLQGXwhh2dXQnn1rZ/a42BI3dL7L+jkFAbQddwdA9Ah35yMKhgEgVT46EFh5D4jz+OgavNKxeBCd1wDSJ/97oR8eoJkLi9t9/BDgDHTJ5NE7Dnzechh914OVv9M1K9PCqsfqb88XVg9qN9lm6nG176UPu+zn17GOxuO0vOWEEC/j+LFKTgghlvEfYJaLS+SA2O0AAAAASUVORK5CYII=",this.size=16,this.load()}load(){return this._imageSource=new Re(this.fontSheet),this._imageSource.load().then((()=>{this._spriteSheet=Ne.fromImageSource({image:this._imageSource,grid:{rows:3,columns:16,spriteWidth:16,spriteHeight:16}}),this._spriteFont=new We({alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ,!'&.\"?-()+ ",caseInsensitive:!0,spriteSheet:this._spriteSheet,spacing:-6})}))}write(t,e,i){this._imageSource.isLoaded()&&this._spriteFont.render(t,e,i.x,i.y)}}class Ge{constructor(t){this._webglCtx=t,this._debugText=new Ve}drawRect(t,e,i,s,n={color:T.Black}){this.drawLine(S(t,e),S(t+i,e),Object.assign({},n)),this.drawLine(S(t+i,e),S(t+i,e+s),Object.assign({},n)),this.drawLine(S(t+i,e+s),S(t,e+s),Object.assign({},n)),this.drawLine(S(t,e+s),S(t,e),Object.assign({},n))}drawLine(t,e,i={color:T.Black}){this._webglCtx.__lineRenderer.addLine(t,e,i.color)}drawPoint(t,e={color:T.Black,size:5}){this._webglCtx.__pointRenderer.addPoint(t,e.color,e.size)}drawText(t,e){this._debugText.write(this._webglCtx,t,e)}}class je{constructor(t){this._transform=new et,this._state=new it,this.snapToPixel=!0,this.smoothing=!1,this.backgroundColor=T.ExcaliburBlue,this.debug=new Ge(this);const{canvasElement:e,enableTransparency:i,smoothing:s,snapToPixel:n,backgroundColor:r}=t;this.__gl=e.getContext("webgl",{antialias:null!=s?s:this.smoothing,premultipliedAlpha:!1,alpha:null==i||i,depth:!0,powerPreference:"high-performance"}),this.snapToPixel=null!=n?n:this.snapToPixel,this.smoothing=null!=s?s:this.smoothing,this.backgroundColor=null!=r?r:this.backgroundColor,this._init()}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get width(){return this.__gl.canvas.width}get height(){return this.__gl.canvas.height}checkIfResolutionSupported(t){const e=this.__gl,i=e.getParameter(e.MAX_TEXTURE_SIZE)/4;let s=!0;return(t.width>i||t.height>i)&&(s=!1),s}_init(){const t=this.__gl;this._ortho=tt.ortho(0,t.canvas.width,t.canvas.height,0,400,-400),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.__pointRenderer=new yt(t,{matrix:this._ortho,transform:this._transform,state:this._state}),this.__lineRenderer=new lt(t,{matrix:this._ortho,transform:this._transform,state:this._state}),this.__imageRenderer=new ft(t,{matrix:this._ortho,transform:this._transform,state:this._state}),this._canvas=new Ct({width:t.canvas.width,height:t.canvas.height}),this.__ctx=this._canvas.ctx}resetTransform(){this._transform.current=tt.identity()}updateViewport(){const t=this.__gl;this._ortho=this._ortho=tt.ortho(0,t.canvas.width,t.canvas.height,0,400,-400),this.__pointRenderer.shader.addUniformMatrix("u_matrix",this._ortho.data),this.__lineRenderer.shader.addUniformMatrix("u_matrix",this._ortho.data),this.__imageRenderer.shader.addUniformMatrix("u_matrix",this._ortho.data),this._canvas.width=t.canvas.width,this._canvas.height=t.canvas.height}drawImage(t,e,i,s,n,r,o,a,h){if(0!==s&&0!==n&&0!==a&&0!==h&&0!==t.width&&0!==t.height)return t?void this.__imageRenderer.addImage(t,e,i,s,n,r,o,a,h):(_.getInstance().warn("Cannot draw a null or undefined image"),void(console.trace&&console.trace()))}drawLine(t,e,i,s=1){this.__imageRenderer.addLine(i,t,e,s)}drawRectangle(t,e,i,s){this.__imageRenderer.addRectangle(s,t,e,i)}drawCircle(t,e,i){this.__imageRenderer.addCircle(t,e,i)}save(){this._transform.save(),this._state.save()}restore(){this._transform.restore(),this._state.restore()}translate(t,e){this._transform.translate(this.snapToPixel?~~t:t,this.snapToPixel?~~e:e)}rotate(t){this._transform.rotate(t)}scale(t,e){this._transform.scale(t,e)}transform(t){this._transform.current=t}clear(){const t=this.__gl;t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT),rt.clear()}flush(){const t=this.__gl;t.viewport(0,0,t.canvas.width,t.canvas.height),this.__imageRenderer.render(),this.__lineRenderer.render(),this.__pointRenderer.render()}}var Xe;!function(t){t.Fixed="Fixed",t.FitScreen="FitScreen",t.FillScreen="FillScreen",t.FitContainer="FitContainer",t.FillContainer="FillContainer",t.Position="Position"}(Xe||(Xe={}));class qe{static get SVGA(){return{width:800,height:600}}static get Standard(){return{width:1920,height:1080}}static get Atari2600(){return{width:160,height:192}}static get GameBoy(){return{width:160,height:144}}static get GameBoyAdvance(){return{width:240,height:160}}static get NintendoDS(){return{width:256,height:192}}static get NES(){return{width:256,height:224}}static get SNES(){return{width:256,height:244}}}class Ke{constructor(t){var e,i,s;this._antialiasing=!0,this._resolutionStack=[],this._viewportStack=[],this._pixelRatioOverride=null,this._isFullScreen=!1,this._isDisposed=!1,this._logger=_.getInstance(),this._fullscreenChangeHandler=()=>{this._isFullScreen=!this._isFullScreen,this._logger.debug("Fullscreen Change",this._isFullScreen)},this._pixelRatioChangeHandler=()=>{this._logger.debug("Pixel Ratio Change",window.devicePixelRatio),this._devicePixelRatio=this._calculateDevicePixelRatio(),this.applyResolutionAndViewport()},this._resizeHandler=()=>{const t=this.parent;this._logger.debug("View port resized"),this._setResolutionAndViewportByDisplayMode(t),this.applyResolutionAndViewport()},this._devicePixelRatio=this._calculateDevicePixelRatio(),this._alreadyWarned=!1,this.viewport=t.viewport,this.resolution=null!==(e=t.resolution)&&void 0!==e?e:Object.assign({},this.viewport),this._displayMode=null!==(i=t.displayMode)&&void 0!==i?i:Xe.Fixed,this._canvas=t.canvas,this._ctx=t.context,this._antialiasing=null!==(s=t.antialiasing)&&void 0!==s?s:this._antialiasing,this._browser=t.browser,this._position=t.position,this._pixelRatioOverride=t.pixelRatio,this._applyDisplayMode(),this._mediaQueryList=this._browser.window.nativeComponent.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._mediaQueryList.addEventListener?this._mediaQueryList.addEventListener("change",this._pixelRatioChangeHandler):this._mediaQueryList.addListener(this._pixelRatioChangeHandler),this._canvas.addEventListener("fullscreenchange",this._fullscreenChangeHandler),this.applyResolutionAndViewport()}dispose(){this._isDisposed||(this._isDisposed=!0,this._browser.window.off("resize",this._resizeHandler),this._resizeObserver&&this._resizeObserver.disconnect(),this.parent.removeEventListener("resize",this._resizeHandler),this._mediaQueryList.removeEventListener?this._mediaQueryList.removeEventListener("change",this._pixelRatioChangeHandler):this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._canvas.removeEventListener("fullscreenchange",this._fullscreenChangeHandler))}_calculateDevicePixelRatio(){if(window.devicePixelRatio<1)return 1;return window.devicePixelRatio||1}get pixelRatio(){return this._pixelRatioOverride?this._pixelRatioOverride:this._devicePixelRatio}get isHiDpi(){return 1!==this.pixelRatio}get displayMode(){return this._displayMode}get canvas(){return this._canvas}get parent(){return this.displayMode===Xe.FillContainer||this.displayMode===Xe.FitContainer?this.canvas.parentElement||document.body:window}get resolution(){return this._resolution}set resolution(t){this._resolution=t}get viewport(){return this._viewport?this._viewport:this._resolution}set viewport(t){this._viewport=t}get aspectRatio(){return this._resolution.width/this._resolution.height}get scaledWidth(){return this._resolution.width*this.pixelRatio}get scaledHeight(){return this._resolution.height*this.pixelRatio}setCurrentCamera(t){this._camera=t}pushResolutionAndViewport(){this._resolutionStack.push(this.resolution),this._viewportStack.push(this.viewport),this.resolution=Object.assign({},this.resolution),this.viewport=Object.assign({},this.viewport)}peekViewport(){return this._viewportStack[this._viewportStack.length-1]}peekResolution(){return this._resolutionStack[this._resolutionStack.length-1]}popResolutionAndViewport(){this.resolution=this._resolutionStack.pop(),this.viewport=this._viewportStack.pop()}applyResolutionAndViewport(){if(this._canvas.width=this.scaledWidth,this._canvas.height=this.scaledHeight,this._ctx instanceof je){this._ctx.checkIfResolutionSupported({width:this.scaledWidth,height:this.scaledHeight})||this._alreadyWarned||(this._alreadyWarned=!0,this._logger.warn(`The currently configured resolution (${this.resolution.width}x${this.resolution.height}) is too large for the platform WebGL implementation, this may work but cause WebGL rendering to behave oddly. Try reducing the resolution or disabling Hi DPI scaling to avoid this (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`))}this._antialiasing?this._canvas.style.imageRendering="auto":(this._canvas.style.imageRendering="pixelated",""===this._canvas.style.imageRendering&&(this._canvas.style.imageRendering="crisp-edges")),this._canvas.style.width=this.viewport.width+"px",this._canvas.style.height=this.viewport.height+"px",this._ctx.updateViewport(),this._ctx.resetTransform(),this._ctx.scale(this.pixelRatio,this.pixelRatio),this._ctx.smoothing=this._antialiasing}get antialiasing(){return this._antialiasing}set antialiasing(t){this._antialiasing=t,this._ctx.smoothing=this._antialiasing}get isFullScreen(){return this._isFullScreen}goFullScreen(){return this._canvas.requestFullscreen()}exitFullScreen(){return document.exitFullscreen()}pageToScreenCoordinates(t){let e=t.x,i=t.y;if(this._isFullScreen||(e-=W(this._canvas).x,i-=W(this._canvas).y),this._isFullScreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const t=window.innerWidth/this.aspectRatio;i=(i-(window.innerHeight-t)/2)/t*this.viewport.height,e=e/window.innerWidth*this.viewport.width}else{const t=window.innerHeight*this.aspectRatio;e=(e-(window.innerWidth-t)/2)/t*this.viewport.width,i=i/window.innerHeight*this.viewport.height}return e=e/this.viewport.width*this.resolution.width,i=i/this.viewport.height*this.resolution.height,new A(e,i)}screenToPageCoordinates(t){let e=t.x,i=t.y;if(e=e/this.resolution.width*this.viewport.width,i=i/this.resolution.height*this.viewport.height,this._isFullScreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const t=window.innerWidth/this.aspectRatio,s=(window.innerHeight-t)/2;i=i/this.viewport.height*t+s,e=e/this.viewport.width*window.innerWidth}else{const t=window.innerHeight*this.aspectRatio,s=(window.innerWidth-t)/2;e=e/this.viewport.width*t+s,i=i/this.viewport.height*window.innerHeight}return this._isFullScreen||(e+=W(this._canvas).x,i+=W(this._canvas).y),new A(e,i)}screenToWorldCoordinates(t){var e,i,s,n;let r=t.x,o=t.y;return r=r/this.resolution.width*this.drawWidth,o=o/this.resolution.height*this.drawHeight,r-=this.halfDrawWidth,o-=this.halfDrawHeight,r+=null!==(i=null===(e=this._camera)||void 0===e?void 0:e.x)&&void 0!==i?i:0,o+=null!==(n=null===(s=this._camera)||void 0===s?void 0:s.y)&&void 0!==n?n:0,new A(r,o)}worldToScreenCoordinates(t){var e,i,s,n;let r=t.x,o=t.y;return r-=null!==(i=null===(e=this._camera)||void 0===e?void 0:e.x)&&void 0!==i?i:0,o-=null!==(n=null===(s=this._camera)||void 0===s?void 0:s.y)&&void 0!==n?n:0,r+=this.halfDrawWidth,o+=this.halfDrawHeight,r=r/this.drawWidth*this.resolution.width,o=o/this.drawHeight*this.resolution.height,new A(r,o)}pageToWorldCoordinates(t){const e=this.pageToScreenCoordinates(t);return this.screenToWorldCoordinates(e)}worldToPageCoordinates(t){const e=this.worldToScreenCoordinates(t);return this.screenToPageCoordinates(e)}getWorldBounds(){const t=this.screenToWorldCoordinates(A.Zero).x,e=this.screenToWorldCoordinates(A.Zero).y,i=t+this.drawWidth,s=e+this.drawHeight;return new B(t,e,i,s)}get canvasWidth(){return this.canvas.width}get halfCanvasWidth(){return this.canvas.width/2}get canvasHeight(){return this.canvas.height}get halfCanvasHeight(){return this.canvas.height/2}get drawWidth(){return this._camera?this.resolution.width/this._camera.zoom:this.resolution.width}get halfDrawWidth(){return this.drawWidth/2}get drawHeight(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get halfDrawHeight(){return this.drawHeight/2}get center(){return S(this.halfDrawWidth,this.halfDrawHeight)}_computeFit(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=this.aspectRatio;let e=0,i=0;window.innerWidth/t<window.innerHeight?(e=window.innerWidth,i=window.innerWidth/t):(e=window.innerHeight*t,i=window.innerHeight),this.viewport={width:e,height:i}}_computeFitContainer(){const t=this.aspectRatio;let e=0,i=0;const s=this.canvas.parentElement;s.clientWidth/t<s.clientHeight?(e=s.clientWidth,i=s.clientWidth/t):(e=s.clientHeight*t,i=s.clientHeight),this.viewport={width:e,height:i}}_applyDisplayMode(){this.displayMode===Xe.Position?this._initializeDisplayModePosition(this._position):(this._setResolutionAndViewportByDisplayMode(this.parent),this.parent instanceof Window?this._browser.window.on("resize",this._resizeHandler):(this._resizeObserver=new ResizeObserver((()=>{this._resizeHandler()})),this._resizeObserver.observe(this.parent)),this.parent.addEventListener("resize",this._resizeHandler))}_setResolutionAndViewportByDisplayMode(t){this.displayMode===Xe.FillContainer&&(this.resolution={width:t.clientWidth,height:t.clientHeight},this.viewport=this.resolution),this.displayMode===Xe.FillScreen&&(document.body.style.margin="0px",document.body.style.overflow="hidden",this.resolution={width:t.innerWidth,height:t.innerHeight},this.viewport=this.resolution),this.displayMode===Xe.FitScreen&&this._computeFit(),this.displayMode===Xe.FitContainer&&this._computeFitContainer()}_initializeDisplayModePosition(t){if(!t)throw new Error("DisplayMode of Position was selected but no position option was given");if(this.canvas.style.display="block",this.canvas.style.position="absolute","string"==typeof t){const e=t.split(" ");switch(e[0]){case"top":this.canvas.style.top="0px";break;case"bottom":this.canvas.style.bottom="0px";break;case"middle":this.canvas.style.top="50%";const t=-this.halfDrawHeight;this.canvas.style.marginTop=t.toString();break;default:throw new Error("Invalid Position Given")}if(e[1])switch(e[1]){case"left":this.canvas.style.left="0px";break;case"right":this.canvas.style.right="0px";break;case"center":this.canvas.style.left="50%";const t=-this.halfDrawWidth;this.canvas.style.marginLeft=t.toString();break;default:throw new Error("Invalid Position Given")}}else t.top&&("number"==typeof t.top?this.canvas.style.top=t.top.toString()+"px":this.canvas.style.top=t.top),t.right&&("number"==typeof t.right?this.canvas.style.right=t.right.toString()+"px":this.canvas.style.right=t.right),t.bottom&&("number"==typeof t.bottom?this.canvas.style.bottom=t.bottom.toString()+"px":this.canvas.style.bottom=t.bottom),t.left&&("number"==typeof t.left?this.canvas.style.left=t.left.toString()+"px":this.canvas.style.left=t.left)}}class Ze{static create(){return this._INSTANCE||(window.AudioContext||window.webkitAudioContext)&&(this._INSTANCE=new AudioContext),this._INSTANCE}}Ze._INSTANCE=null;class Ye{static unlock(){return new Promise(((t,e)=>{if(Ye._UNLOCKED||!Ze.create())return t(!0);const i=setTimeout((()=>{_.getInstance().warn("Excalibur was unable to unlock the audio context, audio probably will not play in this browser."),t(!1)}),200),s=Ze.create();s.resume().then((()=>{const e=s.createBuffer(1,1,22050),n=s.createBufferSource();let r=!1;n.buffer=e,n.connect(s.destination),n.onended=()=>r=!0,n.start(0),setTimeout((()=>{!function(t){return!!t.playbackState}(n)?(s.currentTime>0||r)&&(Ye._UNLOCKED=!0):n.playbackState!==n.PLAYING_STATE&&n.playbackState!==n.FINISHED_STATE||(Ye._UNLOCKED=!0)}),0),clearTimeout(i),t(!0)}),(()=>{e()}))}))}static isUnlocked(){return this._UNLOCKED}}Ye._UNLOCKED=!1;class Qe{constructor(){this.eventDispatcher=new he}on(t,e){this.eventDispatcher.on(t,e)}off(t,e){this.eventDispatcher.off(t,e)}emit(t,e){this.eventDispatcher.emit(t,e)}once(t,e){this.eventDispatcher.once(t,e)}}function $e(t,e=T.Red,i,s,n,r,o=1,a="butt"){t.beginPath(),t.lineWidth=o,t.lineCap=a,t.strokeStyle=e.toString(),t.moveTo(i,s),t.lineTo(n,r),t.closePath(),t.stroke()}function Je(t,e=T.Red,i){t.beginPath(),t.strokeStyle=e.toString(),t.arc(i.x,i.y,5,0,2*Math.PI),t.closePath(),t.stroke()}function ti(t,e,i,s,n=1){const r=e?e.toString():"blue",o=s.scale(n);t.beginPath(),t.strokeStyle=r,t.moveTo(i.x,i.y),t.lineTo(i.x+o.x,i.y+o.y),t.closePath(),t.stroke()}function ei(t,e,i,s,n,r=5,o=T.White,a=null){let h;if("number"==typeof r)h={tl:r,tr:r,br:r,bl:r};else{const t={tl:0,tr:0,br:0,bl:0};for(const e in t)if(t.hasOwnProperty(e)){const i=e;h[i]=r[i]||t[i]}}t.beginPath(),t.moveTo(e+h.tl,i),t.lineTo(e+s-h.tr,i),t.quadraticCurveTo(e+s,i,e+s,i+h.tr),t.lineTo(e+s,i+n-h.br),t.quadraticCurveTo(e+s,i+n,e+s-h.br,i+n),t.lineTo(e+h.bl,i+n),t.quadraticCurveTo(e,i+n,e,i+n-h.bl),t.lineTo(e,i+h.tl),t.quadraticCurveTo(e,i,e+h.tl,i),t.closePath(),a&&(t.fillStyle=a.toString(),t.fill()),o&&(t.strokeStyle=o.toString(),t.stroke())}function ii(t,e,i,s,n=T.White,r=null){t.beginPath(),t.arc(e,i,s,0,2*Math.PI),t.closePath(),r&&(t.fillStyle=r.toString(),t.fill()),n&&(t.strokeStyle=n.toString(),t.stroke())}var si=i(1388),ni=function(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((s=s.apply(t,e||[])).next())}))};class ri extends Qe{constructor(t){super(),this.canvas=new Ct({smoothing:!0,draw:this.draw.bind(this)}),this._resourceList=[],this._index=0,this._playButtonShown=!1,this._resourceCount=0,this._numLoaded=0,this._progressCounts={},this._totalCounts={},this.logo="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdQAAAB2CAYAAABxhGI9AAAACXBIWXMAAAsSAAALEgHS3X78AAAKnUlEQVR42u3dP2wjSx0H8N8hJIonIRmJjsq0SBR+BQ1dcqKhe0lD77SvSwpKkJKGPulpktfRIMUdEqKIqV57rpAokM4dbSiyq7ONPTP7x39ifz7SFbnEnp3xer47O7uzH15fXwMA6OYHmgAABCoACFQAEKgAgEAFAIEKAAIVAAQqACBQAUCgAoBABQCBCgAIVAAQqAAgUAFAoAIAAhUABCoACFQAEKgAgECFLbmOiNeFf2PbAyz68Pr6qhUgbRwR92v+/zwiJrYHMEKFMmcN///UtgcQqFBk1PD/97U9Qx8VCFSgu4EmAIEKAAIVAAQqACBQ4Z25jojP8eX+0WtNAgIVaOY+Im5j+eKh24h41jQgUIEyZ7F5NaPU7wCBCiwYd/w9cOB+qAlgJ3KLLow0EV198803RWvJfvfddx+0lhEqHKu5JgAjVCBvlhmFzjQRXUekHz9+TP79y8uLRjNChXfvoePvAYEKxNtj1e42/O5JoIJABcrdRMRVLM+X3kTEpaaB988cKuzWg9EobTWdMx0Oly8uN4dqhAoARqgnaN3arHfqu7OyH8ItKLVB/P+CEfMTHyGPY3npx1m8zWGDEeoBfUk/xdti57dr/r1Wv2+6EPow3tZ5rRdS72s1neuF97xvWd+XTH0/V+UMttDWqbI/r2nrxfp+jv2uSjSO7S+OXy/A/3lN+9xX5T5HxEUPZZ0tfB71+w57eJ/HFu+z+jkv1u92YX9fbI/HhX3JA9rp5MPr66tWaG9UfUGbrHIzi7cLUyYFf/tpTady03EEeL8mUJ6i7MKYNvWNqr4Pe2jradXO60LrvPAz2PQ5RPX684ah8dxD+2zantnCgVipSVV+m/tgB9W2DDq2Sx/vM95wcHhZhWVJm8yrv58cSgfTdc70+++/X/r522+/tUKSEepBqo+om4ZLPerMjUwuNnQCtx1GWJtee1FwdD5uWd86xLs8UaVt2aNEO1/saZ/Z5rYMW4zq6v34rGV9Bg3q2eZ9SkeNm9qwyUh30OPIHYFKx5FG03C7znSOqYBq+qW/zpQ3anH037TNHluG6f0WPsPhHvab4QFty7ogOeuxDYcNy2/zu2214WNYWxmBurNO8bGn97pNBOO8xy/9uCorZZ4I2r4C7aJgO7ZV9iE49Dm6NvOWx+pWE9CUq3zbdTp9doz38TbXtzqH9RT5CyWe422OaZoZGeZCabrhPQY9HjwsjpTvCg4YtlE2+Ta/j2bzn8fqrDqgm+6yUHOmAvWUjAtGhbNYvsBknDnqH1Qhc7VmxHgeb/NbudA5j/UXlYwif2p6luhAc9teu1npiHKnDs8if6tCm7JLX3NKpgttXe9ruc9mHMd7a83iwdxF5vt8tutARaCeklRnNK9C8WnNF7geJQ4T4XG3JhSnVdilQrG+yOnrlVHfsEGYzhNBn7Lu6tS7+HJafJQ4EMiNlNqWXZ9WPvVgnVYHG5M1ByDXkT6leX2EgTqJtyt45yv7S2qO3sEZjZhDLXeR+YKdJ0Zdk8QocvH9N732KrNtq+FZ/zzIHABcJrYpd+Xv14lOd5ap76SgrduW/VTQ1qcQpqnbgu4ifZvUMNpd9XuoZmvCtPaQ2Y/BCHVLgbrJTeRPDdVf6pfMKDU2fOkHmVFFfXr3MsouLsnNvV5kRoe5+s431PeuoKPqWnaurY/ZPBEeqwceN4l96iwO6H7Mjq4y7VGPVNe10VaZMzVCPVWpI/Z6FZbcv5fMqGCU+dLfFGzj58jP8+bCdJCo7yzKTwdOF0bu9Ug7V4c+yz7FJfYeGoysUss0HssIdVZwYLDujMqlESoCdTtGsZtbHnJBeNdDSJSs0jTKdMJN1HNX54Wv7bvsU9NkVJVa13dX+/wuArV0X/l5RHyo/lnfF4G6p6DrS0kHdtXhy35TGErDPYZUn2WfWqDOo/lVqdMD2O/hKJhD7S/odukymq9s02QN4EEPR/zbaOumZc+r15zK1Zqznl9jsfiemTM1QmV3HUuTkedlg9HIQzRbUD93dfC+2tpj2fIHEH2+RqCCQH13gZq7hWXTNpVu19OB1fc9nQ0AKOKUb5lU0P1kDyOneoWk0lOZ9cIP0x7qu8+2BhCoR2wYu1+e7DmaXzBSsu5vaX1ne2zrpmUPTmxf7PM1Dm4y/vC7ny7Nif7+z/9ZmtM0Z3panPLtPmra9f16bcK0Dpbnwk43Vd/RHtu6zfNQTy1QBy3aqG2g9nVmxml+BOoJyT3NpWmn9xhfFnu4bvDa+44BXhqqfdf3uUF9+yz77AT31Yue2mjecYQ62NLfgkA9ghHqLNEhNem4H1c6vdyDxhf/bpz5m4coW/c39wi6VH2bPtHlcaV9cvXts+zxCe6rTeqc2ndL7uGd93QwM9bFcAzMoZZ7SgTBbWx+asui61h/iq1+RmjqdbnQXQ3T1DNQ63V/U9ucqm/pMzPb1rePsk/1iTOjgvatR4W3Lc8ULB78pELyrnAfeTcj1NU509/86mfJ33/8+Mf00a05UyPUEw7UVCeWG/WNEiExyHRMt5ltW30izUPk18ytt7lNfc8i//DvtvXto+ySA5BjljsLUF8lPkqMPEtW1JomDsiGBZ9Byb4NAvUITSN9GuwsIj6t6UTOqk7jJREkmzqli8xIs96udSO20sX0H1vW92IL9e1a9rgqVyf91gbPsTy9UD9n9lOkT8k+RfkFR5PMNqxOcdSf32PBvg3vilO+zdxE+okx9Wm0ph36XYsRZCpMF993GOk5qvqB3Dct6jvssb67KvuUNJ3frw92bhr8/STSF0JdRPMLpUCgnsgo9S76PZ246ZFk1wWvK5m3vVoYvW1Sz7nN91jfXbQ1ZQc7TW6HeaoOalypG/8/p/rP1aNAc6ZHzSnfdqPUPhdy2PQw6Nz9gSVhuhiqueUHR3uu7y7K3rdDX4u46ZrPbUa0IFBZ0seKQ3XQTRt2vm3W/a2DbNKys++rvm3ep6+y1x2UdP3bWU9lzra47U1GmlctX/sQ23t+aOlByLTh/4NAPaCRxtcdO5HLSJ/6vNtCwGx67VPmPbvWd1q9frKHtp4kAqRJ2HR9j762JfX3bZ//elPtj13PPDx1+D5tqk/Xi6NO8SHz7MmH19dXrdBNfVFP6T2PT1UHNit87/t4m5+aRH+nQBdvqyhZDKJLfZs8h7XPsqdV2ZOV+tanKB8aln0dyxdAXbV4j4gvt4oMOrbP6vbU73NW7TMlbdTnPrWpfqXfh9HKZ9vke7KuTeZRNtXRSe6+1FV//ce/ln5eXfsXgcqXzr6+9261M3moOoa7E6nvTZTfy7iNsmfb7kjfgXGsvxe0vihsEts9HTquPpt1q1vtahu2TqAiUAEEKj0zhwoARqgAu/OnX/442WH+9xc/Wvr58re/Tr7f41/+ZsRqhAoACFQAEKgAcHjMoQJskJsz/eqrr5Z+vvr7v5fmQFevAl5lztQIFQAQqAAgUAHgIJlDBdhgdQ41N2eKESoAIFABQKACwFEwhwoARqgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAEKgAgUAFAoAKAQAUAgQoACFQAEKgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAQqAAgUAFAoAKAQAUAlvwPcFDns1DsH4sAAAAASUVORK5CYII=",this.logoWidth=468,this.logoHeight=118,this.loadingBarColor=T.White,this.backgroundColor="#176BAA",this.suppressPlayButton=!1,this._playButtonStyles=si.Z.toString(),this.playButtonText="Play game",this.startButtonFactory=()=>{let t=document.getElementById("excalibur-play");return t||(t=document.createElement("button")),t.id="excalibur-play",t.textContent=this.playButtonText,t.style.display="none",t},t&&this.addResources(t)}get _image(){return this._imageElement||(this._imageElement=new Image,this._imageElement.src=this.logo),this._imageElement}get playButtonRootElement(){return this._playButtonRootElement}get playButtonElement(){return this._playButtonElement}get _playButton(){const t=document.getElementById("excalibur-play-root");return t&&(this._playButtonRootElement=t),this._playButtonRootElement||(this._playButtonRootElement=document.createElement("div"),this._playButtonRootElement.id="excalibur-play-root",this._playButtonRootElement.style.position="absolute",document.body.appendChild(this._playButtonRootElement)),this._styleBlock||(this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._playButtonStyles,document.head.appendChild(this._styleBlock)),this._playButtonElement||(this._playButtonElement=this.startButtonFactory(),this._playButtonRootElement.appendChild(this._playButtonElement)),this._playButtonElement}wireEngine(t){this._engine=t,this.canvas.width=this._engine.canvas.width,this.canvas.height=this._engine.canvas.height}addResource(t){const e=this._index++;this._resourceList.push(t),this._progressCounts[e]=0,this._totalCounts[e]=1,this._resourceCount++}addResources(t){let e=0;const i=t.length;for(;e<i;e++)this.addResource(t[e])}isLoaded(){return this._numLoaded===this._resourceCount}showPlayButton(){var t;if(this.suppressPlayButton)return this.hidePlayButton(),Promise.resolve();{const e=()=>{this._positionPlayButton()};(null===(t=this._engine)||void 0===t?void 0:t.browser)&&this._engine.browser.window.on("resize",e),this._playButtonShown=!0,this._playButton.style.display="block",document.body.addEventListener("keyup",(t=>{"Enter"===t.key&&this._playButton.click()}));const i=new Promise((t=>{const i=i=>{var s;i.stopPropagation(),this.hidePlayButton(),(null===(s=this._engine)||void 0===s?void 0:s.browser)&&this._engine.browser.window.off("resize",e),t()};this._playButton.addEventListener("click",i),this._playButton.addEventListener("touchend",i),this._playButton.addEventListener("pointerup",i)}));return i}}hidePlayButton(){this._playButtonShown=!1,this._playButton.style.display="none"}dispose(){this._playButtonRootElement.parentElement&&(this._playButtonRootElement.removeChild(this._playButtonElement),document.body.removeChild(this._playButtonRootElement),document.head.removeChild(this._styleBlock),this._playButtonRootElement=null,this._playButtonElement=null,this._styleBlock=null)}update(t,e){}load(){return ni(this,void 0,void 0,(function*(){return yield Promise.all(this._resourceList.map((t=>t.load().finally((()=>{this._numLoaded++}))))),yield Q(200),yield this.showPlayButton(),yield Ye.unlock(),this.data=this._resourceList}))}markResourceComplete(){this._numLoaded++}get progress(){return this._resourceCount>0?L(this._numLoaded,0,this._resourceCount)/this._resourceCount:1}_positionPlayButton(){const t=this._engine.screen.viewport.height,e=this._engine.screen.viewport.width;if(this._playButtonRootElement){const i=this._engine.canvas.offsetLeft,s=this._engine.canvas.offsetTop,n=this._playButton.clientWidth,r=this._playButton.clientHeight;this.playButtonPosition?(this._playButtonRootElement.style.left=`${this.playButtonPosition.x}px`,this._playButtonRootElement.style.top=`${this.playButtonPosition.y}px`):(this._playButtonRootElement.style.left=i+e/2-n/2+"px",this._playButtonRootElement.style.top=s+t/2-r/2+100+"px")}}draw(t){const e=this._engine.canvasHeight/this._engine.pixelRatio,i=this._engine.canvasWidth/this._engine.pixelRatio;this._positionPlayButton(),t.fillStyle=this.backgroundColor,t.fillRect(0,0,i,e);let s=e/2;const n=Math.min(this.logoWidth,.75*i);let r=i/2-n/2;this.logoPosition&&(r=this.logoPosition.x,s=this.logoPosition.y);const o=Math.floor(n*(this.logoHeight/this.logoWidth)),a=this._engine.getAntialiasing();if(this._engine.setAntialiasing(!0),this.logoPosition?t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,r,s,n,o):t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,r,s-o-20,n,o),!this.suppressPlayButton&&this._playButtonShown)return void this._engine.setAntialiasing(a);let h=r,l=s;this.loadingBarPosition&&(h=this.loadingBarPosition.x,l=this.loadingBarPosition.y),t.lineWidth=2,ei(t,h,l,n,20,10,this.loadingBarColor);const c=n*this.progress-10;ei(t,h+5,l+5,c>10?c:10,10,5,null,this.loadingBarColor),this._engine.setAntialiasing(a)}}const oi={webgl:"WebGL",webaudio:"WebAudio",gamepadapi:"Gamepad API"};class ai{constructor(){this._features=null,this.failedTests=[],this._criticalTests={canvasSupport:function(){const t=document.createElement("canvas");return!(!t.getContext||!t.getContext("2d"))},arrayBufferSupport:function(){const t=new XMLHttpRequest;t.open("GET","/");try{t.responseType="arraybuffer"}catch(t){return!1}return"arraybuffer"===t.responseType},dataUrlSupport:function(){return 0===document.createElement("canvas").toDataURL("image/png").indexOf("data:image/png")},objectUrlSupport:function(){return"URL"in window&&"revokeObjectURL"in URL&&"createObjectURL"in URL},rgbaSupport:function(){const t=document.createElement("a").style;return t.cssText="background-color:rgba(150,255,150,.5)",(""+t.backgroundColor).indexOf("rgba")>-1}},this._warningTest={webAudioSupport:function(){return!!(window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext)},webglSupport:function(){const t=document.createElement("canvas");return!(!t.getContext||!t.getContext("webgl"))}},this._features=this._loadBrowserFeatures()}getBrowserFeatures(){return null===this._features&&(this._features=this._loadBrowserFeatures()),this._features}logBrowserFeatures(){let t="%cSUPPORTED BROWSER FEATURES\n==========================%c\n";const e=["font-weight: bold; color: navy","font-weight: normal; color: inherit"],i=this.getBrowserFeatures();for(const s of Object.keys(oi))i[s]?(t+="(%c✓%c)",e.push("font-weight: bold; color: green"),e.push("font-weight: normal; color: inherit")):(t+="(%c✗%c)",e.push("font-weight: bold; color: red"),e.push("font-weight: normal; color: inherit")),t+=" "+oi[s]+"\n";e.unshift(t),console.log.apply(console,e)}_loadBrowserFeatures(){return{canvas:(()=>this._criticalTests.canvasSupport())(),arraybuffer:(()=>this._criticalTests.arrayBufferSupport())(),dataurl:(()=>this._criticalTests.dataUrlSupport())(),objecturl:(()=>this._criticalTests.objectUrlSupport())(),rgba:(()=>this._criticalTests.rgbaSupport())(),webaudio:(()=>this._warningTest.webAudioSupport())(),webgl:(()=>this._warningTest.webglSupport())(),gamepadapi:!!navigator.getGamepads}}test(){let t=!1;for(const e in this._criticalTests)this._criticalTests[e].call(this)||(this.failedTests.push(e),_.getInstance().error("Critical browser feature missing, Excalibur requires:",e),t=!0);if(t)return!1;for(const t in this._warningTest)this._warningTest[t]()||_.getInstance().warn("Warning browser feature missing, Excalibur will have reduced performance:",t);return!0}}var hi;!function(t){t.PreventCollision="PreventCollision",t.Passive="Passive",t.Active="Active",t.Fixed="Fixed"}(hi||(hi={}));var li,ci,di,ui=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};!function(t){t.Arcade="arcade",t.Realistic="realistic"}(li||(li={})),function(t){t[t.DynamicAABBTree=0]="DynamicAABBTree"}(ci||(ci={})),function(t){t[t.Euler=0]="Euler"}(di||(di={}));class pi{static get gravity(){return pi.acc}static set gravity(t){pi.acc=t}static useArcadePhysics(){pi.collisionResolutionStrategy=li.Arcade}static useRealisticPhysics(){pi.collisionResolutionStrategy=li.Realistic}static get dynamicTreeVelocityMultiplyer(){return pi.dynamicTreeVelocityMultiplier}static set dynamicTreeVelocityMultiplyer(t){pi.dynamicTreeVelocityMultiplier=t}}pi.acc=new A(0,0),pi.enabled=!0,pi.broadphaseStrategy=ci.DynamicAABBTree,pi.collisionResolutionStrategy=li.Arcade,pi.defaultMass=10,pi.integrator=di.Euler,pi.dynamicTreeVelocityMultiplier=2,pi.boundsPadding=5,pi.positionIterations=3,pi.velocityIterations=8,pi.slop=1,pi.steeringFactor=.2,pi.warmStart=!0,pi.bodiesCanSleepByDefault=!1,pi.surfaceEpsilon=.1,pi.sleepEpsilon=.07,pi.wakeThreshold=3*pi.sleepEpsilon,pi.sleepBias=.9,pi.checkForFastBodies=!0,pi.disableMinimumSpeedForFastBody=!1,ui([b({message:"Alias for incorrect spelling used in older versions, will be removed in v0.25.0",alternateMethod:"dynamicTreeVelocityMultiplier"})],pi,"dynamicTreeVelocityMultiplyer",null);class gi extends A{constructor(t){super(0,0),this._getX=t.getX,this._getY=t.getY,this._setX=t.setX,this._setY=t.setY}get x(){return this._x=this._getX()}set x(t){this._setX(t),this._x=t}get y(){return this._y=this._getY()}set y(t){this._setY(t),this._y=t}}class _i{constructor(){this.owner=null}clone(){const t=new this.constructor;for(const i in this)if(this.hasOwnProperty(i)){const s=this[i];(null==(e=s)?void 0:e.clone)&&"owner"!==i&&"clone"!==i?t[i]=s.clone():t[i]=s}var e;return t}}class fi extends _i{constructor(t,e){super(),this.type=t,this.value=e}}var mi;!function(t){t.World="world",t.Screen="screen"}(mi||(mi={}));class yi extends _i{constructor(){super(...arguments),this.type="ex.transform",this._dirty=!1,this.matrix=tt.identity().translate(0,0).rotate(0).scale(1,1),this._position=(t=>{const e=t;return new gi({setX:t=>{e.data[$.X]=t},setY:t=>{e.data[$.Y]=t},getX:()=>e.data[$.X],getY:()=>e.data[$.Y]})})(this.matrix),this._rotation=0,this._scale=(t=>{const e=t;return new gi({setX:t=>{e.setScaleX(t)},setY:t=>{e.setScaleY(t)},getX:()=>e.getScaleX(),getY:()=>e.getScaleY()})})(this.matrix),this.coordPlane=mi.World,this.z=0}_recalculate(){this._rotation=this.matrix.getRotation(),this._dirty=!1}getGlobalMatrix(){return this.parent?this.parent.getGlobalMatrix().multm(this.matrix):this.matrix}getGlobalTransform(){return{pos:this.globalPos,scale:this.globalScale,rotation:this.globalRotation,z:this.z,coordPlane:this.coordPlane}}get parent(){var t,e;return null===(e=null===(t=null==this?void 0:this.owner)||void 0===t?void 0:t.parent)||void 0===e?void 0:e.get(yi)}get pos(){return this._dirty&&this._recalculate(),this._position}set pos(t){this.matrix.setPosition(t.x,t.y),this._dirty=!0}get dirty(){var t;if(null===(t=null==this?void 0:this.owner)||void 0===t?void 0:t.parent){return this.parent.dirty||this._dirty}return this._dirty}get globalPos(){const t=this.getGlobalMatrix();return new gi({getX:()=>t.data[$.X],getY:()=>t.data[$.Y],setX:e=>{var i;if(this.parent){const[s]=null===(i=this.parent)||void 0===i?void 0:i.getGlobalMatrix().getAffineInverse().multv([e,t.data[$.Y]]);this.matrix.data[$.X]=s}else this.matrix.data[$.X]=e},setY:e=>{var i;if(this.parent){const[,s]=null===(i=this.parent)||void 0===i?void 0:i.getGlobalMatrix().getAffineInverse().multv([t.data[$.X],e]);this.matrix.data[$.Y]=s}else this.matrix.data[$.Y]=e}})}set globalPos(t){const e=this.parent;this.pos=e?e.getGlobalMatrix().getAffineInverse().multv(t):t}get rotation(){return this._dirty&&this._recalculate(),this._rotation}set rotation(t){this.matrix.setRotation(t),this._dirty=!0}get globalRotation(){return this.getGlobalMatrix().getRotation()}set globalRotation(t){const e=this.parent;this.rotation=e?t-e.globalRotation:t}get scale(){return this._dirty&&this._recalculate(),this._scale}set scale(t){this.matrix.setScale(t),this._dirty=!0}get globalScale(){const t=this.getGlobalMatrix();return new gi({getX:()=>t.getScaleX(),getY:()=>t.getScaleY(),setX:t=>{if(this.parent){const e=this.parent.globalScale.x;this.matrix.setScaleX(t/e)}else this.matrix.setScaleX(t)},setY:t=>{if(this.parent){const e=this.parent.globalScale.y;this.matrix.setScaleY(t/e)}else this.matrix.setScaleY(t)}})}set globalScale(t){const e=this.parent;this.scale=e?S(t.x/e.globalScale.x,t.y/e.globalScale.y):t}apply(t){return this.matrix.multv(t)}applyInverse(t){return this.matrix.getAffineInverse().multv(t)}}class wi extends _i{constructor(){super(...arguments),this.type="ex.motion",this.vel=A.Zero,this.acc=A.Zero,this.scaleFactor=A.Zero,this.angularVelocity=0,this.torque=0,this.inertia=1}}class vi{constructor(t,e,i){this._name=t,this._category=e,this._mask=i}get name(){return this._name}get category(){return this._category}get mask(){return this._mask}canCollide(t){return 0!=(this.category&t.mask)&&0!=(t.category&this.mask)}invert(){return new vi("~("+this.name+")",~this.category,~this.mask)}static combine(t){const e=t.map((t=>t.name)).join("+"),i=t.reduce(((t,e)=>e.category|t),0);return new vi(e,i,~i)}static collidesWith(t){return vi.combine(t).invert()}}vi.All=new vi("Collide with all groups",-1,-1);class xi{constructor(){this.observers=[],this.subscriptions=[]}register(t){this.observers.push(t)}subscribe(t){this.subscriptions.push(t)}unregister(t){const e=this.observers.indexOf(t);-1!==e&&this.observers.splice(e,1)}unsubscribe(t){const e=this.subscriptions.indexOf(t);-1!==e&&this.subscriptions.splice(e,1)}notifyAll(t){this.observers.forEach((e=>e.notify(t))),this.subscriptions.forEach((e=>e(t)))}clear(){this.observers.length=0,this.subscriptions.length=0}}class bi{constructor(t,e){this.colliderA=t,this.colliderB=e,this.id=null,this.id=bi.calculatePairHash(t.id,e.id)}static canCollide(t,e){var i,s;const n=null===(i=null==t?void 0:t.owner)||void 0===i?void 0:i.get(Wi),r=null===(s=null==e?void 0:e.owner)||void 0===s?void 0:s.get(Wi);return!(!n||!r)&&(!!n.group.canCollide(r.group)&&((n.collisionType!==hi.Fixed||r.collisionType!==hi.Fixed)&&(r.collisionType!==hi.PreventCollision&&n.collisionType!==hi.PreventCollision&&!(!n.active||!r.active))))}get canCollide(){const t=this.colliderA,e=this.colliderB;return bi.canCollide(t,e)}collide(){return this.colliderA.collide(this.colliderB)}hasCollider(t){return t===this.colliderA||t===this.colliderB}static calculatePairHash(t,e){return t.value<e.value?`#${t.value}+${e.value}`:`#${e.value}+${t.value}`}}class Ci{constructor(t,e){this.min=t,this.max=e}overlaps(t){return this.max>t.min&&t.max>this.min}getOverlap(t){return this.overlaps(t)?this.max>t.max?t.max-this.min:this.max-t.min:0}}class Ai{constructor(t){this.parent=t,this.parent=t||null,this.data=null,this.bounds=new B,this.left=null,this.right=null,this.height=0}isLeaf(){return!this.left&&!this.right}}class Si{constructor(t=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)){this.worldBounds=t,this.root=null,this.nodes={}}_insert(t){if(null===this.root)return this.root=t,void(this.root.parent=null);const e=t.bounds;let i=this.root;for(;!i.isLeaf();){const t=i.left,s=i.right,n=i.bounds.getPerimeter(),r=i.bounds.combine(e).getPerimeter(),o=2*r,a=2*(r-n);let h=0;const l=e.combine(t.bounds);let c,d;t.isLeaf()?h=l.getPerimeter()+a:(d=t.bounds.getPerimeter(),c=l.getPerimeter(),h=c-d+a);let u=0;const p=e.combine(s.bounds);if(s.isLeaf()?u=p.getPerimeter()+a:(d=s.bounds.getPerimeter(),c=p.getPerimeter(),u=c-d+a),o<h&&o<u)break;i=h<u?t:s}const s=i.parent,n=new Ai(s);n.bounds=e.combine(i.bounds),n.height=i.height+1,null!==s?(s.left===i?s.left=n:s.right=n,n.left=i,n.right=t,i.parent=n,t.parent=n):(n.left=i,n.right=t,i.parent=n,t.parent=n,this.root=n);let r=t.parent;for(;r;){if(r=this._balance(r),!r.left)throw new Error("Parent of current leaf cannot have a null left child"+r);if(!r.right)throw new Error("Parent of current leaf cannot have a null right child"+r);r.height=1+Math.max(r.left.height,r.right.height),r.bounds=r.left.bounds.combine(r.right.bounds),r=r.parent}}_remove(t){if(t===this.root)return void(this.root=null);const e=t.parent,i=e.parent;let s;if(s=e.left===t?e.right:e.left,i){i.left===e?i.left=s:i.right=s,s.parent=i;let t=i;for(;t;)t=this._balance(t),t.bounds=t.left.bounds.combine(t.right.bounds),t.height=1+Math.max(t.left.height,t.right.height),t=t.parent}else this.root=s,s.parent=null}trackCollider(t){const e=new Ai;e.data=t,e.bounds=t.bounds,e.bounds.left-=2,e.bounds.top-=2,e.bounds.right+=2,e.bounds.bottom+=2,this.nodes[t.id.value]=e,this._insert(e)}updateCollider(t){var e;const i=this.nodes[t.id.value];if(!i)return!1;const s=t.bounds;if(!this.worldBounds.contains(s))return _.getInstance().warn("Collider with id "+t.id.value+" is outside the world bounds and will no longer be tracked for physics"),this.untrackCollider(t),!1;if(i.bounds.contains(s))return!1;if(this._remove(i),s.left-=pi.boundsPadding,s.top-=pi.boundsPadding,s.right+=pi.boundsPadding,s.bottom+=pi.boundsPadding,t.owner){const i=null===(e=t.owner)||void 0===e?void 0:e.get(Wi);if(i){const t=32*i.vel.x/1e3*pi.dynamicTreeVelocityMultiplier,e=32*i.vel.y/1e3*pi.dynamicTreeVelocityMultiplier;t<0?s.left+=t:s.right+=t,e<0?s.top+=e:s.bottom+=e}}return i.bounds=s,this._insert(i),!0}untrackCollider(t){const e=this.nodes[t.id.value];e&&(this._remove(e),this.nodes[t.id.value]=null,delete this.nodes[t.id.value])}_balance(t){if(null===t)throw new Error("Cannot balance at null node");if(t.isLeaf()||t.height<2)return t;const e=t.left,i=t.right,s=t,n=e,r=i,o=e.left,a=e.right,h=i.left,l=i.right,c=r.height-n.height;if(c>1)return r.left=s,r.parent=s.parent,s.parent=r,r.parent?r.parent.left===s?r.parent.left=r:r.parent.right=r:this.root=r,h.height>l.height?(r.right=h,s.right=l,l.parent=s,s.bounds=n.bounds.combine(l.bounds),r.bounds=s.bounds.combine(h.bounds),s.height=1+Math.max(n.height,l.height),r.height=1+Math.max(s.height,h.height)):(r.right=l,s.right=h,h.parent=s,s.bounds=n.bounds.combine(h.bounds),r.bounds=s.bounds.combine(l.bounds),s.height=1+Math.max(n.height,h.height),r.height=1+Math.max(s.height,l.height)),r;if(c<-1){if(n.left=s,n.parent=s.parent,s.parent=n,n.parent)if(n.parent.left===s)n.parent.left=n;else{if(n.parent.right!==s)throw"Error rotating Dynamic Tree";n.parent.right=n}else this.root=n;return o.height>a.height?(n.right=o,s.left=a,a.parent=s,s.bounds=r.bounds.combine(a.bounds),n.bounds=s.bounds.combine(o.bounds),s.height=1+Math.max(r.height,a.height),n.height=1+Math.max(s.height,o.height)):(n.right=a,s.left=o,o.parent=s,s.bounds=r.bounds.combine(o.bounds),n.bounds=s.bounds.combine(a.bounds),s.height=1+Math.max(r.height,o.height),n.height=1+Math.max(s.height,a.height)),n}return t}getHeight(){return null===this.root?0:this.root.height}query(t,e){const i=t.bounds,s=n=>{if(n&&n.bounds.intersect(i)){if(!n.isLeaf()||n.data===t)return s(n.left)||s(n.right);if(e.call(t,n.data))return!0}return!1};s(this.root)}rayCastQuery(t,e=1/0,i){const s=n=>{if(n&&n.bounds.rayCast(t,e)){if(!n.isLeaf())return s(n.left)||s(n.right);if(i.call(t,n.data))return!0}return!1};s(this.root)}getNodes(){const t=e=>e?[e].concat(t(e.left),t(e.right)):[];return t(this.root)}debug(t){const e=i=>{i&&(i.isLeaf()?i.bounds.draw(t,T.Green):i.bounds.draw(t,T.White),i.left&&e(i.left),i.right&&e(i.right))};e(this.root)}}class Pi{constructor(t,e){this.pos=t,this.dir=e.normalize()}intersect(t){const e=t.begin.sub(this.pos);if(0===this.dir.cross(t.getSlope())&&0!==e.cross(this.dir))return-1;const i=this.dir.cross(t.getSlope());if(0===i)return-1;const s=e.cross(t.getSlope())/i;if(s>=0){const n=e.cross(this.dir)/i/t.getLength();if(n>=0&&n<=1)return s}return-1}intersectPoint(t){const e=this.intersect(t);return e<0?null:this.getPoint(e)}getPoint(t){return this.pos.add(this.dir.scale(t))}}class Ei{constructor(){this._dynamicCollisionTree=new Si,this._collisions=new Set,this._collisionPairCache=[],this._colliders=[]}getColliders(){return this._colliders}track(t){if(t)if(t instanceof Ri){const e=t.getColliders();for(const i of e)i.owner=t.owner,this._colliders.push(i),this._dynamicCollisionTree.trackCollider(i)}else this._colliders.push(t),this._dynamicCollisionTree.trackCollider(t);else _.getInstance().warn("Cannot track null collider")}untrack(t){if(t)if(t instanceof Ri){const e=t.getColliders();for(const t of e){const e=this._colliders.indexOf(t);-1!==e&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}}else{const e=this._colliders.indexOf(t);-1!==e&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}else _.getInstance().warn("Cannot untrack a null collider")}_shouldGenerateCollisionPair(t,e){if(null!==t.id&&null!==e.id&&t.id===e.id||null!==t.owner&&null!==e.owner&&t.owner===e.owner)return!1;const i=bi.calculatePairHash(t.id,e.id);return!this._collisions.has(i)&&(!t.localBounds.hasZeroDimensions()&&!e.localBounds.hasZeroDimensions()&&bi.canCollide(t,e))}broadphase(t,e,i){const s=e/1e3,n=t.filter((t=>{var e,i;const s=null===(e=t.owner)||void 0===e?void 0:e.get(Wi);return(null===(i=t.owner)||void 0===i?void 0:i.active)&&s.collisionType!==hi.PreventCollision}));let r;this._collisionPairCache=[],this._collisions.clear();for(let t=0,e=n.length;t<e;t++)r=n[t],this._dynamicCollisionTree.query(r,(t=>{if(this._shouldGenerateCollisionPair(r,t)){const e=new bi(r,t);this._collisions.add(e.id),this._collisionPairCache.push(e)}return!1}));if(i&&(i.physics.pairs=this._collisionPairCache.length),pi.checkForFastBodies)for(const t of n){const e=t.owner.get(Wi);if(e.collisionType!==hi.Active)continue;const n=e.vel.size*s+.5*e.acc.size*s*s,r=Math.min(t.bounds.height,t.bounds.width);if(pi.disableMinimumSpeedForFastBody||n>r/2){i&&i.physics.fastBodies++;const s=e.pos.sub(e.oldPos),r=t.center,o=t.getFurthestPoint(e.vel),a=o.sub(s),h=new Pi(a,e.vel);let l;h.pos=h.pos.add(h.dir.scale(-2*pi.surfaceEpsilon));let c=new A(1/0,1/0);if(this._dynamicCollisionTree.rayCastQuery(h,n+2*pi.surfaceEpsilon,(e=>{if(t!==e&&bi.canCollide(t,e)){const t=e.rayCast(h,n+10*pi.surfaceEpsilon);if(t){const i=t.sub(a);i.size<c.size&&(c=i,l=e)}}return!1})),l&&A.isValid(c)){const s=new bi(t,l);this._collisions.has(s.id)||(this._collisions.add(s.id),this._collisionPairCache.push(s));const n=r.sub(o);e.pos=a.add(n).add(c).add(h.dir.scale(10*pi.surfaceEpsilon)),t.update(e.transform),i&&i.physics.fastBodyCollisions++}}}return this._collisionPairCache}narrowphase(t,e){let i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();if(i=i.concat(n),e&&n.length>0)for(const t of n)e.physics.contacts.set(t.id,t)}return e&&(e.physics.collisions+=i.length),i}update(t){let e=0;const i=t.length;for(let s=0;s<i;s++)this._dynamicCollisionTree.updateCollider(t[s])&&e++;return e}debug(t){this._dynamicCollisionTree.debug(t)}}class Ti{constructor(){this.id=g("collider",Ti._ID++),this.events=new he}touching(t){return!!this.collide(t)}}Ti._ID=0;class Ri extends Ti{constructor(t){super(),this._collisionProcessor=new Ei,this._dynamicAABBTree=new Si,this._colliders=[];for(const e of t)this.addCollider(e)}clearColliders(){this._colliders=[]}addCollider(t){this.events.wire(t.events),this._colliders.push(t),this._collisionProcessor.track(t),this._dynamicAABBTree.trackCollider(t)}removeCollider(t){this.events.unwire(t.events),G(t,this._colliders),this._collisionProcessor.untrack(t),this._dynamicAABBTree.untrackCollider(t)}getColliders(){return this._colliders}get worldPos(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:A.Zero}get center(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:A.Zero}get bounds(){var t,e;const i=this.getColliders();return i.reduce(((t,e)=>t.combine(e.bounds)),null!==(e=null===(t=i[0])||void 0===t?void 0:t.bounds)&&void 0!==e?e:(new B).translate(this.worldPos))}get localBounds(){var t,e;const i=this.getColliders();return i.reduce(((t,e)=>t.combine(e.localBounds)),null!==(e=null===(t=i[0])||void 0===t?void 0:t.localBounds)&&void 0!==e?e:new B)}get axes(){const t=this.getColliders();let e=[];for(const i of t)e=e.concat(i.axes);return e}getFurthestPoint(t){const e=this.getColliders(),i=[];for(const s of e)i.push(s.getFurthestPoint(t));let s=i[0],n=-Number.MAX_VALUE;for(const e of i){const i=e.dot(t);i>n&&(s=e,n=i)}return s}getInertia(t){const e=this.getColliders();let i=0;for(const s of e)i+=s.getInertia(t);return i}collide(t){let e=[t];t instanceof Ri&&(e=t.getColliders());const i=[];for(const t of e)this._dynamicAABBTree.query(t,(e=>(i.push(new bi(t,e)),!1)));let s=[];for(const t of i)s=s.concat(t.collide());return s}getClosestLineBetween(t){const e=this.getColliders(),i=[];if(t instanceof Ri){const s=t.getColliders();for(const t of e)for(const e of s){const s=t.getClosestLineBetween(e);s&&i.push(s)}}else for(const s of e){const e=t.getClosestLineBetween(s);e&&i.push(e)}if(i.length){let t=i[0].getLength(),e=i[0];for(const s of i){const i=s.getLength();i<t&&(t=i,e=s)}return e}return null}contains(t){const e=this.getColliders();for(const i of e)if(i.contains(t))return!0;return!1}rayCast(t,e){const i=this.getColliders(),s=[];for(const n of i){const i=n.rayCast(t,e);i&&s.push(i)}if(s.length){let e=s[0],i=e.dot(t.dir);for(const n of s){const s=t.dir.dot(n);s<i&&(e=n,i=s)}return e}return null}project(t){const e=this.getColliders(),i=[];for(const s of e){const e=s.project(t);e&&i.push(e)}if(i.length){const t=new Ci(i[0].min,i[0].max);for(const e of i)t.min=Math.min(e.min,t.min),t.max=Math.max(e.max,t.max);return t}return null}update(t){if(t){const e=this.getColliders();for(const i of e)i.owner=this.owner,i.update(t)}}draw(t,e,i){const s=this.getColliders();for(const n of s)n.draw(t,e,i)}debug(t,e){const i=this.getColliders();for(const s of i)s.debug(t,e)}debugDraw(t,e){const i=this.getColliders();for(const s of i)s.draw(t,e)}clone(){return new Ri(this._colliders.map((t=>t.clone())))}}class Bi{constructor(t,e){this.begin=t,this.end=e}get slope(){return(this.end.y-this.begin.y)/(this.end.x-this.begin.x)}get intercept(){return this.begin.y-this.slope*this.begin.x}normal(){return this.end.sub(this.begin).normal()}dir(){return this.end.sub(this.begin)}getPoints(){return[this.begin,this.end]}getSlope(){const t=this.begin,e=this.end,i=t.distance(e);return e.sub(t).scale(1/i)}getEdge(){const t=this.begin;return this.end.sub(t)}getLength(){const t=this.begin,e=this.end;return t.distance(e)}get midpoint(){return this.begin.add(this.end).scale(.5)}flip(){return new Bi(this.end,this.begin)}below(t){return(this.end.x-this.begin.x)*(t.y-this.begin.y)-(this.end.y-this.begin.y)*(t.x-this.begin.x)>=0}clip(t,e){let i=t;i=i.normalize();const s=i.dot(this.begin)-e,n=i.dot(this.end)-e,r=[];if(s<=0&&r.push(this.begin),n<=0&&r.push(this.end),s*n<0){const t=s/(s-n);r.push(this.begin.add(this.end.sub(this.begin).scale(t)))}return 2!==r.length?null:new Bi(r[0],r[1])}distanceToPoint(t,e=!1){const i=t.x,s=t.y,n=this.getLength(),r=((this.end.y-this.begin.y)*i-(this.end.x-this.begin.x)*s+this.end.x*this.begin.y-this.end.y*this.begin.x)/n;return e?r:Math.abs(r)}findVectorToPoint(t){const e=this.begin.sub(t),i=this.getSlope();return e.sub(i.scale(e.dot(i)))}findPoint(t=null,e=null){const i=this.slope,s=this.intercept;if(null!==t)return new A(t,i*t+s);if(null!==e)return new A((e-s)/i,e);throw new Error("You must provide an X or a Y value")}hasPoint(){let t,e=0;if("number"==typeof arguments[0]&&"number"==typeof arguments[1])t=new A(arguments[0],arguments[1]),e=arguments[2]||0;else{if(!(arguments[0]instanceof A))throw"Could not determine the arguments for Vector.hasPoint";t=arguments[0],e=arguments[1]||0}const i=t.x-this.begin.x,s=t.y-this.begin.y,n=this.end.x-this.begin.x,r=this.end.y-this.begin.y,o=i*r-s*n;return!(Math.abs(o)>e)&&(Math.abs(n)>=Math.abs(r)?n>0?this.begin.x<=t.x&&t.x<=this.end.x:this.end.x<=t.x&&t.x<=this.begin.x:r>0?this.begin.y<=t.y&&t.y<=this.end.y:this.end.y<=t.y&&t.y<=this.begin.y)}}function Di(t,e,i,s){const n=t.sub(i),r=e.dot(e),o=e.dot(s),a=s.dot(s),h=e.dot(n),l=s.dot(n),c=r*a-o*o;let d=c,u=c;if(0===c||c<=.01){const e=h/o;return new Bi(t,i.add(s.scale(e)))}let p=o*l-a*h,g=r*l-o*h;return p<0?(p=0,g=l,u=a):p>d&&(p=d,g=l+o,u=a),g<0?(g=0,-h<0?p=0:-h>r?p=d:(p=-h,d=r)):g>u&&(g=u,-h+o<0?p=0:-h+o>r?p=d:(p=-h+o,d=r)),p=Math.abs(p)<.001?0:p/d,g=Math.abs(g)<.001?0:g/u,new Bi(t.add(e.scale(p)),i.add(s.scale(g)))}const Mi={PolygonPolygonClosestLine(t,e){const i=e.worldPos,s=i.sub(t.worldPos),n=s.negate(),r=new Pi(t.worldPos,s),o=new Pi(i,n),a=t.rayCast(r).add(r.dir.scale(.1)),h=e.rayCast(o).add(o.dir.scale(.1)),l=t.getClosestFace(a),c=e.getClosestFace(h);return Di(l.face.begin,l.face.getEdge(),c.face.begin,c.face.getEdge())},PolygonEdgeClosestLine(t,e){const i=e.worldPos.sub(t.worldPos),s=new Pi(t.worldPos,i),n=t.rayCast(s).add(s.dir.scale(.1)),r=t.getClosestFace(n),o=r.face.begin,a=r.face.getEdge(),h=e.asLine();return Di(o,a,h.begin,h.getEdge())},PolygonCircleClosestLine(t,e){const i=e.worldPos,s=i.sub(t.worldPos),n=new Pi(t.worldPos,s.normalize()),r=t.rayCast(n).add(n.dir.scale(.1)),o=t.getClosestFace(r),a=o.face.begin,h=o.face.getEdge();let l=(h.x*(i.x-a.x)+h.y*(i.y-a.y))/(h.x*h.x+h.y*h.y);l>1?l=1:l<0&&(l=0);const c=Math.sqrt(Math.pow(a.x+h.x*l-i.x,2)+Math.pow(a.y+h.y*l-i.y,2))-e.radius,d=(a.x+h.x*l-i.x)*e.radius/(e.radius+c),u=(a.y+h.y*l-i.y)*e.radius/(e.radius+c);return new Bi(h.scale(l).add(a),new A(i.x+d,i.y+u))},CircleCircleClosestLine(t,e){const i=e.worldPos.sub(t.worldPos),s=t.worldPos.sub(e.worldPos),n=new Pi(t.worldPos,i),r=new Pi(e.worldPos,s),o=t.rayCast(n),a=e.rayCast(r);return new Bi(o,a)},CircleEdgeClosestLine(t,e){const i=t.worldPos,s=e.asLine(),n=s.begin,r=s.getEdge();let o=(r.x*(i.x-n.x)+r.y*(i.y-n.y))/(r.x*r.x+r.y*r.y);o>1?o=1:o<0&&(o=0);const a=Math.sqrt(Math.pow(n.x+r.x*o-i.x,2)+Math.pow(n.y+r.y*o-i.y,2))-t.radius,h=(n.x+r.x*o-i.x)*t.radius/(t.radius+a),l=(n.y+r.y*o-i.y)*t.radius/(t.radius+a);return new Bi(r.scale(o).add(n),new A(i.x+h,i.y+l))},EdgeEdgeClosestLine(t,e){const i=t.asLine(),s=i.begin,n=i.getEdge(),r=e.asLine();return Di(s,n,r.begin,r.getEdge())}};class Fi extends Ti{constructor(t){super(),this.offset=A.Zero,this.offset=t.offset||A.Zero,this.radius=t.radius||0}get worldPos(){var t,e;return this.offset.add(null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:A.Zero)}clone(){return new Fi({offset:this.offset.clone(),radius:this.radius})}get center(){var t,e;return this.offset.add(null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:A.Zero)}contains(t){var e,i;return(null!==(i=null===(e=this._transform)||void 0===e?void 0:e.pos)&&void 0!==i?i:this.offset).distance(t)<=this.radius}rayCast(t,e=1/0){const i=this.center,s=t.dir,n=t.pos,r=Math.sqrt(Math.pow(s.dot(n.sub(i)),2)-Math.pow(n.sub(i).distance(),2)+Math.pow(this.radius,2));if(r<0)return null;{let o=0;if(0===r)return o=-s.dot(n.sub(i)),o>0&&o<e?t.getPoint(o):null;{const o=-s.dot(n.sub(i))+r,a=-s.dot(n.sub(i))-r,h=[];o>=0&&h.push(o),a>=0&&h.push(a);const l=Math.min(...h);return l<=e?t.getPoint(l):null}}}getClosestLineBetween(t){if(t instanceof Fi)return Mi.CircleCircleClosestLine(this,t);if(t instanceof zi)return Mi.PolygonCircleClosestLine(t,this).flip();if(t instanceof Oi)return Mi.CircleEdgeClosestLine(this,t).flip();throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Fi)return Li.CollideCircleCircle(this,t);if(t instanceof zi)return Li.CollideCirclePolygon(this,t);if(t instanceof Oi)return Li.CollideCircleEdge(this,t);throw new Error("Circle could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){return this.center.add(t.normalize().scale(this.radius))}getFurthestLocalPoint(t){return t.normalize().scale(this.radius)}get bounds(){var t;const e=this._transform,i=null!==(t=null==e?void 0:e.globalPos)&&void 0!==t?t:A.Zero;return new B(this.offset.x+i.x-this.radius,this.offset.y+i.y-this.radius,this.offset.x+i.x+this.radius,this.offset.y+i.y+this.radius)}get localBounds(){return new B(this.offset.x-this.radius,this.offset.y-this.radius,this.offset.x+this.radius,this.offset.y+this.radius)}get axes(){return[]}getInertia(t){return t*this.radius*this.radius/2}update(t){this._transform=t}project(t){const e=[],i=this.center.dot(t);return e.push(i),e.push(i+this.radius),e.push(i-this.radius),new Ci(Math.min.apply(Math,e),Math.max.apply(Math,e))}draw(t,e=T.Green,i=A.Zero){const s=i.add(this.offset);t.beginPath(),t.fillStyle=e.toString(),t.arc(s.x,s.y,this.radius,0,2*Math.PI),t.closePath(),t.fill()}debug(t,e){const i=this._transform,s=(null==i?void 0:i.globalPos)?null==i?void 0:i.globalPos.add(this.offset):this.offset;t.drawCircle(s,this.radius,e)}debugDraw(t,e=T.Green){const i=this._transform,s=i?i.pos.add(this.offset):this.offset,n=i?i.rotation:0;t.beginPath(),t.strokeStyle=e.toString(),t.arc(s.x,s.y,this.radius,0,2*Math.PI),t.closePath(),t.stroke(),t.beginPath(),t.moveTo(s.x,s.y),t.lineTo(Math.cos(n)*this.radius+s.x,Math.sin(n)*this.radius+s.y),t.closePath(),t.stroke()}}class ki{constructor(t,e,i,s,n,r,o,a){this._canceled=!1,this.colliderA=t,this.colliderB=e,this.mtv=i,this.normal=s,this.tangent=n,this.points=r,this.localPoints=o,this.info=a,this.id=bi.calculatePairHash(t.id,e.id)}matchAwake(){const t=this.colliderA.owner.get(Wi),e=this.colliderB.owner.get(Wi);t&&e&&t.sleeping!==e.sleeping&&(t.sleeping&&t.collisionType!==hi.Fixed&&e.sleepMotion>=pi.wakeThreshold&&t.setSleeping(!1),e.sleeping&&e.collisionType!==hi.Fixed&&t.sleepMotion>=pi.wakeThreshold&&e.setSleeping(!1))}isCanceled(){return this._canceled}cancel(){this._canceled=!0}}class Ii{static findPolygonPolygonSeparation(t,e){let i=-Number.MAX_VALUE,s=null,n=null,r=-1,o=null;const a=t.getSides(),h=t.getLocalSides();for(let t=0;t<a.length;t++){const h=a[t],l=h.normal(),c=e.getFurthestPoint(l.negate()),d=h.distanceToPoint(c,!0);d>i&&(i=d,s=h,n=l,r=t,o=c)}return{collider:t,separation:n?i:99,axis:n,side:s,localSide:h[r],sideId:r,point:o,localPoint:n?e.getFurthestLocalPoint(n.negate()):null}}static findCirclePolygonSeparation(t,e){const i=e.axes,s=e.center.sub(t.worldPos),n=e.getFurthestPoint(s.negate());i.push(n.sub(t.worldPos).normalize());let r=Number.MAX_VALUE,o=null,a=-1;for(let s=0;s<i.length;s++){const n=e.project(i[s]),h=t.project(i[s]),l=n.getOverlap(h);if(l<=0)return null;l<r&&(r=l,o=i[s],a=s)}return a<0?null:o.normalize().scale(r)}}const Li={CollideCircleCircle(t,e){const i=t.worldPos,s=e.worldPos,n=t.radius+e.radius,r=i.distance(s);if(r>n)return[];const o=n-r,a=s.sub(i).normalize(),h=a.perpendicular(),l=a.scale(o),c=t.getFurthestPoint(a),d=t.getFurthestLocalPoint(a);return[new ki(t,e,l,a,h,[c],[d],{collider:t,separation:o,axis:a,point:c})]},CollideCirclePolygon(t,e){var i,s;let n=Ii.findCirclePolygonSeparation(t,e);if(!n)return[];const r=n.dot(e.center.sub(t.center));n=r<0?n.negate():n;const o=t.getFurthestPoint(n),a=(null!==(s=null===(i=t.owner)||void 0===i?void 0:i.get(yi))&&void 0!==s?s:new yi).applyInverse(o),h=n.normalize(),l={collider:t,separation:-n.size,axis:h,point:o,localPoint:a,side:e.findSide(h.negate()),localSide:e.findLocalSide(h.negate())};return[new ki(t,e,n,h,h.perpendicular(),[o],[a],l)]},CollideCircleEdge(t,e){const i=t.center,s=e.asLine(),n=s.end.sub(s.begin),r=n.dot(s.end.sub(i)),o=n.dot(i.sub(s.begin)),a=e.asLine(),h=e.asLocalLine();if(o<=0){const n=s.begin.sub(i),r=n.dot(n);if(r>t.radius*t.radius)return[];const o=n.normalize(),l=t.radius-Math.sqrt(r),c={collider:t,separation:l,axis:o,point:a.begin,side:a,localSide:h};return[new ki(t,e,o.scale(l),o,o.perpendicular(),[a.begin],[h.begin],c)]}if(r<=0){const n=s.end.sub(i),r=n.dot(n);if(r>t.radius*t.radius)return[];const o=n.normalize(),l=t.radius-Math.sqrt(r),c={collider:t,separation:l,axis:o,point:a.end,side:a,localSide:h};return[new ki(t,e,o.scale(l),o,o.perpendicular(),[a.end],[h.end],c)]}const l=n.dot(n),c=s.begin.scale(r).add(s.end.scale(o)).scale(1/l),d=i.sub(c),u=d.dot(d);if(u>t.radius*t.radius)return[];let p=n.perpendicular();p.dot(i.sub(s.begin))<0&&(p.x=-p.x,p.y=-p.y),p=p.normalize();const g=t.radius-Math.sqrt(u),_=p.scale(g),f={collider:t,separation:g,axis:p,point:c,side:a,localSide:h};return[new ki(t,e,_,p.negate(),p.negate().perpendicular(),[c],[c.sub(e.worldPos)],f)]},CollideEdgeEdge:()=>[],CollidePolygonEdge(t,e){var i;const s=t.center,n=e.center.sub(s).normalize(),r=new zi({points:[e.begin,e.end,e.end.add(n.scale(100)),e.begin.add(n.scale(100))],offset:e.offset});r.owner=e.owner;(null===(i=e.owner)||void 0===i?void 0:i.get(yi))&&r.update(e.owner.get(yi));const o=this.CollidePolygonPolygon(t,r);return o.length&&(o[0].colliderB=e,o[0].id=bi.calculatePairHash(t.id,e.id)),o},CollidePolygonPolygon(t,e){var i,s,n,r;const o=Ii.findPolygonPolygonSeparation(t,e);if(o.separation>0)return[];const a=Ii.findPolygonPolygonSeparation(e,t);if(a.separation>0)return[];const h=o.separation>a.separation?o:a,l=(h.collider===t?e:t).findSide(h.axis.negate()),c=h.side,d=c.dir().normalize(),u=l.clip(d.negate(),-d.dot(c.begin));let p=null;if(u&&(p=u.clip(d,d.dot(c.end))),p){const o=p.getPoints().filter((t=>c.below(t)));let a=h.axis,l=a.perpendicular();e.worldPos.sub(t.worldPos).dot(a)<0&&(a=a.negate(),l=a.perpendicular());let d=[];if(h.collider===t){const t=null!==(s=null===(i=e.owner)||void 0===i?void 0:i.get(yi))&&void 0!==s?s:new yi;d=o.map((e=>t.applyInverse(e)))}else{const e=null!==(r=null===(n=t.owner)||void 0===n?void 0:n.get(yi))&&void 0!==r?r:new yi;d=o.map((t=>e.applyInverse(t)))}return[new ki(t,e,a.scale(-h.separation),a,l,o,d,h)]}return[]},FindContactSeparation(t,e){var i,s,n,r;const o=t.colliderA,a=null!==(s=null===(i=t.colliderA.owner)||void 0===i?void 0:i.get(yi))&&void 0!==s?s:new yi,h=t.colliderB,l=null!==(r=null===(n=t.colliderB.owner)||void 0===n?void 0:n.get(yi))&&void 0!==r?r:new yi;if(o instanceof Fi&&h instanceof Fi){return-(o.radius+h.radius-a.pos.distance(l.pos))}if(o instanceof zi&&h instanceof zi&&t.info.localSide){let i,s;return t.info.collider===o?(i=new Bi(a.apply(t.info.localSide.begin),a.apply(t.info.localSide.end)),s=l.apply(e)):(i=new Bi(l.apply(t.info.localSide.begin),l.apply(t.info.localSide.end)),s=a.apply(e)),i.distanceToPoint(s,!0)}if(o instanceof zi&&h instanceof Fi||h instanceof zi&&o instanceof Fi){const i=a.apply(e);if(t.info.side)return t.info.side.distanceToPoint(i,!0)}if(o instanceof Oi&&h instanceof zi||h instanceof Oi&&o instanceof zi){let i;if(i=t.info.collider===o?l.apply(e):a.apply(e),t.info.side)return t.info.side.distanceToPoint(i,!0)}if(o instanceof Fi&&h instanceof Oi||h instanceof Fi&&o instanceof Oi){const i=l.apply(e);let s;o instanceof Fi&&(s=o.getFurthestPoint(t.normal));const n=i.distance(s);if(t.info.side)return n>0?-n:0}return 0}};class Oi extends Ti{constructor(t){var e;super(),this.begin=t.begin||A.Zero,this.end=t.end||A.Zero,this.offset=null!==(e=t.offset)&&void 0!==e?e:A.Zero}clone(){return new Oi({begin:this.begin.clone(),end:this.end.clone()})}get worldPos(){var t;const e=this._transform;return null!==(t=null==e?void 0:e.globalPos.add(this.offset))&&void 0!==t?t:this.offset}get center(){return this.begin.average(this.end).add(this._getBodyPos())}_getBodyPos(){var t;const e=this._transform;return null!==(t=null==e?void 0:e.globalPos)&&void 0!==t?t:A.Zero}_getTransformedBegin(){const t=this._transform,e=t?t.globalRotation:0;return this.begin.rotate(e).add(this._getBodyPos())}_getTransformedEnd(){const t=this._transform,e=t?t.globalRotation:0;return this.end.rotate(e).add(this._getBodyPos())}getSlope(){const t=this._getTransformedBegin(),e=this._getTransformedEnd(),i=t.distance(e);return e.sub(t).scale(1/i)}getLength(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.distance(e)}contains(){return!1}rayCast(t,e=1/0){const i=this._getTransformedBegin().sub(t.pos);if(0===t.dir.cross(this.getSlope())&&0!==i.cross(t.dir))return null;const s=t.dir.cross(this.getSlope());if(0===s)return null;const n=i.cross(this.getSlope())/s;if(n>=0&&n<=e){const e=i.cross(t.dir)/s/this.getLength();if(e>=0&&e<=1)return t.getPoint(n)}return null}getClosestLineBetween(t){if(t instanceof Fi)return Mi.CircleEdgeClosestLine(t,this);if(t instanceof zi)return Mi.PolygonEdgeClosestLine(t,this).flip();if(t instanceof Oi)return Mi.EdgeEdgeClosestLine(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Fi)return Li.CollideCircleEdge(t,this);if(t instanceof zi)return Li.CollidePolygonEdge(t,this);if(t instanceof Oi)return Li.CollideEdgeEdge();throw new Error("Edge could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){const e=this._getTransformedBegin(),i=this._getTransformedEnd();return t.dot(e)>0?e:i}_boundsFromBeginEnd(t,e,i=10){return new B(Math.min(t.x,e.x)-i,Math.min(t.y,e.y)-i,Math.max(t.x,e.x)+i,Math.max(t.y,e.y)+i)}get bounds(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return this._boundsFromBeginEnd(t,e)}get localBounds(){return this._boundsFromBeginEnd(this.begin,this.end)}asLine(){return new Bi(this._getTransformedBegin(),this._getTransformedEnd())}asLocalLine(){return new Bi(this.begin,this.end)}get axes(){const t=this._getTransformedEnd().sub(this._getTransformedBegin()).normal(),e=[];return e.push(t),e.push(t.negate()),e.push(t.normal()),e.push(t.normal().negate()),e}getInertia(t){const e=this.end.sub(this.begin).distance()/2;return t*e*e}update(t){this._transform=t}project(t){const e=[],i=[this._getTransformedBegin(),this._getTransformedEnd()],s=i.length;for(let n=0;n<s;n++)e.push(i[n].dot(t));return new Ci(Math.min.apply(Math,e),Math.max.apply(Math,e))}draw(t,e=T.Green,i=A.Zero){const s=this.begin.add(i),n=this.end.add(i);t.strokeStyle=e.toString(),t.beginPath(),t.moveTo(s.x,s.y),t.lineTo(n.x,n.y),t.closePath(),t.stroke()}debug(t,e){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.drawLine(i,s,e,2),t.drawCircle(i,2,e),t.drawCircle(s,2,e)}debugDraw(t,e=T.Red){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.strokeStyle=e.toString(),t.beginPath(),t.moveTo(i.x,i.y),t.lineTo(s.x,s.y),t.closePath(),t.stroke()}}class zi extends Ti{constructor(t){var e;super(),this._transformedPoints=[],this._axes=[],this._sides=[],this._localSides=[],this.offset=null!==(e=t.offset)&&void 0!==e?e:A.Zero;const i=!!t.clockwiseWinding;this.points=(i?t.points.reverse():t.points)||[],this._calculateTransformation()}clone(){return new zi({offset:this.offset.clone(),points:this.points.map((t=>t.clone()))})}get worldPos(){return this._transform?this._transform.pos.add(this.offset):this.offset}get center(){return this.bounds.center}_calculateTransformation(){const t=this._transform,e=t?t.globalPos.add(this.offset):this.offset,i=t?t.globalRotation:0,s=t?t.globalScale:A.One,n=this.points.length;this._transformedPoints.length=0;for(let t=0;t<n;t++)this._transformedPoints[t]=this.points[t].scale(s).rotate(i).add(e)}getTransformedPoints(){return this._calculateTransformation(),this._transformedPoints}getSides(){if(this._sides.length)return this._sides;const t=[],e=this.getTransformedPoints(),i=e.length;for(let s=0;s<i;s++)t.push(new Bi(e[s],e[(s+1)%i]));return this._sides=t,this._sides}getLocalSides(){if(this._localSides.length)return this._localSides;const t=[],e=this.points,i=e.length;for(let s=0;s<i;s++)t.push(new Bi(e[s],e[(s+1)%i]));return this._localSides=t,this._localSides}findSide(t){const e=this.getSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=e[n],o=r.normal().dot(t);o>s&&(i=r,s=o)}return i}findLocalSide(t){const e=this.getLocalSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=e[n],o=r.normal().dot(t);o>s&&(i=r,s=o)}return i}get axes(){if(this._axes.length)return this._axes;const t=this.getSides().map((t=>t.normal()));return this._axes=t,this._axes}update(t){this._transform=t,this._sides.length=0,this._localSides.length=0,this._axes.length=0,this._transformedPoints.length=0,this.getTransformedPoints(),this.getSides(),this.getLocalSides()}contains(t){const e=new Pi(t,new A(1,0));return this.getSides().reduce((function(t,i){return e.intersect(i)>=0?t+1:t}),0)%2!=0}getClosestLineBetween(t){if(t instanceof Fi)return Mi.PolygonCircleClosestLine(this,t);if(t instanceof zi)return Mi.PolygonPolygonClosestLine(this,t);if(t instanceof Oi)return Mi.PolygonEdgeClosestLine(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Fi)return Li.CollideCirclePolygon(t,this);if(t instanceof zi)return Li.CollidePolygonPolygon(this,t);if(t instanceof Oi)return Li.CollidePolygonEdge(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){const e=this.getTransformedPoints();let i=null,s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=t.dot(e[n]);r>s&&(s=r,i=e[n])}return i}getFurthestLocalPoint(t){const e=this.points;let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=t.dot(e[n]);r>s&&(s=r,i=e[n])}return i}getClosestFace(t){const e=this.getSides();let i=Number.POSITIVE_INFINITY,s=-1,n=-1;for(let r=0;r<e.length;r++){const o=e[r].distanceToPoint(t);o<i&&(i=o,s=r,n=o)}return-1!==s?{distance:e[s].normal().scale(n),face:e[s]}:null}get bounds(){var t,e,i;const s=this._transform,n=null!==(t=null==s?void 0:s.globalScale)&&void 0!==t?t:A.One,r=null!==(e=null==s?void 0:s.globalRotation)&&void 0!==e?e:0,o=(null!==(i=null==s?void 0:s.globalPos)&&void 0!==i?i:A.Zero).add(this.offset);return this.localBounds.scale(n).rotate(r).translate(o)}get localBounds(){return B.fromPoints(this.points)}getInertia(t){let e=0,i=0;for(let t=0;t<this.points.length;t++){const s=(t+1)%this.points.length,n=this.points[s].cross(this.points[t]);e+=n*(this.points[t].dot(this.points[t])+this.points[t].dot(this.points[s])+this.points[s].dot(this.points[s])),i+=n}return t/6*(e/i)}rayCast(t,e=1/0){const i=this.getSides(),s=i.length;let n=Number.MAX_VALUE,r=-1;for(let o=0;o<s;o++){const s=t.intersect(i[o]);s>=0&&s<n&&s<=e&&(n=s,r=o)}return r>=0?t.getPoint(n):null}project(t){const e=this.getTransformedPoints(),i=e.length;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let r=0;r<i;r++){const i=e[r].dot(t);s=Math.min(s,i),n=Math.max(n,i)}return new Ci(s,n)}draw(t,e=T.Green,i=A.Zero){const s=i.add(this.offset);t.beginPath(),t.fillStyle=e.toString();const n=this.points[0].add(s);t.moveTo(n.x,n.y),this.points.map((t=>t.add(s))).forEach((function(e){t.lineTo(e.x,e.y)})),t.lineTo(n.x,n.y),t.closePath(),t.fill()}debug(t,e){const i=this.getTransformedPoints()[0],s=[i,...this.getTransformedPoints(),i];for(let i=0;i<s.length-1;i++)t.drawLine(s[i],s[i+1],e,2),t.drawCircle(s[i],2,e),t.drawCircle(s[i+1],2,e)}debugDraw(t,e=T.Red){t.beginPath(),t.strokeStyle=e.toString();const i=this.getTransformedPoints()[0];t.moveTo(i.x,i.y),this.getTransformedPoints().forEach((function(e){t.lineTo(e.x,e.y)})),t.lineTo(i.x,i.y),t.closePath(),t.stroke()}}class Ui{static Box(t,e,i=A.Half,s=A.Zero){return new zi({points:new B(-t*i.x,-e*i.y,t-t*i.x,e-e*i.y).getPoints(),offset:s})}static Polygon(t,e=!1,i=A.Zero){return new zi({points:t,offset:i,clockwiseWinding:e})}static Circle(t,e=A.Zero){return new Fi({radius:t,offset:e})}static Edge(t,e){return new Oi({begin:t,end:e})}static Capsule(t,e,i=A.Zero){const s=_.getInstance();t===e&&s.warn("A capsule collider with equal width and height is a circle, consider using a ex.Shape.Circle or ex.CircleCollider");if(e>=t){return new Ri([Ui.Circle(t/2,S(0,-e/2+t/2).add(i)),Ui.Box(t,e-t,A.Half,i),Ui.Circle(t/2,S(0,e/2-t/2).add(i))])}return new Ri([Ui.Circle(e/2,S(-t/2+e/2,0).add(i)),Ui.Box(t-e,e,A.Half,i),Ui.Circle(e/2,S(t/2-e/2,0).add(i))])}}class Hi extends _i{constructor(t){super(),this.type="ex.collider",this.events=new he,this.$colliderAdded=new xi,this.$colliderRemoved=new xi,this.set(t)}get(){return this._collider}set(t){return this.clear(),t&&(this._collider=t,this._collider.owner=this.owner,this.events.wire(t.events),this.$colliderAdded.notifyAll(t),this.update()),t}clear(){this._collider&&(this.events.unwire(this._collider.events),this.$colliderRemoved.notifyAll(this._collider),this._collider.owner=null,this._collider=null)}get bounds(){var t,e;return null!==(e=null===(t=this._collider)||void 0===t?void 0:t.bounds)&&void 0!==e?e:new B}get localBounds(){var t,e;return null!==(e=null===(t=this._collider)||void 0===t?void 0:t.localBounds)&&void 0!==e?e:new B}update(){var t;const e=null===(t=this.owner)||void 0===t?void 0:t.get(yi);this._collider&&(this._collider.owner=this.owner,e&&this._collider.update(e))}collide(t){let e=this._collider,i=t._collider;if(!e||!i)return[];let s=!1;if(i instanceof Ri&&(e=i,i=this._collider,s=!0),this._collider){const n=e.collide(i);return n?(s&&n.forEach((e=>{e.mtv=e.mtv.negate(),e.normal=e.normal.negate(),e.tangent=e.normal.perpendicular(),e.colliderA=this._collider,e.colliderB=t._collider})),n):[]}return[]}onAdd(t){this._collider&&this.update(),this.events.on("precollision",(e=>{const i=e;t.events.emit("precollision",new qt(i.target.owner,i.other.owner,i.side,i.intersection))})),this.events.on("postcollision",(e=>{const i=e;t.events.emit("postcollision",new Kt(i.target.owner,i.other.owner,i.side,i.intersection))})),this.events.on("collisionstart",(e=>{const i=e;t.events.emit("collisionstart",new Jt(i.target.owner,i.other.owner,i.contact))})),this.events.on("collisionend",(e=>{const i=e;t.events.emit("collisionend",new te(i.target.owner,i.other.owner))}))}onRemove(){this.events.clear(),this.$colliderRemoved.notifyAll(this._collider)}useBoxCollider(t,e,i=A.Half,s=A.Zero){const n=Ui.Box(t,e,i,s);return this.set(n)}usePolygonCollider(t,e=A.Zero){const i=Ui.Polygon(t,!1,e);return this.set(i)}useCircleCollider(t,e=A.Zero){const i=Ui.Circle(t,e);return this.set(i)}useEdgeCollider(t,e){const i=Ui.Edge(t,e);return this.set(i)}useCompositeCollider(t){return this.set(new Ri(t))}}var Ni;!function(t){t.Rotation="rotation",t.X="x",t.Y="y"}(Ni||(Ni={}));class Wi extends _i{constructor(t){var e,i,s;super(),this.type="ex.body",this.dependencies=[yi,wi],this.id=g("body",Wi._ID++),this.events=new he,this.collisionType=hi.PreventCollision,this.group=vi.All,this.mass=pi.defaultMass,this.sleepMotion=5*pi.sleepEpsilon,this.canSleep=pi.bodiesCanSleepByDefault,this._sleeping=!1,this.bounciness=.2,this.friction=.99,this.useGravity=!0,this.limitDegreeOfFreedom=[],this.oldPos=new A(0,0),this.oldVel=new A(0,0),this.oldAcc=A.Zero,this.oldRotation=0,this.oldScale=A.One,t&&(this.collisionType=null!==(e=t.type)&&void 0!==e?e:this.collisionType,this.group=null!==(i=t.group)&&void 0!==i?i:this.group,this.useGravity=null!==(s=t.useGravity)&&void 0!==s?s:this.useGravity)}get inverseMass(){return this.collisionType===hi.Fixed?0:1/this.mass}get sleeping(){return this._sleeping}setSleeping(t){this._sleeping=t,t?(this.vel=A.Zero,this.acc=A.Zero,this.angularVelocity=0,this.sleepMotion=0):this.sleepMotion=5*pi.sleepEpsilon}updateMotion(){this._sleeping&&this.setSleeping(!0);const t=this.vel.size*this.vel.size+Math.abs(this.angularVelocity*this.angularVelocity),e=pi.sleepBias;this.sleepMotion=e*this.sleepMotion+(1-e)*t,this.sleepMotion=L(this.sleepMotion,0,10*pi.sleepEpsilon),this.canSleep&&this.sleepMotion<pi.sleepEpsilon&&this.setSleeping(!0)}get inertia(){const t=this.owner.get(Hi);return(null==t?void 0:t.get())?t.get().getInertia(this.mass):0}get inverseInertia(){return this.collisionType===hi.Fixed?0:1/this.inertia}get active(){var t;return!!(null===(t=this.owner)||void 0===t?void 0:t.active)}get center(){return this.pos}get transform(){var t;return null===(t=this.owner)||void 0===t?void 0:t.get(yi)}get motion(){var t;return null===(t=this.owner)||void 0===t?void 0:t.get(wi)}get pos(){return this.transform.globalPos}set pos(t){this.transform.globalPos=t}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t}get torque(){return this.motion.torque}set torque(t){this.motion.torque=t}get rotation(){return this.transform.globalRotation}set rotation(t){this.transform.globalRotation=t}get scale(){return this.transform.globalScale}set scale(t){this.transform.globalScale=t}get sx(){return this.motion.scaleFactor.x}set sx(t){this.motion.scaleFactor.x=t}get sy(){return this.motion.scaleFactor.y}set sy(t){this.motion.scaleFactor.y=t}get rx(){return this.motion.angularVelocity}set rx(t){this.motion.angularVelocity=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}applyImpulse(t,e){if(this.collisionType!==hi.Active)return;const i=e.scale(this.inverseMass);if(this.limitDegreeOfFreedom.includes(Ni.X)&&(i.x=0),this.limitDegreeOfFreedom.includes(Ni.Y)&&(i.y=0),this.vel.addEqual(i),!this.limitDegreeOfFreedom.includes(Ni.Rotation)){const i=t.sub(this.pos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}applyLinearImpulse(t){if(this.collisionType!==hi.Active)return;const e=t.scale(this.inverseMass);this.limitDegreeOfFreedom.includes(Ni.X)&&(e.x=0),this.limitDegreeOfFreedom.includes(Ni.Y)&&(e.y=0),this.vel=this.vel.add(e)}applyAngularImpulse(t,e){if(this.collisionType===hi.Active&&!this.limitDegreeOfFreedom.includes(Ni.Rotation)){const i=t.sub(this.pos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}captureOldTransform(){this.oldVel.setTo(this.vel.x,this.vel.y),this.oldPos.setTo(this.pos.x,this.pos.y),this.oldAcc.setTo(this.acc.x,this.acc.y),this.oldScale.setTo(this.scale.x,this.scale.y),this.oldRotation=this.rotation}debugDraw(t){}}Wi._ID=0;class Vi{constructor(){this._topLeft=new A(0,0),this._topRight=new A(0,0),this._bottomLeft=new A(0,0),this._bottomRight=new A(0,0)}isSpriteOffScreen(t,e){const i=t.currentDrawing.drawWidth,s=t.currentDrawing.drawHeight,n=t.rotation,r=t.center,o=t.getGlobalPos();this._topLeft=S(o.x-i/2,o.y-s/2),this._topLeft=this._topLeft.rotate(n,r),this._topRight=S(o.x+i/2,o.y-s/2),this._topRight=this._topRight.rotate(n,r),this._bottomLeft=S(o.x-i/2,o.y+s/2),this._bottomLeft=this._bottomLeft.rotate(n,r),this._bottomRight=S(o.x+i/2,o.y+s/2),this._bottomRight=this._bottomRight.rotate(n,r);const a=e.worldToScreenCoordinates(this._topLeft),h=e.worldToScreenCoordinates(this._topRight),l=e.worldToScreenCoordinates(this._bottomLeft),c=e.worldToScreenCoordinates(this._bottomRight);this._xCoords=[],this._yCoords=[],this._xCoords.push(a.x,h.x,l.x,c.x),this._yCoords.push(a.y,h.y,l.y,c.y),this._xMin=Math.min.apply(null,this._xCoords),this._yMin=Math.min.apply(null,this._yCoords),this._xMax=Math.max.apply(null,this._xCoords),this._yMax=Math.max.apply(null,this._yCoords);const d=e.screenToWorldCoordinates(new A(this._xMin,this._yMin)),u=e.screenToWorldCoordinates(new A(this._xMax,this._yMax));this._xMinWorld=d.x,this._yMinWorld=d.y,this._xMaxWorld=u.x,this._yMaxWorld=u.y;const p=[new A(this._xMin,this._yMin),new A(this._xMax,this._yMin),new A(this._xMin,this._yMax),new A(this._xMax,this._yMax)];if(p[0].x<0&&p[1].x>e.canvas.clientWidth&&(p[0].y>0||p[2].y<e.canvas.clientHeight))return!1;if(p[0].y<0&&p[2].y>e.canvas.clientHeight&&(p[1].x>0||p[0].x<e.canvas.clientWidth))return!1;for(let t=0;t<p.length;t++)if(p[t].x>0&&p[t].y>0&&p[t].x<e.canvas.clientWidth&&p[t].y<e.canvas.clientHeight)return!1;return!0}debugDraw(t){t.beginPath(),t.strokeStyle=T.White.toString(),t.rect(this._xMinWorld,this._yMinWorld,this._xMaxWorld-this._xMinWorld,this._yMaxWorld-this._yMinWorld),t.stroke(),t.fillStyle=T.Red.toString(),t.beginPath(),t.arc(this._topLeft.x,this._topLeft.y,5,0,2*Math.PI),t.closePath(),t.fill(),t.fillStyle=T.Green.toString(),t.beginPath(),t.arc(this._topRight.x,this._topRight.y,5,0,2*Math.PI),t.closePath(),t.fill(),t.fillStyle=T.Blue.toString(),t.beginPath(),t.arc(this._bottomLeft.x,this._bottomLeft.y,5,0,2*Math.PI),t.closePath(),t.fill(),t.fillStyle=T.Magenta.toString(),t.beginPath(),t.arc(this._bottomRight.x,this._bottomRight.y,5,0,2*Math.PI),t.closePath(),t.fill()}}class Gi{constructor(){this.cullingBox=new Vi}update(t,e){const i=t.eventDispatcher;let s=!0;null!=t.currentDrawing&&(s=this.cullingBox.isSpriteOffScreen(t,e));let n=!1;e&&e.currentScene&&e.currentScene.camera&&e.currentScene.camera.viewport&&!t.parent&&(n=!e.currentScene.camera.viewport.intersect(t.collider.bounds)),t.isOffScreen?n&&s||(i.emit("enterviewport",new re(t)),t.removeComponent("offscreen")):n&&s&&(i.emit("exitviewport",new ne(t)),t.addComponent(new fi("offscreen")))}}class ji{constructor(t){this.data=t,this.type="Component Added"}}function Xi(t){return!!t&&"Component Added"===t.type}class qi{constructor(t){this.data=t,this.type="Component Removed"}}function Ki(t){return!!t&&"Component Removed"===t.type}class Zi extends Qe{constructor(t,e){if(super(),this.id=Zi._ID++,this._name="anonymous",this.active=!0,this._componentsToRemove=[],this._componentTypeToInstance=new Map,this._componentStringToInstance=new Map,this._tagsMemo=[],this._typesMemo=[],this.componentAdded$=new xi,this.componentRemoved$=new xi,this._parent=null,this.childrenAdded$=new xi,this.childrenRemoved$=new xi,this._children=[],this._isInitialized=!1,this._setName(e),t)for(const e of t)this.addComponent(e)}_setName(t){t&&(this._name=t)}get name(){return this._name}get events(){return this.eventDispatcher}kill(){this.active=!1}isKilled(){return!this.active}get tags(){return this._tagsMemo}hasTag(t){return this.tags.includes(t)}addTag(t){return this.addComponent(new fi(t))}removeTag(t,e=!1){return this.removeComponent(t,e)}get types(){return this._typesMemo}_rebuildMemos(){this._tagsMemo=Array.from(this._componentStringToInstance.values()).filter((t=>t instanceof fi)).map((t=>t.type)),this._typesMemo=Array.from(this._componentStringToInstance.keys())}getComponents(){return Array.from(this._componentStringToInstance.values())}_notifyAddComponent(t){this._rebuildMemos();const e=new ji({component:t,entity:this});this.componentAdded$.notifyAll(e)}_notifyRemoveComponent(t){const e=new qi({component:t,entity:this});this.componentRemoved$.notifyAll(e),this._rebuildMemos()}get parent(){return this._parent}get children(){return this._children}unparent(){this._parent&&(this._parent.removeChild(this),this._parent=null)}addChild(t){if(null!==t.parent)throw new Error("Entity already has a parent, cannot add without unparenting");if(this.getAncestors().includes(t))throw new Error("Cycle detected, cannot add entity");return this._children.push(t),t._parent=this,this.childrenAdded$.notifyAll(t),this}removeChild(t){return t.parent===this&&(G(t,this._children),t._parent=null,this.childrenRemoved$.notifyAll(t)),this}removeAllChildren(){return this.children.forEach((t=>{this.removeChild(t)})),this}getAncestors(){const t=[this];let e=this.parent;for(;e;)t.push(e),e=e.parent;return t.reverse()}getDescendants(){let t=[this],e=[this];for(;e.length>0;){const i=e.pop();e=e.concat(i.children),t=t.concat(i.children)}return t}clone(){const t=new Zi;for(const e of this.types)t.addComponent(this.get(e).clone());for(const e of this.children)t.addChild(e.clone());return t}addTemplate(t,e=!1){for(const i of t.getComponents())this.addComponent(i.clone(),e);for(const e of t.children)this.addChild(e.clone().addTemplate(e));return this}addComponent(t,e=!1){if(this.has(t.type)){if(!e)return this;this.removeComponent(t)}if(t.dependencies&&t.dependencies.length)for(const e of t.dependencies)this.addComponent(new e);t.owner=this;const i=t.constructor;return this._componentTypeToInstance.set(i,t),this._componentStringToInstance.set(t.type,t),t.onAdd&&t.onAdd(this),this._notifyAddComponent(t),this}removeComponent(t,e=!1){return e?"string"==typeof t?this._removeComponentByType(t):t instanceof _i&&this._removeComponentByType(t.type):this._componentsToRemove.push(t),this}_removeComponentByType(t){if(this.has(t)){const e=this.get(t);e.owner=null,e.onRemove&&e.onRemove(this);const i=e.constructor;this._componentTypeToInstance.delete(i),this._componentStringToInstance.delete(e.type),this._notifyRemoveComponent(e)}}processComponentRemoval(){for(const t of this._componentsToRemove){const e="string"==typeof t?t:t.type;this._removeComponentByType(e)}this._componentsToRemove.length=0}has(t){return"string"==typeof t?this._componentStringToInstance.has(t):this._componentTypeToInstance.has(t)}get(t){return"string"==typeof t?this._componentStringToInstance.get(t):this._componentTypeToInstance.get(t)}get isInitialized(){return this._isInitialized}_initialize(t){this.isInitialized||(this.onInitialize(t),super.emit("initialize",new ee(t,this)),this._isInitialized=!0)}_preupdate(t,e){this.emit("preupdate",new It(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new Lt(t,e,this)),this.onPostUpdate(t,e)}onInitialize(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this._initialize(t),this._preupdate(t,e);for(const i of this.children)i.update(t,e);this._postupdate(t,e)}}Zi._ID=0;class Yi extends _i{constructor(t){var e;super(),this.draw=t,this.type="ex.canvas",this.draw=null!==(e=this.draw)&&void 0!==e?e:()=>{}}}function Qi(t){return!!t.tick}class $i{constructor(t,e){this._options=t,this._graphics=e,this.graphics=[]}get name(){return this._options.name}hide(t){if(t){let e=null;e=t instanceof wt?t:this._graphics.getGraphic(t),this.graphics=this.graphics.filter((t=>t.graphic!==e))}else this.graphics.length=0}show(t,e){let i;return e=Object.assign({},e),t instanceof wt?i=this._graphics.copyGraphics?t.clone():t:(i=this._graphics.getGraphic(t),i||_.getInstance().error(`No such graphic added to component named ${t}. These named graphics are available: `,this._graphics.getNames())),i?(this.graphics.push({graphic:i,options:e}),i):null}use(t,e){return e=Object.assign({},e),this.hide(),this.show(t,e)}get order(){return this._options.order}set order(t){this._options.order=t}get offset(){var t;return null!==(t=this._options.offset)&&void 0!==t?t:A.Zero}set offset(t){this._options.offset=t}get currentKeys(){var t;return null!==(t=this.name)&&void 0!==t?t:"anonymous"}}class Ji{constructor(t){this._component=t,this._layers=[],this._layerMap={},this.default=new $i({name:"default",order:0},t),this._maybeAddLayer(this.default)}create(t){const e=new $i(t,this._component);return this._maybeAddLayer(e)}get(t){return t?this._getLayer(t):this._layers}currentKeys(){const t=[];for(const e of this._layers)t.push(e.currentKeys);return t}has(t){return t in this._layerMap}_maybeAddLayer(t){return this._layerMap[t.name]?this._layerMap[t.name]:(this._layerMap[t.name]=t,this._layers.push(t),this._layers.sort(((t,e)=>t.order-e.order)),t)}_getLayer(t){return this._layerMap[t]}}class ts extends _i{constructor(t){super(),this.type="ex.graphics",this._graphics={},this.visible=!0,this.opacity=1,this.offset=A.Zero,this.anchor=A.Half,this.copyGraphics=!1,this._bounds=null,t=Object.assign({visible:this.visible},t);const{current:e,anchor:i,opacity:s,visible:n,graphics:r,offset:o,copyGraphics:a,onPreDraw:h,onPostDraw:l}=t;this._graphics=r||{},this.offset=null!=o?o:this.offset,this.opacity=null!=s?s:this.opacity,this.anchor=null!=i?i:this.anchor,this.copyGraphics=null!=a?a:this.copyGraphics,this.onPreDraw=null!=h?h:this.onPreDraw,this.onPostDraw=null!=l?l:this.onPostDraw,this.visible=!!n,this.layers=new Ji(this),e&&this._graphics[e]&&this.show(this._graphics[e])}getGraphic(t){return this._graphics[t]}getNames(){return Object.keys(this._graphics)}get current(){return this.layers.default.graphics}get graphics(){return this._graphics}add(t,e){let i="default",s=null;return"string"==typeof t?(i=t,s=e):s=t,this._graphics[i]=this.copyGraphics?s.clone():s,"default"===i&&this.show("default"),s}show(t,e){return this.layers.default.show(t,e)}use(t,e){return this.layers.default.use(t,e)}hide(t){this.layers.default.hide(t)}set localBounds(t){this._bounds=t}get localBounds(){if(this._bounds)return this._bounds;let t=new B;for(const e of this.layers.get())for(const{graphic:i,options:s}of e.graphics){let n=this.anchor,r=this.offset;(null==s?void 0:s.anchor)&&(n=s.anchor),(null==s?void 0:s.offset)&&(r=s.offset);const o=i.localBounds,a=-o.width*i.scale.x*n.x+r.x,h=-o.height*i.scale.y*n.y+r.y;t=null==i?void 0:i.localBounds.translate(S(a+e.offset.x,h+e.offset.y)).combine(t)}return t}update(t,e=0){for(const i of this.layers.get())for(const{graphic:s}of i.graphics)Qi(s)&&(null==s||s.tick(t,e))}}class es extends bt{constructor(t){super(t),this.width=t.width,this.height=t.height,this.rasterize()}clone(){return new es(Object.assign(Object.assign({width:this.width,height:this.height},this.cloneGraphicOptions()),this.cloneRasterOptions()))}execute(t){this.color&&t.fillRect(0,0,this.width,this.height),this.strokeColor&&t.strokeRect(0,0,this.width,this.height)}}class is extends bt{constructor(t){var e;super(t),this._radius=0,this.padding=null!==(e=t.padding)&&void 0!==e?e:2,this.radius=t.radius,this.rasterize()}get radius(){return this._radius}set radius(t){this._radius=t,this.width=2*this._radius,this.height=2*this._radius,this.flagDirty()}clone(){return new is(Object.assign(Object.assign({radius:this.radius},this.cloneGraphicOptions()),this.cloneRasterOptions()))}execute(t){this.radius>0&&(t.beginPath(),t.arc(this.radius,this.radius,this.radius,0,2*Math.PI),this.color&&t.fill(),this.strokeColor&&t.stroke())}}class ss extends _i{constructor(){super(...arguments),this.type="ex.pointer",this.useColliderShape=!0,this.useGraphicsBounds=!1}}var ns,rs=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class os{static CreateReversibleEasingFunction(t){return(e,i,s,n)=>s<i?i-(t(e,s,i,n)-s):t(e,i,s,n)}static CreateReversableEasingFunction(t){return os.CreateReversibleEasingFunction(t)}static CreateVectorEasingFunction(t){return(e,i,s,n)=>new A(t(e,i.x,s.x,n),t(e,i.y,s.y,n))}}os.Linear=os.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*t/s+e)),os.EaseInQuad=os.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*(t/=s)*t+e)),os.EaseOutQuad=os.CreateReversibleEasingFunction(((t,e,i,s)=>-(i-=e)*(t/=s)*(t-2)+e)),os.EaseInOutQuad=os.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e,(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e))),os.EaseInCubic=os.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*(t/=s)*t*t+e)),os.EaseOutCubic=os.CreateReversibleEasingFunction(((t,e,i,s)=>(t/=s,(i-=e)*(--t*t*t+1)+e))),os.EaseInOutCubic=os.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e,(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e))),rs([b({message:"Alias for incorrect spelling used in older versions, will be removed in v0.25.0",alternateMethod:"CreateReversibleEasingFunction"})],os,"CreateReversableEasingFunction",null);class as{constructor(t){this._actions=[],this._completedActions=[],this._entity=t}add(t){this._actions.push(t)}remove(t){const e=this._actions.indexOf(t);this._actions.splice(e,1)}clearActions(){this._actions.length=0,this._completedActions.length=0,this._currentAction&&this._currentAction.stop()}getActions(){return this._actions.concat(this._completedActions)}hasNext(){return this._actions.length>0}isComplete(){return 0===this._actions.length}reset(){this._actions=this.getActions();const t=this._actions.length;for(let e=0;e<t;e++)this._actions[e].reset();this._completedActions=[]}update(t){this._actions.length>0&&(this._currentAction=this._actions[0],this._currentAction.update(t),this._currentAction.isComplete(this._entity)&&this._completedActions.push(this._actions.shift()))}}class hs{constructor(t,e,i){this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new As(t),this._actionQueue=this._repeatContext.getQueue(),this._repeat=i,this._originalRepeat=i,this._repeatBuilder(this._repeatContext),this._repeat--}update(t){this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext),this._repeat--),this._actionQueue.update(t)}isComplete(){return this._stopped||this._repeat<=0&&this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._repeat=this._originalRepeat}}class ls{constructor(t,e){this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new As(t),this._actionQueue=this._repeatContext.getQueue(),this._repeatBuilder(this._repeatContext)}update(t){this._stopped||(this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext)),this._actionQueue.update(t))}isComplete(){return this._stopped}stop(){this._stopped=!0,this._actionQueue.clearActions()}reset(){}}class cs{constructor(t,e,i,s){if(this._started=!1,this._stopped=!1,this._entity=t,this._tx=t.get(yi),this._motion=t.get(wi),this._speed=s,this._offset=new A(e,i),s<=0)throw _.getInstance().error("Attempted to moveBy with speed less than or equal to zero : "+s),new Error("Speed must be greater than 0 pixels per second")}update(t){this._started||(this._started=!0,this._start=new A(this._tx.pos.x,this._tx.pos.y),this._end=this._start.add(this._offset),this._distance=this._offset.size,this._dir=this._end.sub(this._start).normalize()),this.isComplete(this._entity)?(this._tx.pos=S(this._end.x,this._end.y),this._motion.vel=S(0,0)):this._motion.vel=this._dir.scale(this._speed)}isComplete(t){const e=t.get(yi);return this._stopped||e.pos.distance(this._start)>=this._distance}stop(){this._motion.vel=S(0,0),this._stopped=!0}reset(){this._started=!1}}class ds{constructor(t,e,i,s){this.entity=t,this._started=!1,this._stopped=!1,this._tx=t.get(yi),this._motion=t.get(wi),this._end=new A(e,i),this._speed=s}update(t){this._started||(this._started=!0,this._start=new A(this._tx.pos.x,this._tx.pos.y),this._distance=this._start.distance(this._end),this._dir=this._end.sub(this._start).normalize());const e=this._dir.scale(this._speed);this._motion.vel=S(e.x,e.y),this.isComplete(this.entity)&&(this._tx.pos=S(this._end.x,this._end.y),this._motion.vel=S(0,0))}isComplete(t){const e=t.get(yi);return this._stopped||new A(e.pos.x,e.pos.y).distance(this._start)>=this._distance}stop(){this._motion.vel=S(0,0),this._stopped=!0}reset(){this._started=!1}}!function(t){t[t.ShortestPath=0]="ShortestPath",t[t.LongestPath=1]="LongestPath",t[t.Clockwise=2]="Clockwise",t[t.CounterClockwise=3]="CounterClockwise"}(ns||(ns={}));class us{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(yi),this._motion=t.get(wi),this._end=e,this._speed=i,this._rotationType=s||ns.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation;const t=Math.abs(this._end-this._start),e=F-t;switch(t>e?(this._shortDistance=e,this._longDistance=t):(this._shortDistance=t,this._longDistance=e),this._shortestPathIsPositive=(this._start-this._end+F)%F>=Math.PI,this._rotationType){case ns.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case ns.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case ns.Clockwise:this._direction=1,this._shortestPathIsPositive?this._distance=this._shortDistance:this._distance=this._longDistance;break;case ns.CounterClockwise:this._direction=-1,this._shortestPathIsPositive?this._distance=this._longDistance:this._distance=this._shortDistance}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1}}class ps{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(yi),this._motion=t.get(wi),this._speed=i,this._offset=e,this._rotationType=s||ns.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation,this._end=this._start+this._offset;const t=Math.abs(this._end-this._start),e=F-t;switch(t>e?(this._shortDistance=e,this._longDistance=t):(this._shortDistance=t,this._longDistance=e),this._shortestPathIsPositive=(this._start-this._end+F)%F>=Math.PI,this._rotationType){case ns.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case ns.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case ns.Clockwise:this._direction=1,this._shortDistance>=0?this._distance=this._shortDistance:this._distance=this._longDistance;break;case ns.CounterClockwise:this._direction=-1,this._shortDistance<=0?this._distance=this._shortDistance:this._distance=this._longDistance}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1}}class gs{constructor(t,e,i,s,n){this._started=!1,this._stopped=!1,this._tx=t.get(yi),this._motion=t.get(wi),this._endX=e,this._endY=i,this._speedX=s,this._speedY=n}update(t){if(this._started||(this._started=!0,this._startX=this._tx.scale.x,this._startY=this._tx.scale.y,this._distanceX=Math.abs(this._endX-this._startX),this._distanceY=Math.abs(this._endY-this._startY)),Math.abs(this._tx.scale.x-this._startX)>=this._distanceX)this._motion.scaleFactor.x=0;else{const t=this._endY<this._startY?-1:1;this._motion.scaleFactor.x=this._speedX*t}if(Math.abs(this._tx.scale.y-this._startY)>=this._distanceY)this._motion.scaleFactor.y=0;else{const t=this._endY<this._startY?-1:1;this._motion.scaleFactor.y=this._speedY*t}this.isComplete()&&(this._tx.scale=S(this._endX,this._endY),this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.y-this._startX)>=this._distanceX&&Math.abs(this._tx.scale.y-this._startY)>=this._distanceY}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1}}class _s{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(yi),this._motion=t.get(wi),this._offset=new A(e,i),this._speedX=this._speedY=s}update(t){this._started||(this._started=!0,this._startScale=this._tx.scale.clone(),this._endScale=this._startScale.add(this._offset),this._distanceX=Math.abs(this._endScale.x-this._startScale.x),this._distanceY=Math.abs(this._endScale.y-this._startScale.y),this._directionX=this._endScale.x<this._startScale.x?-1:1,this._directionY=this._endScale.y<this._startScale.y?-1:1),this._motion.scaleFactor.x=this._speedX*this._directionX,this._motion.scaleFactor.y=this._speedY*this._directionY,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startScale.x)>=this._distanceX&&Math.abs(this._tx.scale.y-this._startScale.y)>=this._distanceY}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1}}class fs{constructor(t){this._method=null,this._hasBeenCalled=!1,this._method=t}update(t){this._method(),this._hasBeenCalled=!0}isComplete(){return this._hasBeenCalled}reset(){this._hasBeenCalled=!1}stop(){this._hasBeenCalled=!0}}class ms{constructor(t,e,i,s,n){this.easingFcn=n,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=new A(0,0),this._lerpEnd=new A(0,0),this._initialized=!1,this._stopped=!1,this._distance=0,this._tx=t.get(yi),this._motion=t.get(wi),this._lerpDuration=s,this._lerpEnd=new A(e,i)}_initialize(){this._lerpStart=new A(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0,this._distance=this._lerpStart.distance(this._lerpEnd)}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;this._currentLerpTime<this._lerpDuration?(e=this._lerpEnd.x<this._lerpStart.x?this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),i=this._lerpEnd.y<this._lerpStart.y?this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration),this._motion.vel=S((e-this._tx.pos.x)/(t/1e3),(i-this._tx.pos.y)/(t/1e3))):(this._tx.pos=S(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=A.Zero)}isComplete(t){return this._stopped||new A(t.pos.x,t.pos.y).distance(this._lerpStart)>=this._distance}reset(){this._initialized=!1}stop(){this._motion.vel=S(0,0),this._stopped=!0}}class ys{constructor(t,e,i,s=1){this._timeVisible=0,this._timeNotVisible=0,this._elapsedTime=0,this._totalTime=0,this._stopped=!1,this._started=!1,this._graphics=t.get(ts),this._timeVisible=e,this._timeNotVisible=i,this._duration=(e+i)*s}update(t){this._started||(this._started=!0),this._graphics&&(this._elapsedTime+=t,this._totalTime+=t,this._graphics.visible&&this._elapsedTime>=this._timeVisible&&(this._graphics.visible=!1,this._elapsedTime=0),!this._graphics.visible&&this._elapsedTime>=this._timeNotVisible&&(this._graphics.visible=!0,this._elapsedTime=0),this.isComplete()&&(this._graphics.visible=!0))}isComplete(){return this._stopped||this._totalTime>=this._duration}stop(){this._graphics&&(this._graphics.visible=!0),this._stopped=!0}reset(){this._started=!1,this._elapsedTime=0,this._totalTime=0}}class ws{constructor(t,e,i){this._multiplier=1,this._started=!1,this._stopped=!1,this._graphics=t.get(ts),this._endOpacity=e,this._speed=i}update(t){this._graphics&&(this._started||(this._started=!0,this._endOpacity<this._graphics.opacity?this._multiplier=-1:this._multiplier=1),this._speed>0&&(this._graphics.opacity+=this._multiplier*(Math.abs(this._graphics.opacity-this._endOpacity)*t)/this._speed),this._speed-=t,this.isComplete()&&(this._graphics.opacity=this._endOpacity),_.getInstance().debug("[Action fade] Actor opacity:",this._graphics.opacity))}isComplete(){return this._stopped||Math.abs(this._graphics.opacity-this._endOpacity)<.05}stop(){this._stopped=!0}reset(){this._started=!1}}class vs{constructor(t){this._elapsedTime=0,this._started=!1,this._stopped=!1,this._delay=t}update(t){this._started||(this._started=!0),this._elapsedTime+=t}isComplete(){return this._stopped||this._elapsedTime>=this._delay}stop(){this._stopped=!0}reset(){this._elapsedTime=0,this._started=!1}}class xs{constructor(t){this._stopped=!1,this._entity=t}update(t){this._entity.get(Ss).clearActions(),this._entity.kill(),this._stopped=!0}isComplete(){return this._stopped}stop(){}reset(){}}class bs{constructor(t,e,i){this._started=!1,this._stopped=!1,this._tx=t.get(yi),this._motion=t.get(wi),this._followTx=e.get(yi),this._followMotion=e.get(wi),this._current=new A(this._tx.pos.x,this._tx.pos.y),this._end=new A(this._followTx.pos.x,this._followTx.pos.y),this._maximumDistance=void 0!==i?i:this._current.distance(this._end),this._speed=0}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._followMotion.vel.x,2)+Math.pow(this._followMotion.vel.y,2));if(0!==e&&(this._speed=e),this._current=S(this._tx.pos.x,this._tx.pos.y),this._end=S(this._followTx.pos.x,this._followTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize(),this._distanceBetween>=this._maximumDistance){const t=this._dir.scale(this._speed);this._motion.vel=S(t.x,t.y)}else this._motion.vel=S(0,0);this.isComplete()&&(this._tx.pos=S(this._end.x,this._end.y),this._motion.vel=S(0,0))}stop(){this._motion.vel=S(0,0),this._stopped=!0}isComplete(){return this._stopped}reset(){this._started=!1}}class Cs{constructor(t,e,i){this._started=!1,this._stopped=!1,this._speedWasSpecified=!1,this._tx=t.get(yi),this._motion=t.get(wi),this._meetTx=e.get(yi),this._meetMotion=e.get(wi),this._current=new A(this._tx.pos.x,this._tx.pos.y),this._end=new A(this._meetTx.pos.x,this._meetTx.pos.y),this._speed=i||0,void 0!==i&&(this._speedWasSpecified=!0)}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._meetMotion.vel.x,2)+Math.pow(this._meetMotion.vel.y,2));0===e||this._speedWasSpecified||(this._speed=e),this._current=S(this._tx.pos.x,this._tx.pos.y),this._end=S(this._meetTx.pos.x,this._meetTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize();const i=this._dir.scale(this._speed);this._motion.vel=S(i.x,i.y),this.isComplete()&&(this._tx.pos=S(this._end.x,this._end.y),this._motion.vel=S(0,0))}isComplete(){return this._stopped||this._distanceBetween<=1}stop(){this._motion.vel=S(0,0),this._stopped=!0}reset(){this._started=!1}}class As{constructor(t){this._entity=t,this._queue=new as(t)}getQueue(){return this._queue}update(t){this._queue.update(t)}clearActions(){this._queue.clearActions()}easeTo(...t){var e,i;let s=0,n=0,r=0,o=os.Linear;return t[0]instanceof A?(s=t[0].x,n=t[0].y,r=t[1],o=null!==(e=t[2])&&void 0!==e?e:o):(s=t[0],n=t[1],r=t[2],o=null!==(i=t[3])&&void 0!==i?i:o),this._queue.add(new ms(this._entity,s,n,r,o)),this}moveTo(t,e,i){let s=0,n=0,r=0;return t instanceof A?(s=t.x,n=t.y,r=e):(s=t,n=e,r=i),this._queue.add(new ds(this._entity,s,n,r)),this}moveBy(t,e,i){let s=0,n=0,r=0;return t instanceof A?(s=t.x,n=t.y,r=e):(s=t,n=e,r=i),this._queue.add(new cs(this._entity,s,n,r)),this}rotateTo(t,e,i){return this._queue.add(new us(this._entity,t,e,i)),this}rotateBy(t,e,i){return this._queue.add(new ps(this._entity,t,e,i)),this}scaleTo(t,e,i,s){let n=1,r=1,o=0,a=0;return t instanceof A&&e instanceof A&&(n=t.x,r=t.y,o=e.x,a=e.y),"number"==typeof t&&"number"==typeof e&&(n=t,r=e,o=i,a=s),this._queue.add(new gs(this._entity,n,r,o,a)),this}scaleBy(t,e,i){let s=1,n=1;return t instanceof A&&(s=t.x,n=t.y,i=e),"number"==typeof t&&"number"==typeof e&&(s=t,n=e),this._queue.add(new _s(this._entity,s,n,i)),this}blink(t,e,i=1){return this._queue.add(new ys(this._entity,t,e,i)),this}fade(t,e){return this._queue.add(new ws(this._entity,t,e)),this}delay(t){return this._queue.add(new vs(t)),this}die(){return this._queue.add(new xs(this._entity)),this}callMethod(t){return this._queue.add(new fs(t)),this}repeat(t,e){return e?(this._queue.add(new hs(this._entity,t,e)),this):(this.repeatForever(t),this)}repeatForever(t){return this._queue.add(new ls(this._entity,t)),this}follow(t,e){return void 0===e?this._queue.add(new bs(this._entity,t)):this._queue.add(new bs(this._entity,t,e)),this}meet(t,e){return void 0===e?this._queue.add(new Cs(this._entity,t)):this._queue.add(new Cs(this._entity,t,e)),this}asPromise(){return this.toPromise()}toPromise(){return new Promise((t=>{this._queue.add(new fs((()=>{t()})))}))}}class Ss extends _i{constructor(){super(...arguments),this.type="ex.actions",this.dependencies=[yi,wi]}onAdd(t){this._ctx=new As(t)}onRemove(){this._ctx=null}getQueue(){var t;return null===(t=this._ctx)||void 0===t?void 0:t.getQueue()}update(t){var e;return null===(e=this._ctx)||void 0===e?void 0:e.update(t)}clearActions(){var t;null===(t=this._ctx)||void 0===t||t.clearActions()}easeTo(...t){return this._ctx.easeTo.apply(this._ctx,t)}moveTo(t,e,i){return this._ctx.moveTo.apply(this._ctx,[t,e,i])}moveBy(t,e,i){return this._ctx.moveBy.apply(this._ctx,[t,e,i])}rotateTo(t,e,i){return this._ctx.rotateTo(t,e,i)}rotateBy(t,e,i){return this._ctx.rotateBy(t,e,i)}scaleTo(t,e,i,s){return this._ctx.scaleTo.apply(this._ctx,[t,e,i,s])}scaleBy(t,e,i){return this._ctx.scaleBy.apply(this._ctx,[t,e,i])}blink(t,e,i){return this._ctx.blink(t,e,i)}fade(t,e){return this._ctx.fade(t,e)}delay(t){return this._ctx.delay(t)}die(){return this._ctx.die()}callMethod(t){return this._ctx.callMethod(t)}repeat(t,e){return this._ctx.repeat(t,e)}repeatForever(t){return this._ctx.repeatForever(t)}follow(t,e){return this._ctx.follow(t,e)}meet(t,e){return this._ctx.meet(t,e)}asPromise(){return this.toPromise()}toPromise(){return this._ctx.toPromise()}}var Ps=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Es extends Zi{constructor(t){super(),this._anchor=vt(A.Half,(t=>this._handleAnchorChange(t))),this.logger=_.getInstance(),this.scene=null,this.frames={},this.currentDrawing=null,this._draggable=!1,this._dragging=!1,this._pointerDragStartHandler=()=>{this._dragging=!0},this._pointerDragEndHandler=()=>{this._dragging=!1},this._pointerDragMoveHandler=t=>{this._dragging&&(this.pos=t.worldPos)},this._pointerDragLeaveHandler=t=>{this._dragging&&(this.pos=t.worldPos)},this.traits=[];const{name:e,x:i,y:s,pos:n,scale:r,width:o,height:a,radius:h,collider:l,vel:d,acc:u,rotation:g,angularVelocity:f,z:m,color:y,visible:w,anchor:v,collisionType:x,collisionGroup:b}=Object.assign({},t);this._setName(e),this.anchor=null!=v?v:Es.defaults.anchor.clone(),this.addComponent(new yi),this.pos=null!=n?n:S(null!=i?i:0,null!=s?s:0),this.rotation=null!=g?g:0,this.scale=null!=r?r:S(1,1),this.z=null!=m?m:0,this.addComponent(new ss),this.addComponent(new ts({anchor:this.anchor})),this.addComponent(new Yi(((t,e)=>this.draw(t,e)))),this.addComponent(new wi),this.vel=null!=d?d:A.Zero,this.acc=null!=u?u:A.Zero,this.angularVelocity=null!=f?f:0,this.addComponent(new Ss),this.addComponent(new Wi),this.body.collisionType=null!=x?x:hi.Passive,b&&(this.body.group=b),l?this.addComponent(new Hi(l)):h?this.addComponent(new Hi(Ui.Circle(h,this.anchor))):o>0&&a>0?this.addComponent(new Hi(Ui.Box(o,a,this.anchor))):this.addComponent(new Hi),this.graphics.visible=null==w||w,y&&(this.color=y,o&&a?this.graphics.add(new es({color:y,width:o,height:a})):h&&this.graphics.add(new is({color:y,radius:h}))),p.isEnabled(c.LegacyDrawing)&&this.traits.push(new Gi)}get body(){return this.get(Wi)}get transform(){return this.get(yi)}get motion(){return this.get(wi)}get graphics(){return this.get(ts)}get collider(){return this.get(Hi)}get pointer(){return this.get(ss)}get actions(){return this.get(Ss)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t.clone()}get oldPos(){return this.body.oldPos}set oldPos(t){this.body.oldPos.setTo(t.x,t.y)}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t.clone()}get oldVel(){return this.body.oldVel}set oldVel(t){this.body.oldVel.setTo(t.x,t.y)}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t.clone()}set oldAcc(t){this.body.oldAcc.setTo(t.x,t.y)}get oldAcc(){return this.body.oldAcc}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}get scale(){return this.get(yi).scale}set scale(t){this.get(yi).scale=t}get anchor(){return this._anchor}set anchor(t){this._anchor=vt(t,(t=>this._handleAnchorChange(t))),this._handleAnchorChange(t)}_handleAnchorChange(t){this.graphics&&(this.graphics.anchor=t)}get isOffScreen(){return this.hasTag("offscreen")}get visible(){return this.graphics.visible}set visible(t){this.graphics.visible=t}get opacity(){return this.graphics.opacity}set opacity(t){this.graphics.opacity=t}get draggable(){return this._draggable}set draggable(t){t&&(t&&!this._draggable?(this.on("pointerdragstart",this._pointerDragStartHandler),this.on("pointerdragend",this._pointerDragEndHandler),this.on("pointerdragmove",this._pointerDragMoveHandler),this.on("pointerdragleave",this._pointerDragLeaveHandler)):!t&&this._draggable&&(this.off("pointerdragstart",this._pointerDragStartHandler),this.off("pointerdragend",this._pointerDragEndHandler),this.off("pointerdragmove",this._pointerDragMoveHandler),this.off("pointerdragleave",this._pointerDragLeaveHandler)),this._draggable=t)}get color(){return this._color}set color(t){this._color=t.clone()}onInitialize(t){}_initialize(t){super._initialize(t);for(const e of this.children)e._initialize(t)}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}_prekill(t){super.emit("prekill",new Et(this)),this.onPreKill(t)}onPreKill(t){}_postkill(t){super.emit("postkill",new Tt(this)),this.onPostKill(t)}onPostKill(t){}kill(){this.scene?(this._prekill(this.scene),this.emit("kill",new Pt(this)),super.kill(),this._postkill(this.scene)):this.logger.warn("Cannot kill actor, it was never added to the Scene")}unkill(){this.active=!0}isKilled(){return!this.active}setDrawing(t){t=t.toString(),this.currentDrawing!==this.frames[t]&&(null!=this.frames[t]?(this.frames[t].reset(),this.currentDrawing=this.frames[t]):_.getInstance().error(`the specified drawing key ${t} does not exist`)),this.currentDrawing&&this.currentDrawing instanceof Me&&this.currentDrawing.tick(0)}addDrawing(){2===arguments.length?(this.frames[arguments[0]]=arguments[1],this.currentDrawing||(this.currentDrawing=arguments[1])):(arguments[0]instanceof Pe&&this.addDrawing("default",arguments[0]),arguments[0]instanceof xe&&this.addDrawing("default",arguments[0].asSprite()))}get z(){return this.get(yi).z}getZIndex(){return this.get(yi).z}set z(t){this.get(yi).z=t}setZIndex(t){this.get(yi).z=t}get center(){return new A(this.pos.x+this.width/2-this.anchor.x*this.width,this.pos.y+this.height/2-this.anchor.y*this.height)}get width(){return this.collider.localBounds.width*this.getGlobalScale().x}get height(){return this.collider.localBounds.height*this.getGlobalScale().y}getGlobalRotation(){return this.get(yi).globalRotation}getGlobalPos(){return this.get(yi).globalPos}getGlobalScale(){return this.get(yi).globalScale}contains(t,e,i=!1){const s=S(t,e),n=this.get(Hi);n.update();const r=n.get();if(!r)return!1;const o=r.contains(s);return i?o||this.children.some((i=>i.contains(t,e,!0))):o}within(t,e){const i=this.get(Hi),s=t.get(Hi),n=i.get(),r=s.get();return!(!n||!r)&&n.getClosestLineBetween(r).getLength()<=e}update(t,e){this._initialize(t),this._preupdate(t,e);const i=this.currentDrawing;i&&i instanceof Me&&i.tick(e,t.stats.currFrame.id);for(const i of this.traits)i.update(this,t,e);this._postupdate(t,e)}onPreUpdate(t,e){}onPostUpdate(t,e){}_preupdate(t,e){this.emit("preupdate",new It(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new It(t,e,this)),this.onPostUpdate(t,e)}draw(t,e){var i;if(t.save(),this.currentDrawing){t.translate(-this.width*this.anchor.x,-this.height*this.anchor.y),this._predraw(t,e);const i=this.currentDrawing,s=(this.width-i.width*i.scale.x)*this.anchor.x,n=(this.height-i.height*i.scale.y)*this.anchor.y;this.currentDrawing.draw({ctx:t,x:s,y:n,opacity:this.graphics.opacity})}else if(this._predraw(t,e),this.color&&this.collider){const e=this.get(Hi);e.update(),e&&!e.bounds.hasZeroDimensions()&&(t.globalAlpha=this.graphics.opacity,null===(i=e.get())||void 0===i||i.draw(t,this.color,S(0,0)))}t.restore(),this._postdraw(t,e)}onPreDraw(t,e){}onPostDraw(t,e){}_predraw(t,e){this.emit("predraw",new Dt(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new Dt(t,e,this)),this.onPostDraw(t,e)}debugDraw(t){}}Es.defaults={anchor:A.Half},Ps([b({message:"Actor.visible will be removed in v0.26.0",alternateMethod:"Use Actor.graphics.visible"})],Es.prototype,"visible",null),Ps([b({message:"Actor.opacity will be removed in v0.26.0",alternateMethod:"Use Actor.graphics.opacity"})],Es.prototype,"opacity",null),Ps([b({message:"Actor.setDrawing will be removed in v0.26.0",alternateMethod:"Use Actor.graphics.show() or Actor.graphics.use()"})],Es.prototype,"setDrawing",null),Ps([b({message:"Actor.addDrawing will be removed in v0.26.0",alternateMethod:"Use Actor.graphics.add()"})],Es.prototype,"addDrawing",null),Ps([b({message:"Actor.getZIndex will be removed in v0.26.0",alternateMethod:"Use Actor.transform.z or Actor.z"})],Es.prototype,"getZIndex",null),Ps([b({message:"Actor.setZIndex will be removed in v0.26.0",alternateMethod:"Use Actor.transform.z or Actor.z"})],Es.prototype,"setZIndex",null);class Ts extends Es{constructor(t){super(Object.assign({},t)),this.get(yi).coordPlane=mi.Screen,this.anchor=S(0,0),this.body.collisionType=hi.PreventCollision,this.collider.useBoxCollider(this.width,this.height,this.anchor)}_initialize(t){this._engine=t,super._initialize(t)}contains(t,e,i=!0){if(i)return super.contains(t,e);const s=this._engine.worldToScreenCoordinates(new A(t,e));return super.contains(s.x,s.y)}}var Rs=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Bs{constructor(t,e,i,s){if(this._logger=_.getInstance(),this.id=0,this._elapsedTime=0,this._totalTimeAlive=0,this._running=!1,this._numberOfTicks=0,this.interval=10,this.repeats=!1,this.maxNumberOfRepeats=-1,this._complete=!1,this.scene=null,"function"!=typeof t){const n=t;t=n.fcn,e=n.interval,i=n.repeats,s=n.numberOfRepeats}if(s&&s>=0&&(this.maxNumberOfRepeats=s,!i))throw new Error("repeats must be set to true if numberOfRepeats is set");this.id=Bs._MAX_ID++,this.interval=e||this.interval,this.repeats=i||this.repeats,this._callbacks=[],t&&this.on(t)}get complete(){return this._complete}on(t){this._callbacks.push(t)}off(t){const e=this._callbacks.indexOf(t);this._callbacks.splice(e,1)}update(t){this._running&&(this._totalTimeAlive+=t,this._elapsedTime+=t,this.maxNumberOfRepeats>-1&&this._numberOfTicks>=this.maxNumberOfRepeats&&(this._complete=!0,this._running=!1,this._elapsedTime=0),!this.complete&&this._elapsedTime>=this.interval&&(this._callbacks.forEach((t=>{t.call(this)})),this._numberOfTicks++,this.repeats||(this._complete=!0,this._running=!1),this._elapsedTime=0))}reset(t,e){if(t&&t>=0&&(this.interval=t),this.maxNumberOfRepeats&&this.maxNumberOfRepeats>=0&&(this.maxNumberOfRepeats=e,!this.repeats))throw new Error("repeats must be set to true if numberOfRepeats is set");this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0}get timesRepeated(){return this._numberOfTicks}getTimeRunning(){return this._totalTimeAlive}get timeToNextAction(){return this.complete?0:this.interval-this._elapsedTime}get timeElapsedTowardNextAction(){return this._elapsedTime}get isRunning(){return this._running}pause(){return this._running=!1,this}unpause(){this._running=!0}resume(){return this._running=!0,this}start(){return this.scene||this._logger.warn("Cannot start a timer not part of a scene, timer wont start until added"),this._running=!0,this.complete&&(this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0),this}stop(){return this._running=!1,this._elapsedTime=0,this._numberOfTicks=0,this}cancel(){this.pause(),this.scene&&this.scene.cancelTimer(this)}}Bs._MAX_ID=0,Rs([b({message:"Will be removed in v0.26.0",alternateMethod:"Use Timer.resume()"})],Bs.prototype,"unpause",null);var Ds,Ms=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Fs extends Zi{constructor(t,e,i,s,n,r){if(super(),this._token=0,this._onScreenXStart=0,this._onScreenXEnd=9999,this._onScreenYStart=0,this._onScreenYEnd=9999,this._spriteSheets={},this._legacySpriteMap=new Map,this.logger=_.getInstance(),this.data=[],this._rows=[],this._cols=[],this.visible=!0,this.isOffscreen=!1,this._dirty=!0,t&&"object"==typeof t){const o=t;t=o.x,e=o.y,i=o.cellWidth,s=o.cellHeight,n=o.rows,r=o.cols}this.addComponent(new yi),this.addComponent(new wi),this.addComponent(new Wi({type:hi.Fixed})),this.addComponent(new Yi(((t,e)=>this.draw(t,e)))),this.addComponent(new ts({onPostDraw:(t,e)=>this.draw(t,e)})),this.addComponent(new Hi),this._transform=this.get(yi),this._motion=this.get(wi),this._collider=this.get(Hi),this._composite=this._collider.useCompositeCollider([]),this.x=t,this.y=e,this.cellWidth=i,this.cellHeight=s,this.rows=n,this.cols=r,this.data=new Array(n*r),this._rows=new Array(n),this._cols=new Array(r);let o=[];for(let a=0;a<r;a++){for(let h=0;h<n;h++){const n=new Ls(a*i+t,h*s+e,i,s,a+h*r);n.map=this,this.data[a+h*r]=n,o.push(n),this._rows[h]||(this._rows[h]=[]),this._rows[h].push(n)}this._cols[a]=o,o=[]}this.get(ts).localBounds=new B({left:0,top:0,right:this.cols*this.cellWidth,bottom:this.rows*this.cellHeight})}flagDirty(){this._dirty=!0}get x(){var t;return null!==(t=this._transform.pos.x)&&void 0!==t?t:0}set x(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.pos)&&(this.get(yi).pos=S(t,this.y))}get y(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos.y)&&void 0!==e?e:0}set y(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.pos)&&(this._transform.pos=S(this.x,t))}get z(){var t;return null!==(t=this._transform.z)&&void 0!==t?t:0}set z(t){this._transform&&(this._transform.z=t)}get rotation(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.rotation)&&void 0!==e?e:0}set rotation(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.rotation)&&(this._transform.rotation=t)}get scale(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.scale)&&void 0!==e?e:A.One}set scale(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.scale)&&(this._transform.scale=t)}get pos(){return this._transform.pos}set pos(t){this._transform.pos=t}get vel(){return this._motion.vel}set vel(t){this._motion.vel=t}on(t,e){super.on(t,e)}_initialize(t){super._initialize(t)}registerSpriteSheet(t,e){this._spriteSheets[t]=e instanceof Ne?e:Ne.fromLegacySpriteSheet(e)}_updateColliders(){this._composite.clearColliders();const t=[];let e;for(let i=0;i<this.cols;i++){for(let s=0;s<this.rows;s++){0===s&&(e=null);const n=this.data[i+s*this.cols];n.solid?e=e?e.combine(n.bounds):n.bounds:(e&&t.push(e),e=null)}if(e){const i=t[t.length-1];i&&i.top===e.top&&i.bottom===e.bottom?t[t.length-1]=i.combine(e):t.push(e)}}this._composite=this._collider.useCompositeCollider([]);for(const e of t){const t=Ui.Box(e.width,e.height,A.Zero,S(e.left-this.pos.x,e.top-this.pos.y));t.owner=this,this._composite.addCollider(t)}this._collider.update()}getCellByIndex(t){return this.data[t]}getCell(t,e){return t<0||e<0||t>=this.cols||e>=this.rows?null:this.data[t+e*this.cols]}getCellByPoint(t,e){t=Math.floor((t-this.pos.x)/this.cellWidth),e=Math.floor((e-this.pos.y)/this.cellHeight);const i=this.getCell(t,e);return t>=0&&e>=0&&t<this.cols&&e<this.rows&&i?i:null}getRows(){return this._rows}getColumns(){return this._cols}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this.onPreUpdate(t,e),this.emit("preupdate",new It(t,e,this)),this._dirty&&(this._dirty=!1,this._updateColliders()),this._token++;const i=t.getWorldBounds(),s=S(i.left,i.top),n=S(i.right,i.bottom);this._onScreenXStart=Math.max(Math.floor((s.x-this.x)/this.cellWidth)-2,0),this._onScreenYStart=Math.max(Math.floor((s.y-this.y)/this.cellHeight)-2,0),this._onScreenXEnd=Math.max(Math.floor((n.x-this.x)/this.cellWidth)+2,0),this._onScreenYEnd=Math.max(Math.floor((n.y-this.y)/this.cellHeight)+2,0),this._transform.pos=S(this.x,this.y),this.onPostUpdate(t,e),this.emit("postupdate",new Lt(t,e,this))}draw(t,e){this.emit("predraw",new Dt(t,e,this));let i=this._onScreenXStart;const s=Math.min(this._onScreenXEnd,this.cols);let n=this._onScreenYStart;const r=Math.min(this._onScreenYEnd,this.rows);let o,a,h;for(;i<s;i++){for(;n<r;n++)for(o=this.getCell(i,n).graphics,a=0,h=o.length;a<h;a++){const s=o[a];s&&(t instanceof CanvasRenderingContext2D?s instanceof Ee&&(this._legacySpriteMap.has(s)||this._legacySpriteMap.set(s,Ee.toLegacySprite(s)),this._legacySpriteMap.get(s).draw(t,i*this.cellWidth,n*this.cellHeight)):(Qi(s)&&(null==s||s.tick(e,this._token)),s.draw(t,i*this.cellWidth,n*this.cellHeight)))}n=this._onScreenYStart}this.emit("postdraw",new Mt(t,e,this))}}Ms([b({message:"No longer used, will be removed in v0.26.0"})],Fs.prototype,"registerSpriteSheet",null);class ks extends(be(Fs)){constructor(t,e,i,s,n,r){super(t,e,i,s,n,r)}}class Is extends Zi{constructor(t,e,i,s,n,r=!1,o=[]){if(super(),this._solid=!1,this.graphics=[],this.data=new Map,t&&"object"==typeof t){const a=t;t=a.x,e=a.y,i=a.width,s=a.height,n=a.index,r=a.solid,o=a.sprites}this.x=t,this.y=e,this.width=i,this.height=s,this.index=n,this.solid=r,this.graphics=o,this._bounds=new B(this.x,this.y,this.x+this.width,this.y+this.height)}get solid(){return this._solid}set solid(t){var e;null===(e=this.map)||void 0===e||e.flagDirty(),this._solid=t}get bounds(){return this._bounds}get center(){return new A(this.x+this.width/2,this.y+this.height/2)}pushSprite(t){this.addGraphic(t)}addGraphic(t){t instanceof Pe?this.graphics.push(Ee.fromLegacySprite(t)):this.graphics.push(t)}removeGraphic(t){G(t,this.graphics)}clearGraphics(){this.graphics.length=0}}Ms([b({message:"Will be removed in v0.26.0",alternateMethod:"addSprite"})],Is.prototype,"pushSprite",null);class Ls extends(be(Is)){constructor(t,e,i,s,n,r,o){super(t,e,i,s,n,r,o)}}class Os{constructor(t){this.camera=t}lockToActor(t){this.camera.addStrategy(new zs(t))}lockToActorAxis(t,e){this.camera.addStrategy(new Us(t,e))}elasticToActor(t,e,i){this.camera.addStrategy(new Hs(t,e,i))}radiusAroundActor(t,e){this.camera.addStrategy(new Ns(t,e))}limitCameraBounds(t){this.camera.addStrategy(new Ws(t))}}!function(t){t[t.X=0]="X",t[t.Y=1]="Y"}(Ds||(Ds={}));class zs{constructor(t){this.target=t,this.action=(t,e,i,s)=>t.center}}class Us{constructor(t,e){this.target=t,this.axis=e,this.action=(t,e,i,s)=>{const n=t.center,r=e.getFocus();return this.axis===Ds.X?new A(n.x,r.y):new A(r.x,n.y)}}}class Hs{constructor(t,e,i){this.target=t,this.cameraElasticity=e,this.cameraFriction=i,this.action=(t,e,i,s)=>{const n=t.center;let r=e.getFocus(),o=e.vel.clone();const a=n.sub(r).scale(this.cameraElasticity);o=o.add(a);const h=o.scale(-1).scale(this.cameraFriction);return o=o.add(h),r=r.add(o),r}}}class Ns{constructor(t,e){this.target=t,this.radius=e,this.action=(t,e,i,s)=>{const n=t.center,r=e.getFocus(),o=n.sub(r),a=o.size;if(a>=this.radius){const t=a-this.radius;return r.add(o.normalize().scale(t))}return r}}}class Ws{constructor(t){this.target=t,this.boundSizeChecked=!1,this.action=(t,e,i,s)=>{const n=e.getFocus();this.boundSizeChecked||((t.bottom-t.top<i.drawHeight||t.right-t.left<i.drawWidth)&&_.getInstance().warn("Camera bounds should not be smaller than the engine viewport"),this.boundSizeChecked=!0);let r=n.x,o=n.y;return n.x<t.left+i.halfDrawWidth?r=t.left+i.halfDrawWidth:n.x>t.right-i.halfDrawWidth&&(r=t.right-i.halfDrawWidth),n.y<t.top+i.halfDrawHeight?o=t.top+i.halfDrawHeight:n.y>t.bottom-i.halfDrawHeight&&(o=t.bottom-i.halfDrawHeight),S(r,o)}}}class Vs extends Qe{constructor(){super(...arguments),this._cameraStrategies=[],this.strategy=new Os(this),this._z=1,this.dz=0,this.az=0,this.rotation=0,this.rx=0,this._posChanged=!1,this._pos=xt(A.Zero,(()=>this._posChanged=!0)),this.vel=A.Zero,this.acc=A.Zero,this._cameraMoving=!1,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=null,this._lerpEnd=null,this._isShaking=!1,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._elapsedShakeTime=0,this._xShake=0,this._yShake=0,this._isZooming=!1,this._zoomStart=1,this._zoomEnd=1,this._currentZoomTime=0,this._zoomDuration=0,this._zoomEasing=os.EaseInOutCubic,this._easing=os.EaseInOutCubic,this._halfWidth=0,this._halfHeight=0,this._viewport=null,this._isInitialized=!1}get zoom(){return this._z}set zoom(t){this._z=t,this._engine&&(this._halfWidth=this._engine.halfDrawWidth,this._halfHeight=this._engine.halfDrawHeight)}get angularVelocity(){return this.rx}set angularVelocity(t){this.rx=t}get pos(){return this._pos}set pos(t){this._pos=xt(t,(()=>this._posChanged=!0)),this._posChanged=!0}get x(){return this.pos.x}set x(t){this._follow||this._cameraMoving||(this.pos=S(t,this.pos.y))}get y(){return this.pos.y}set y(t){this._follow||this._cameraMoving||(this.pos=S(this.pos.x,t))}get dx(){return this.vel.x}set dx(t){this.vel=S(t,this.vel.y)}get dy(){return this.vel.y}set dy(t){this.vel=S(this.vel.x,t)}get ax(){return this.acc.x}set ax(t){this.acc=S(t,this.acc.y)}get ay(){return this.acc.y}set ay(t){this.acc=S(this.acc.x,t)}getFocus(){return this.pos}move(t,e,i=os.EaseInOutCubic){if("function"!=typeof i)throw"Please specify an EasingFunction";return this._follow?Promise.reject(t):(this._lerpPromise&&this._lerpResolve&&this._lerpResolve(t),this._lerpPromise=new Promise((t=>{this._lerpResolve=t})),this._lerpStart=this.getFocus().clone(),this._lerpDuration=e,this._lerpEnd=t,this._currentLerpTime=0,this._cameraMoving=!0,this._easing=i,this._lerpPromise)}shake(t,e,i){this._isShaking=!0,this._shakeMagnitudeX=t,this._shakeMagnitudeY=e,this._shakeDuration=i}zoomOverTime(t,e=0,i=os.EaseInOutCubic){return this._zoomPromise=new Promise((t=>{this._zoomResolve=t})),e?(this._isZooming=!0,this._zoomEasing=i,this._currentZoomTime=0,this._zoomDuration=e,this._zoomStart=this.zoom,this._zoomEnd=t,this._zoomPromise):(this._isZooming=!1,this.zoom=t,Promise.resolve(!0))}get viewport(){return this._viewport?this._viewport:new B(0,0,0,0)}addStrategy(t){this._cameraStrategies.push(t)}removeStrategy(t){G(t,this._cameraStrategies)}clearAllStrategies(){this._cameraStrategies.length=0}_preupdate(t,e){this.emit("preupdate",new It(t,e,this)),this.onPreUpdate(t,e)}onPreUpdate(t,e){}_postupdate(t,e){this.emit("postupdate",new Lt(t,e,this)),this.onPostUpdate(t,e)}onPostUpdate(t,e){}get isInitialized(){return this._isInitialized}_initialize(t){if(!this.isInitialized){this._engine=t;const e=this._engine.screen.resolution;let i=S(e.width/2,e.height/2);if(!this._engine.loadingComplete){const t=this._engine.screen.peekResolution();t&&(i=S(t.width/2,t.height/2))}this._halfWidth=i.x,this._halfHeight=i.x,this._posChanged||(this.pos=i),this.onInitialize(t),super.emit("initialize",new ee(t,this)),this._isInitialized=!0}}onInitialize(t){}on(t,e){super.on(t,e)}off(t,e){super.off(t,e)}once(t,e){super.once(t,e)}update(t,e){if(this._initialize(t),this._preupdate(t,e),this.pos=this.pos.add(this.vel.scale(e/1e3)),this.zoom+=this.dz*e/1e3,this.vel=this.vel.add(this.acc.scale(e/1e3)),this.dz+=this.az*e/1e3,this.rotation+=this.angularVelocity*e/1e3,this._isZooming)if(this._currentZoomTime<this._zoomDuration){const t=(0,this._zoomEasing)(this._currentZoomTime,this._zoomStart,this._zoomEnd,this._zoomDuration);this.zoom=t,this._currentZoomTime+=e}else this._isZooming=!1,this.zoom=this._zoomEnd,this._currentZoomTime=0,this._zoomResolve(!0);if(this._cameraMoving)if(this._currentLerpTime<this._lerpDuration){const t=os.CreateVectorEasingFunction(this._easing)(this._currentLerpTime,this._lerpStart,this._lerpEnd,this._lerpDuration);this.pos=t,this._currentLerpTime+=e}else{this.pos=this._lerpEnd;const t=this._lerpEnd.clone();this._lerpStart=null,this._lerpEnd=null,this._currentLerpTime=0,this._cameraMoving=!1,this._lerpResolve(t)}this._isDoneShaking()?(this._isShaking=!1,this._elapsedShakeTime=0,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._xShake=0,this._yShake=0):(this._elapsedShakeTime+=e,this._xShake=1+(Math.random()*this._shakeMagnitudeX|0),this._yShake=1+(Math.random()*this._shakeMagnitudeY|0));for(const i of this._cameraStrategies)this.pos=i.action.call(i,i.target,this,t,e);this._viewport=new B(this.x-this._halfWidth,this.y-this._halfHeight,this.x+this._halfWidth,this.y+this._halfHeight),this._postupdate(t,e)}draw(t){let e=0,i=0;t instanceof CanvasRenderingContext2D?(e=t.canvas.width,i=t.canvas.height):(e=t.width,i=t.height);const s=this.getFocus(),n=this._engine?this._engine.pixelRatio:1,r=this.zoom,o=e/r/n,a=i/r/n;t.scale(r,r),t.translate(-s.x+o/2+this._xShake,-s.y+a/2+this._yShake)}debugDraw(t){}_isDoneShaking(){return!this._isShaking||this._elapsedShakeTime>=this._shakeDuration}}function Gs(t){return t instanceof Ts}const js={pos:A.Zero,width:10,height:10,visible:!1,action:()=>{},filter:()=>!0,repeat:-1};class Xs extends Es{constructor(t){super({x:t.pos.x,y:t.pos.y,width:t.width,height:t.height}),this.action=()=>{},this.filter=()=>!0,this.repeat=-1,t=Object.assign(Object.assign({},js),t),this.filter=t.filter||this.filter,this.repeat=t.repeat||this.repeat,this.action=t.action||this.action,t.target&&(this.target=t.target),this.graphics.visible=t.visible,this.body.collisionType=hi.Passive,this.eventDispatcher=new he,this.events.on("collisionstart",(t=>{this.filter(t.other)&&(this.emit("enter",new oe(this,t.other)),this._dispatchAction(),0===this.repeat&&this.kill())})),this.events.on("collisionend",(t=>{this.filter(t.other)&&this.emit("exit",new ae(this,t.other))}))}set target(t){this._target=t,this.filter=e=>e===t}get target(){return this._target}_initialize(t){super._initialize(t)}_dispatchAction(){0!==this.repeat&&(this.action.call(this),this.repeat--)}debugDraw(t){super.debugDraw(t),t.save(),t.translate(this.pos.x,this.pos.y);const e=this.collider.bounds,i=this.getGlobalPos();e.left=e.left-i.x,e.right=e.right-i.x,e.top=e.top-i.y,e.bottom=e.bottom-i.y,t.fillStyle=T.Violet.toString(),t.strokeStyle=T.Violet.toString(),t.fillText("Trigger",10,10),e.debugDraw(t),t.restore()}}var qs;!function(t){t.Update="update",t.Draw="draw"}(qs||(qs={}));class Ks{constructor(){this.priority=0}notify(t){}}class Zs{constructor(t){this.data=t,this.type="Entity Added"}}function Ys(t){return!!t&&"Entity Added"===t.type}class Qs{constructor(t){this.data=t,this.type="Entity Removed"}}function $s(t){return!!t&&"Entity Removed"===t.type}class Js{constructor(t){this._world=t,this.entities=[],this._entityIndex={},this._entitiesToRemove=[]}updateEntities(t,e){for(const i of this.entities)i.update(t.engine,e),i.active||this.removeEntity(i)}findEntitiesForRemoval(){for(const t of this.entities)t.active||this.removeEntity(t)}notify(t){Xi(t)&&this._world.queryManager.addEntity(t.data.entity),Ki(t)&&this._world.queryManager.removeComponent(t.data.entity,t.data.component)}addEntity(t){t.active=!0,t&&!this._entityIndex[t.id]&&(this._entityIndex[t.id]=t,this.entities.push(t),this._world.queryManager.addEntity(t),t.componentAdded$.register(this),t.componentRemoved$.register(this),t.children.forEach((t=>this.addEntity(t))),t.childrenAdded$.register({notify:t=>{this.addEntity(t)}}),t.childrenRemoved$.register({notify:t=>{this.removeEntity(t,!1)}}))}removeEntity(t,e=!0){var i;let s=0;s=t instanceof Zi?t.id:t;const n=this._entityIndex[s];n&&n.active&&n.kill(),n&&e?this._entitiesToRemove.push(n):(delete this._entityIndex[s],n&&(G(n,this.entities),this._world.queryManager.removeEntity(n),n.componentAdded$.unregister(this),n.componentRemoved$.unregister(this),n.children.forEach((t=>this.removeEntity(t,e))),n.childrenAdded$.clear(),n.childrenRemoved$.clear(),(null===(i=this._world.context)||void 0===i?void 0:i.engine)&&this._world.context.engine.stats.currFrame.actors.killed++))}processEntityRemovals(){for(const t of this._entitiesToRemove)t.active||this.removeEntity(t,!1)}processComponentRemovals(){for(const t of this.entities)t.processComponentRemoval()}getById(t){return this._entityIndex[t]}getByName(t){return this.entities.filter((e=>e.name===t))}clear(){for(const t of this.entities)this.removeEntity(t)}}const tn=t=>[...t].sort(((t,e)=>t.localeCompare(e))).join("+");class en extends xi{constructor(t){super(),this._entities=[],t[0]instanceof Function?this.types=t.map((t=>(new t).type)):this.types=t}get key(){return this._key?this._key:this._key=tn(this.types)}getEntities(t){return t&&this._entities.sort(t),this._entities}addEntity(t){!j(this._entities,t)&&this.matches(t)&&(this._entities.push(t),this.notifyAll(new Zs(t)))}removeEntity(t){G(t,this._entities)&&this.notifyAll(new Qs(t))}clear(){this._entities.length=0;for(const t of this.observers)this.unregister(t)}matches(t){let e=[];e=t instanceof Zi?t.types:t;let i=!0;for(const t of this.types)if(i=i&&e.indexOf(t)>-1,!i)return!1;return i}contain(t){return this.types.indexOf(t)>-1}}class sn{constructor(t){this._world=t,this._queries={}}_addQuery(t){this._queries[tn(t.types)]=t;for(const e of this._world.entityManager.entities)t.addEntity(e)}maybeRemoveQuery(t){0===t.observers.length&&(t.clear(),delete this._queries[tn(t.types)])}addEntity(t){for(const e in this._queries)this._queries[e]&&this._queries[e].addEntity(t)}removeComponent(t,e){for(const i in this._queries)this._queries[i].contain(e.type)&&this._queries[i].removeEntity(t)}removeEntity(t){for(const e in this._queries)this._queries[e].removeEntity(t)}createQuery(t){const e=this.getQuery(t);if(e)return e;const i=new en(t);return this._addQuery(i),i}getQuery(t){const e=tn(t);return this._queries[e]?this._queries[e]:null}}class nn{constructor(t){this._world=t,this.systems=[],this.initialized=!1}get(t){return this.systems.find((e=>e instanceof t))}addSystem(t){if(!t.types||0===t.types.length)throw new Error("Attempted to add a System without any types");const e=this._world.queryManager.createQuery(t.types);this.systems.push(t),this.systems.sort(((t,e)=>t.priority-e.priority)),e.register(t),this.initialized&&t.initialize&&t.initialize(this._world.context)}removeSystem(t){G(t,this.systems);const e=this._world.queryManager.getQuery(t.types);e&&(e.unregister(t),this._world.queryManager.maybeRemoveQuery(e))}updateSystems(t,e,i){if(!this.initialized){this.initialized=!0;for(const t of this.systems)t.initialize&&t.initialize(this._world.context)}const s=this.systems.filter((e=>e.systemType===t));for(const t of s)t.preupdate&&t.preupdate(e,i);for(const t of s){const s=this._world.queryManager.getQuery(t.types).getEntities(t.sort);if(e instanceof Ln)for(const t of s)t._initialize(null==e?void 0:e.engine);t.update(s,i)}for(const t of s)t.postupdate&&t.postupdate(e,i)}clear(){for(const t of this.systems)this.removeSystem(t)}}class rn{constructor(t){this.context=t,this.queryManager=new sn(this),this.entityManager=new Js(this),this.systemManager=new nn(this)}update(t,e){t===qs.Update&&this.entityManager.updateEntities(this.context,e),this.systemManager.updateSystems(t,this.context,e),this.entityManager.findEntitiesForRemoval(),this.entityManager.processComponentRemovals(),this.entityManager.processEntityRemovals()}add(t){t instanceof Zi&&this.entityManager.addEntity(t),t instanceof Ks&&this.systemManager.addSystem(t)}remove(t,e=!0){t instanceof Zi&&this.entityManager.removeEntity(t,e),t instanceof Ks&&this.systemManager.removeSystem(t)}clearEntities(){this.entityManager.clear()}clearSystems(){this.systemManager.clear()}}class on{static integrate(t,e,i,s){const n=s/1e3;e.vel.addEqual(i.scale(n)),t.pos.addEqual(e.vel.scale(n)).addEqual(i.scale(.5*n*n)),e.angularVelocity+=e.torque*(1/e.inertia)*n,t.rotation+=e.angularVelocity*n,t.scale.addEqual(e.scaleFactor.scale(n))}}class an extends Ks{constructor(){super(...arguments),this.types=["ex.transform","ex.motion"],this.systemType=qs.Update,this.priority=-1}update(t,e){let i,s;for(const n of t){i=n.get(yi),s=n.get(wi);const t=n.get(Wi);if(null==t?void 0:t.sleeping)continue;const r=s.acc.clone();(null==t?void 0:t.collisionType)===hi.Active&&(null==t?void 0:t.useGravity)&&r.addEqual(pi.gravity),null==t||t.captureOldTransform(),on.integrate(i,s,r,e)}}debugDraw(t){}}class hn{solve(t){return this.preSolve(t),t=t.filter((t=>!t.isCanceled())),this.solveVelocity(t),this.solvePosition(t),this.postSolve(t),t}}class ln extends hn{preSolve(t){for(const e of t){const t=P.fromDirection(e.mtv),i=e.mtv.negate();e.colliderA.events.emit("precollision",new qt(e.colliderA,e.colliderB,t,i)),e.colliderB.events.emit("precollision",new qt(e.colliderB,e.colliderA,P.getOpposite(t),i.negate()))}}postSolve(t){var e,i;for(const s of t){const t=s.colliderA,n=s.colliderB,r=null===(e=t.owner)||void 0===e?void 0:e.get(Wi),o=null===(i=n.owner)||void 0===i?void 0:i.get(Wi);if(r&&o&&(r.collisionType===hi.Passive||o.collisionType===hi.Passive))continue;const a=P.fromDirection(s.mtv),h=s.mtv.negate();s.colliderA.events.emit("postcollision",new Kt(s.colliderA,s.colliderB,a,h)),s.colliderB.events.emit("postcollision",new Kt(s.colliderB,s.colliderA,P.getOpposite(a),h.negate()))}}solvePosition(t){var e,i;for(const s of t){if(!s.colliderA.bounds.intersect(s.colliderB.bounds))continue;let t=s.mtv;const n=s.colliderA,r=s.colliderB,o=null===(e=n.owner)||void 0===e?void 0:e.get(Wi),a=null===(i=r.owner)||void 0===i?void 0:i.get(Wi);if(o&&a){if(o.collisionType===hi.Passive||a.collisionType===hi.Passive)continue;o.collisionType===hi.Active&&a.collisionType===hi.Active&&(t=t.scale(.5)),o.collisionType===hi.Active&&(o.pos.x-=t.x,o.pos.y-=t.y),a.collisionType===hi.Active&&(a.pos.x+=t.x,a.pos.y+=t.y)}}}solveVelocity(t){var e,i;for(const s of t){const t=s.colliderA,n=s.colliderB,r=null===(e=t.owner)||void 0===e?void 0:e.get(Wi),o=null===(i=n.owner)||void 0===i?void 0:i.get(Wi);if(r&&o){if(r.collisionType===hi.Passive||o.collisionType===hi.Passive)continue;const t=s.normal,e=t.negate();if(r.collisionType===hi.Active){const e=t.scale(t.dot(r.vel.negate()));r.vel=r.vel.add(e)}if(o.collisionType===hi.Active){const t=e.scale(e.dot(o.vel.negate()));o.vel=o.vel.add(t)}}}}}class cn{constructor(t,e,i){this.point=t,this.local=e,this.contact=i,this.normalImpulse=0,this.tangentImpulse=0,this.normalMass=0,this.tangentMass=0,this.aToContact=new A(0,0),this.bToContact=new A(0,0),this.update()}update(){var t,e;const i=null===(t=this.contact.colliderA.owner)||void 0===t?void 0:t.get(Wi),s=null===(e=this.contact.colliderB.owner)||void 0===e?void 0:e.get(Wi);if(i&&s){const t=this.contact.normal,e=this.contact.tangent;this.aToContact=this.point.sub(i.pos),this.bToContact=this.point.sub(s.pos);const n=this.aToContact.cross(t),r=this.bToContact.cross(t);this.normalMass=i.inverseMass+s.inverseMass+i.inverseInertia*n*n+s.inverseInertia*r*r;const o=this.aToContact.cross(e),a=this.bToContact.cross(e);this.tangentMass=i.inverseMass+s.inverseMass+i.inverseInertia*o*o+s.inverseInertia*a*a}return this}getRelativeVelocity(){var t,e;const i=null===(t=this.contact.colliderA.owner)||void 0===t?void 0:t.get(Wi),s=null===(e=this.contact.colliderB.owner)||void 0===e?void 0:e.get(Wi);if(i&&s){const t=i.vel.add(A.cross(i.angularVelocity,this.aToContact));return s.vel.add(A.cross(s.angularVelocity,this.bToContact)).sub(t)}return A.Zero}}class dn extends hn{constructor(){super(...arguments),this.lastFrameContacts=new Map,this.idToContactConstraint=new Map}getContactConstraints(t){var e;return null!==(e=this.idToContactConstraint.get(t))&&void 0!==e?e:[]}preSolve(t){var e,i,s;for(const e of t){const t=P.fromDirection(e.mtv);e.colliderA.events.emit("precollision",new qt(e.colliderA,e.colliderB,t,e.mtv)),e.colliderA.events.emit("beforecollisionresolve",new Qt(e.colliderA,e.colliderB,t,e.mtv,e)),e.colliderB.events.emit("precollision",new qt(e.colliderB,e.colliderA,P.getOpposite(t),e.mtv.negate())),e.colliderB.events.emit("beforecollisionresolve",new Qt(e.colliderB,e.colliderA,P.getOpposite(t),e.mtv.negate(),e)),e.matchAwake()}const n=Array.from(this.idToContactConstraint.keys());for(const r of t){const t=n.indexOf(r.id);t>-1&&n.splice(t,1);const o=null!==(e=this.idToContactConstraint.get(r.id))&&void 0!==e?e:[];let a=0;const h=r.colliderA.owner.get(Wi),l=r.colliderB.owner.get(Wi);if(h&&l)for(const t of r.points){const e=r.normal,n=r.tangent,c=t.sub(h.pos),d=t.sub(l.pos),u=c.cross(e),p=d.cross(e),g=h.inverseMass+l.inverseMass+h.inverseInertia*u*u+l.inverseInertia*p*p,_=c.cross(n),f=d.cross(n),m=h.inverseMass+l.inverseMass+h.inverseInertia*_*_+l.inverseInertia*f*f;o[a]&&(null===(s=null===(i=o[a])||void 0===i?void 0:i.point)||void 0===s?void 0:s.squareDistance(t))<4?(o[a].point=t,o[a].local=r.localPoints[a]):o[a]=new cn(t,r.localPoints[a],r),o[a].aToContact=c,o[a].bToContact=d,o[a].normalMass=g,o[a].tangentMass=m,a++}this.idToContactConstraint.set(r.id,o)}for(const t of n)this.idToContactConstraint.delete(t);if(pi.warmStart)this.warmStart(t);else for(const e of t){const t=this.getContactConstraints(e.id);for(const e of t)e.normalImpulse=0,e.tangentImpulse=0}}postSolve(t){for(const e of t){const t=e.colliderA.owner.get(Wi),i=e.colliderB.owner.get(Wi);if(t&&i){if(t.collisionType===hi.Passive||i.collisionType===hi.Passive)continue;t.updateMotion(),i.updateMotion()}const s=P.fromDirection(e.mtv);e.colliderA.events.emit("postcollision",new Kt(e.colliderA,e.colliderB,s,e.mtv)),e.colliderA.events.emit("aftercollisionresolve",new $t(e.colliderA,e.colliderB,s,e.mtv,e)),e.colliderB.events.emit("postcollision",new Kt(e.colliderB,e.colliderA,P.getOpposite(s),e.mtv.negate())),e.colliderB.events.emit("aftercollisionresolve",new $t(e.colliderB,e.colliderA,P.getOpposite(s),e.mtv.negate(),e))}this.lastFrameContacts.clear();for(const e of t)this.lastFrameContacts.set(e.id,e)}warmStart(t){var e,i,s;for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Wi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Wi);if(t&&r){const e=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const i of e)if(pi.warmStart){const e=n.normal.scale(i.normalImpulse),s=n.tangent.scale(i.tangentImpulse),o=e.add(s);t.applyImpulse(i.point,o.negate()),r.applyImpulse(i.point,o)}else i.normalImpulse=0,i.tangentImpulse=0}}}solvePosition(t){var e,i,s;for(let n=0;n<pi.positionIterations;n++)for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Wi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Wi);if(t&&r){if(t.collisionType===hi.Passive||r.collisionType===hi.Passive)continue;const e=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const i of e){const e=n.normal,s=Li.FindContactSeparation(n,i.local),o=-5,a=L(pi.steeringFactor*(s+pi.slop),o,0),h=e.scale(-a/i.normalMass);t.collisionType===hi.Active&&(t.pos=t.pos.add(h.negate().scale(t.inverseMass)),t.rotation-=i.aToContact.cross(h)*t.inverseInertia),r.collisionType===hi.Active&&(r.pos=r.pos.add(h.scale(r.inverseMass)),r.rotation+=i.bToContact.cross(h)*r.inverseInertia)}}}}solveVelocity(t){var e,i,s;for(let n=0;n<pi.velocityIterations;n++)for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Wi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Wi);if(t&&r){if(t.collisionType===hi.Passive||r.collisionType===hi.Passive)continue;const e=t.bounciness*r.bounciness,i=Math.min(t.friction,r.friction),o=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const e of o){let s=-e.getRelativeVelocity().dot(n.tangent)/e.tangentMass;const o=i*e.normalImpulse,a=L(e.tangentImpulse+s,-o,o);s=a-e.tangentImpulse,e.tangentImpulse=a;const h=n.tangent.scale(s);t.applyImpulse(e.point,h.negate()),r.applyImpulse(e.point,h)}for(const i of o){let s=-(1+e)*i.getRelativeVelocity().dot(n.normal)/i.normalMass;const o=Math.max(i.normalImpulse+s,0);s=o-i.normalImpulse,i.normalImpulse=o;const a=n.normal.scale(s);t.applyImpulse(i.point,a.negate()),r.applyImpulse(i.point,a)}}}}}class un extends Ks{constructor(){super(...arguments),this.types=["ex.transform","ex.motion","ex.collider"],this.systemType=qs.Update,this.priority=-1,this._realisticSolver=new dn,this._arcadeSolver=new ln,this._processor=new Ei,this._lastFrameContacts=new Map,this._currentFrameContacts=new Map,this._trackCollider=t=>this._processor.track(t),this._untrackCollider=t=>this._processor.untrack(t)}notify(t){if(Ys(t)){const e=t.data.get(Hi);e.$colliderAdded.subscribe(this._trackCollider),e.$colliderRemoved.subscribe(this._untrackCollider);const i=e.get();i&&this._processor.track(i)}else{const e=t.data.get(Hi),i=e.get();e&&i&&this._processor.untrack(i)}}initialize(t){this._engine=t.engine}update(t,e){var i;if(!pi.enabled)return;let s=[];for(const e of t){const t=e.get(Hi),n=null==t?void 0:t.get();t&&(null===(i=t.owner)||void 0===i?void 0:i.active)&&n&&(t.update(),n instanceof Ri?s=s.concat(n.getColliders()):s.push(n))}this._processor.update(s);const n=this._processor.broadphase(s,e);this._currentFrameContacts.clear();let r=this._processor.narrowphase(n,this._engine.debug.stats.currFrame);r=this.getSolver().solve(r),r.forEach((t=>this._currentFrameContacts.set(t.id,t))),this.runContactStartEnd(),this._lastFrameContacts.clear(),this._lastFrameContacts=new Map(this._currentFrameContacts)}getSolver(){return pi.collisionResolutionStrategy===li.Realistic?this._realisticSolver:this._arcadeSolver}debug(t){this._processor.debug(t)}runContactStartEnd(){for(const[t,e]of this._currentFrameContacts)if(!this._lastFrameContacts.has(t)){const t=e.colliderA,i=e.colliderB;t.events.emit("collisionstart",new Jt(t,i,e)),t.events.emit("contactstart",new Zt(t,i,e)),i.events.emit("collisionstart",new Jt(i,t,e)),i.events.emit("contactstart",new Zt(i,t,e))}for(const[t,e]of this._lastFrameContacts)if(!this._currentFrameContacts.has(t)){const t=e.colliderA,i=e.colliderB;t.events.emit("collisionend",new te(t,i)),t.events.emit("contactend",new Yt(t,i)),i.events.emit("collisionend",new te(i,t)),i.events.emit("contactend",new Yt(i,t))}}}var pn,gn,_n;!function(t){t.Forward="forward",t.Backward="backward"}(pn||(pn={})),function(t){t.End="end",t.Loop="loop",t.PingPong="pingpong",t.Freeze="freeze"}(gn||(gn={}));class fn extends wt{constructor(t){var e,i;super(t),this.events=new he,this.frames=[],this.strategy=gn.Loop,this.frameDuration=100,this.timeScale=1,this._idempotencyToken=-1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=0,this._direction=1,this._done=!1,this._playing=!0,this._reversed=!1,this.frames=t.frames,this.strategy=null!==(e=t.strategy)&&void 0!==e?e:this.strategy,this.frameDuration=t.totalDuration?t.totalDuration/this.frames.length:null!==(i=t.frameDuration)&&void 0!==i?i:this.frameDuration,t.reverse&&this.reverse(),this.goToFrame(0)}clone(){return new fn(Object.assign({frames:this.frames.map((t=>Object.assign({},t))),frameDuration:this.frameDuration,reverse:this._reversed,strategy:this.strategy},this.cloneGraphicOptions()))}static fromSpriteSheet(t,e,i,s=gn.Loop){const n=t.sprites.length-1,r=e.filter((t=>t<0||t>n));return r.length&&fn._LOGGER.warn(`Indices into SpriteSheet were provided that don't exist: ${r.join(",")} no frame will be shown`),new fn({frames:t.sprites.filter(((t,i)=>e.indexOf(i)>-1)).map((t=>({graphic:t,duration:i}))),strategy:s})}static toLegacyAnimation(t,e){const i=e.frames.map((t=>Ee.toLegacySprite(t.graphic)));return new Me({sprites:i,loop:e.strategy===gn.Loop,freezeFrame:e.strategy===gn.Freeze?i.length-1:void 0,speed:e.frameDuration,engine:t})}get currentFrame(){return this._currentFrame>=0&&this._currentFrame<this.frames.length?this.frames[this._currentFrame]:null}get currentFrameIndex(){return this._currentFrame}get isPlaying(){return this._playing}reverse(){this.frames=this.frames.slice().reverse(),this._reversed=!this._reversed}get direction(){return!(!this._reversed||1!==this._direction)?pn.Backward:pn.Forward}play(){this._playing=!0}pause(){this._playing=!1,this._firstTick=!0}reset(){this._done=!1,this._firstTick=!0,this._currentFrame=0}get canFinish(){switch(this.strategy){case gn.End:case gn.Freeze:return!0;default:return!1}}get done(){return this._done}goToFrame(t){var e,i;this._currentFrame=t,this._timeLeftInFrame=this.frameDuration;const s=this.frames[this._currentFrame];s&&!this._done&&(this._timeLeftInFrame=(null==s?void 0:s.duration)||this.frameDuration,this.width=null===(e=s.graphic)||void 0===e?void 0:e.width,this.height=null===(i=s.graphic)||void 0===i?void 0:i.height,this.events.emit("frame",s))}_nextFrame(){const t=this._currentFrame;if(this._done)return t;let e=-1;switch(this.strategy){case gn.Loop:e=(t+1)%this.frames.length,0===e&&this.events.emit("loop",this);break;case gn.End:e=t+1,e>=this.frames.length&&(this._done=!0,this._currentFrame=this.frames.length,this.events.emit("end",this));break;case gn.Freeze:e=L(t+1,0,this.frames.length-1),e>=this.frames.length-1&&(this._done=!0,this.events.emit("end",this));break;case gn.PingPong:t+this._direction>=this.frames.length&&(this._direction=-1,this.events.emit("loop",this)),t+this._direction<0&&(this._direction=1,this.events.emit("loop",this)),e=t+this._direction%this.frames.length}return e}tick(t,e=0){this._idempotencyToken!==e&&(this._idempotencyToken=e,this._playing&&(this._firstTick&&(this._firstTick=!1,this.events.emit("frame",this.currentFrame)),this._timeLeftInFrame-=t*this.timeScale,this._timeLeftInFrame<=0&&this.goToFrame(this._nextFrame()),this._updateDimensions()))}_updateDimensions(){var t,e;this.currentFrame&&(this.width=null===(t=this.currentFrame.graphic)||void 0===t?void 0:t.width,this.height=null===(e=this.currentFrame.graphic)||void 0===e?void 0:e.height)}_drawImage(t,e,i){this.currentFrame&&this.currentFrame.graphic.draw(t,e,i)}}fn._LOGGER=_.getInstance();class mn extends wt{constructor(t){super(t),this.members=[],this.members=t.members,this._updateDimensions()}clone(){return new mn(Object.assign({members:[...this.members]},this.cloneGraphicOptions()))}_updateDimensions(){let t=new B;for(const{graphic:e,pos:i}of this.members)t=e.localBounds.translate(i).combine(t);return this.width=t.width,this.height=t.height,t}get localBounds(){let t=new B;for(const{graphic:e,pos:i}of this.members)t=e.localBounds.translate(i).combine(t);return t}_isAnimationOrGroup(t){return t instanceof fn||t instanceof mn}tick(t,e){for(const i of this.members){const s=i.graphic;this._isAnimationOrGroup(s)&&s.tick(t,e)}}reset(){for(const t of this.members){const e=t.graphic;this._isAnimationOrGroup(e)&&e.reset()}}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,e,i)}_drawImage(t,e,i){for(const s of this.members)t.save(),t.translate(e,i),s.graphic.draw(t,s.pos.x,s.pos.y),this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}}!function(t){t[t.Circle=0]="Circle",t[t.Rectangle=1]="Rectangle"}(_n||(_n={}));class yn extends Zi{constructor(t,e,i,s,n,r,o,a,h,l){super(),this.position=new A(0,0),this.velocity=new A(0,0),this.acceleration=new A(0,0),this.particleRotationalVelocity=0,this.currentRotation=0,this.focus=null,this.focusAccel=0,this.opacity=1,this.beginColor=T.White,this.endColor=T.White,this.life=300,this.fadeFlag=!1,this._rRate=1,this._gRate=1,this._bRate=1,this._aRate=0,this._currentColor=T.White,this.emitter=null,this.particleSize=5,this.particleSprite=null,this.sizeRate=0,this.elapsedMultiplier=0,this.visible=!0,this.isOffscreen=!1;let c=t;if(c&&!(t instanceof vn)){const d=t;c=d.emitter,e=d.life,i=d.opacity,n=d.endColor,s=d.beginColor,r=d.position,o=d.velocity,a=d.acceleration,h=d.startSize,l=d.endSize}this.emitter=c,this.life=e||this.life,this.opacity=i||this.opacity,this.endColor=n||this.endColor.clone(),this.beginColor=s||this.beginColor.clone(),this._currentColor=this.beginColor.clone(),this.position=(r||this.position).add(this.emitter.pos),this.velocity=o||this.velocity,this.acceleration=a||this.acceleration,this._rRate=(this.endColor.r-this.beginColor.r)/this.life,this._gRate=(this.endColor.g-this.beginColor.g)/this.life,this._bRate=(this.endColor.b-this.beginColor.b)/this.life,this._aRate=this.opacity/this.life,this.startSize=h||0,this.endSize=l||0,this.endSize>0&&this.startSize>0&&(this.sizeRate=(this.endSize-this.startSize)/this.life,this.particleSize=this.startSize),this.addComponent(this.transform=new yi),this.addComponent(new Yi((t=>this.draw(t)))),this.addComponent(this.graphics=new ts),this.transform.pos=this.position,this.transform.rotation=this.currentRotation,this.transform.scale=S(1,1),this.particleSprite?(this.graphics.opacity=this.opacity,this.graphics.use(Ee.fromLegacySprite(this.particleSprite))):this.graphics.onPostDraw=t=>{t.save(),this.graphics.opacity=this.opacity;const e=this._currentColor.clone();e.a=1,t.debug.drawPoint(S(0,0),{color:e,size:this.particleSize}),t.restore()}}kill(){this.emitter.removeParticle(this)}update(t,e){if(this.life=this.life-e,this.elapsedMultiplier=this.elapsedMultiplier+e,this.life<0&&this.kill(),this.fadeFlag&&(this.opacity=L(this._aRate*this.life,1e-4,1)),this.startSize>0&&this.endSize>0&&(this.particleSize=L(this.sizeRate*e+this.particleSize,Math.min(this.startSize,this.endSize),Math.max(this.startSize,this.endSize))),this._currentColor.r=L(this._currentColor.r+this._rRate*e,0,255),this._currentColor.g=L(this._currentColor.g+this._gRate*e,0,255),this._currentColor.b=L(this._currentColor.b+this._bRate*e,0,255),this._currentColor.a=L(this.opacity,1e-4,1),this.focus){const t=this.focus.sub(this.position).normalize().scale(this.focusAccel).scale(e/1e3);this.velocity=this.velocity.add(t)}else this.velocity=this.velocity.add(this.acceleration.scale(e/1e3));this.position=this.position.add(this.velocity.scale(e/1e3)),this.particleRotationalVelocity&&(this.currentRotation=(this.currentRotation+this.particleRotationalVelocity*e/1e3)%(2*Math.PI)),this.transform.pos=this.position,this.transform.rotation=this.currentRotation,this.transform.scale=S(1,1),this.graphics.opacity=this.opacity}draw(t){if(this.particleSprite)return this.particleSprite.opacity(this.opacity),void this.particleSprite.draw(t,0,0);t.save(),this._currentColor.a=L(this.opacity,1e-4,1),t.fillStyle=this._currentColor.toString(),t.beginPath(),t.arc(0,0,this.particleSize,0,2*Math.PI),t.fill(),t.closePath(),t.restore()}}class wn extends(be(yn)){constructor(t,e,i,s,n,r,o,a,h,l){super(t,e,i,s,n,r,o,a,h,l)}}class vn extends Es{constructor(t){var e,i;super({width:null!==(e=t.width)&&void 0!==e?e:0,height:null!==(i=t.height)&&void 0!==i?i:0}),this._particlesToEmit=0,this.numParticles=0,this.isEmitting=!0,this.particles=[],this.deadParticles=[],this.minVel=0,this.maxVel=0,this.acceleration=new A(0,0),this.minAngle=0,this.maxAngle=0,this.emitRate=1,this.particleLife=2e3,this.fadeFlag=!1,this.focus=null,this.focusAccel=null,this.startSize=null,this.endSize=null,this.minSize=5,this.maxSize=5,this.beginColor=T.White,this.endColor=T.White,this._og=null,this._sprite=null,this.emitterType=_n.Rectangle,this.radius=0,this.particleRotationalVelocity=0,this.randomRotation=!1;const{x:s,y:n,pos:r,isEmitting:o,minVel:a,maxVel:h,acceleration:l,minAngle:c,maxAngle:d,emitRate:u,particleLife:p,opacity:g,fadeFlag:_,focus:f,focusAccel:m,startSize:y,endSize:w,minSize:v,maxSize:x,beginColor:b,endColor:C,particleSprite:P,emitterType:E,radius:R,particleRotationalVelocity:B,randomRotation:D,random:F}=Object.assign({},t);this.pos=null!=r?r:S(null!=s?s:0,null!=n?n:0),this.isEmitting=null!=o?o:this.isEmitting,this.minVel=null!=a?a:this.minVel,this.maxVel=null!=h?h:this.maxVel,this.acceleration=null!=l?l:this.acceleration,this.minAngle=null!=c?c:this.minAngle,this.maxAngle=null!=d?d:this.maxAngle,this.emitRate=null!=u?u:this.emitRate,this.particleLife=null!=p?p:this.particleLife,this.opacity=null!=g?g:this.opacity,this.fadeFlag=null!=_?_:this.fadeFlag,this.focus=null!=f?f:this.focus,this.focusAccel=null!=m?m:this.focusAccel,this.startSize=null!=y?y:this.startSize,this.endSize=null!=w?w:this.endSize,this.minSize=null!=v?v:this.minSize,this.maxSize=null!=x?x:this.maxSize,this.beginColor=null!=b?b:this.beginColor,this.endColor=null!=C?C:this.endColor,this.particleSprite=null!=P?P:this.particleSprite,this.emitterType=null!=E?E:this.emitterType,this.radius=null!=R?R:this.radius,this.particleRotationalVelocity=null!=B?B:this.particleRotationalVelocity,this.randomRotation=null!=D?D:this.randomRotation,this.body.collisionType=hi.PreventCollision,this.random=null!=F?F:new M;for(let t=0;t<this.traits.length;t++)this.traits[t]instanceof Gi&&this.traits.splice(t,1)}get opacity(){return super.graphics.opacity}set opacity(t){super.graphics.opacity=t}get particleSprite(){return this._og}set particleSprite(t){this._og=t,t&&(this._sprite=Ee.fromLegacySprite(t))}removeParticle(t){this.deadParticles.push(t)}emitParticles(t){var e;for(let i=0;i<t;i++){const t=this._createParticle();this.particles.push(t),(null===(e=null==this?void 0:this.scene)||void 0===e?void 0:e.world)&&this.scene.world.add(t)}}clearParticles(){this.particles.length=0}_createParticle(){let t=0,e=0;const i=O(this.minAngle,this.maxAngle,this.random),s=O(this.minVel,this.maxVel,this.random),n=this.startSize||O(this.minSize,this.maxSize,this.random),r=s*Math.cos(i),o=s*Math.sin(i);if(this.emitterType===_n.Rectangle)t=O(0,this.width,this.random),e=O(0,this.height,this.random);else if(this.emitterType===_n.Circle){const s=O(0,this.radius,this.random);t=s*Math.cos(i),e=s*Math.sin(i)}const a=new wn(this,this.particleLife,this.opacity,this.beginColor,this.endColor,new A(t,e),new A(r,o),this.acceleration,this.startSize,this.endSize);return a.fadeFlag=this.fadeFlag,a.particleSize=n,this.particleSprite&&(a.particleSprite=this.particleSprite,a.graphics.opacity=this.opacity,a.graphics.use(this._sprite)),a.particleRotationalVelocity=this.particleRotationalVelocity,this.randomRotation&&(a.currentRotation=O(0,2*Math.PI,this.random)),this.focus&&(a.focus=this.focus.add(new A(this.pos.x,this.pos.y)),a.focusAccel=this.focusAccel),a}update(t,e){var i;super.update(t,e),this.isEmitting&&(this._particlesToEmit+=this.emitRate*(e/1e3),this._particlesToEmit>1&&(this.emitParticles(Math.floor(this._particlesToEmit)),this._particlesToEmit=this._particlesToEmit-Math.floor(this._particlesToEmit)));for(let t=0;t<this.deadParticles.length;t++)G(this.deadParticles[t],this.particles),(null===(i=null==this?void 0:this.scene)||void 0===i?void 0:i.world)&&this.scene.world.remove(this.deadParticles[t],!1);this.deadParticles.length=0}draw(t){this.particles.forEach((e=>e.draw(t)))}debugDraw(t){super.debugDraw(t),t.fillStyle=T.Black.toString(),t.fillText("Particles: "+this.particles.length,this.pos.x,this.pos.y+20),this.focus&&(t.fillRect(this.focus.x+this.pos.x,this.focus.y+this.pos.y,3,3),$e(t,T.Yellow,this.focus.x+this.pos.x,this.focus.y+this.pos.y,this.center.x,this.center.y),t.fillText("Focus",this.focus.x+this.pos.x,this.focus.y+this.pos.y))}}class xn extends Ks{constructor(){super(...arguments),this.types=["ex.transform","ex.graphics"],this.systemType=qs.Draw,this.priority=0,this._token=0}initialize(t){this._graphicsContext=t.engine.graphicsContext,this._camera=t.camera,this._engine=t.engine}sort(t,e){return t.get(yi).z-e.get(yi).z}update(t,e){let i,s;this._clearScreen(),this._token++;for(const n of t){i=n.get(yi),s=n.get(ts);const t=this._isOffscreen(i,s);if(t&&!n.hasTag("offscreen")&&(n.eventDispatcher.emit("exitviewport",new ne(n)),n.addComponent(new fi("offscreen"))),!t&&n.hasTag("offscreen")&&(n.eventDispatcher.emit("enterviewport",new re(n)),n.removeComponent("offscreen")),t)continue;this._pushCameraTransform(i),this._graphicsContext.save(),s.update(e,this._token),this._applyTransform(n),s.onPreDraw&&s.onPreDraw(this._graphicsContext,e);const r=n instanceof wn?n.opacity:1;this._graphicsContext.opacity=s.opacity*r,this._drawGraphicsComponent(s),s.onPostDraw&&s.onPostDraw(this._graphicsContext,e),this._graphicsContext.restore(),this._popCameraTransform(i)}this._graphicsContext.flush(),this._engine.stats.currFrame.graphics.drawnImages=rt.DrawnImagesCount,this._engine.stats.currFrame.graphics.drawCalls=rt.DrawCallCount}_clearScreen(){this._graphicsContext.clear()}_isOffscreen(t,e){if(t.coordPlane===mi.World){return!this._camera.viewport.intersect(e.localBounds.transform(t.getGlobalMatrix()))}return!1}_drawGraphicsComponent(t){var e,i;if(t.visible)for(const s of t.layers.get())for(const{graphic:n,options:r}of s.graphics){let o=t.anchor,a=t.offset;(null==r?void 0:r.anchor)&&(o=r.anchor),(null==r?void 0:r.offset)&&(a=r.offset);const h=-n.width*o.x+a.x,l=-n.height*o.y+a.y;if(null==n||n.draw(this._graphicsContext,h+s.offset.x,l+s.offset.y),(null===(e=this._engine)||void 0===e?void 0:e.isDebug)&&this._engine.debug.graphics.showBounds){const t=S(h+s.offset.x,l+s.offset.y);if(n instanceof mn)for(const e of n.members)null===(i=e.graphic)||void 0===i||i.localBounds.translate(t.add(e.pos)).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor);else null==n||n.localBounds.translate(t).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor)}}}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(yi);e&&(this._graphicsContext.translate(e.pos.x,e.pos.y),this._graphicsContext.scale(e.scale.x,e.scale.y),this._graphicsContext.rotate(e.rotation))}}_pushCameraTransform(t){t.coordPlane===mi.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===mi.World&&this._graphicsContext.restore()}}class bn extends Ks{constructor(){super(...arguments),this.types=["ex.transform","ex.canvas"],this.systemType=qs.Draw,this.priority=-1}initialize(t){this._ctx=t.engine.ctx,this._engine=t.engine,this._camera=t.camera}sort(t,e){return t.get(yi).z-e.get(yi).z}update(t,e){var i,s,n;let r,o;this._clearScreen();const a=t.length;for(let h=0;h<a;h++){const a=null===(n=null===(s=null===(i=t[h])||void 0===i?void 0:i.graphics)||void 0===s?void 0:s.visible)||void 0===n||n,l=t[h].isOffScreen;a&&!l&&(r=t[h].get(yi),o=t[h].get(Yi),this._ctx.save(),this._pushCameraTransform(r),this._ctx.save(),this._applyTransform(t[h]),o.draw(this._ctx,e),this._ctx.restore(),this._popCameraTransform(r),this._ctx.restore()),this._engine.isDebug&&(this._ctx.save(),this._pushCameraTransform(r),this._ctx.strokeStyle="yellow",t[h].debugDraw(this._ctx),this._popCameraTransform(r),this._ctx.restore())}this._engine.isDebug&&(this._ctx.save(),this._camera.draw(this._ctx),this._camera.debugDraw(this._ctx),this._ctx.restore()),this._engine.stats.currFrame.graphics.drawnImages=rt.DrawnImagesCount,this._engine.stats.currFrame.graphics.drawCalls=rt.DrawCallCount}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(yi);e&&(this._ctx.translate(e.pos.x,e.pos.y),this._ctx.rotate(e.rotation),this._ctx.scale(e.scale.x,e.scale.y))}}_clearScreen(){this._ctx.clearRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height),this._ctx.fillStyle=this._engine.backgroundColor.toString(),this._ctx.fillRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height)}_pushCameraTransform(t){t.coordPlane===mi.World&&(this._ctx.save(),this._camera&&this._camera.draw(this._ctx))}_popCameraTransform(t){t.coordPlane===mi.World&&this._ctx.restore()}}class Cn extends Ks{constructor(){super(...arguments),this.types=["ex.transform"],this.systemType=qs.Draw,this.priority=999}initialize(t){this._graphicsContext=t.engine.graphicsContext,this._camera=t.camera,this._engine=t.engine,this._collisionSystem=t.world.systemManager.get(un)}update(t,e){var i,s;if(!this._engine.isDebug)return;const n=this._engine.debug.filter;let r,o;const a=this._engine.debug.entity;let h;const l=this._engine.debug.transform;let c;const d=this._engine.debug.motion;let u;const p=this._engine.debug.collider,g=this._engine.debug.physics;let _;const f=this._engine.debug.graphics;let m;const y=this._engine.debug.body,w=this._engine.debug.camera;for(const e of t){if(e.hasTag("offscreen"))continue;if(e instanceof wn)continue;if(n.useFilter){if(!(0===n.ids.length||n.ids.includes(e.id)))continue;if(!(""===n.nameQuery||e.name.includes(n.nameQuery)))continue}let t=A.Zero;const g=S(0,16);if(r=e.id,o=e.name,h=e.get(yi),this._pushCameraTransform(h),this._graphicsContext.save(),this._applyTransform(e),h&&((l.showAll||l.showPosition)&&(this._graphicsContext.debug.drawPoint(A.Zero,{size:2,color:l.positionColor}),this._graphicsContext.debug.drawText(`pos${h.pos.toString(2)}`,t),t=t.add(g)),(a.showAll||a.showId)&&(this._graphicsContext.debug.drawText(`id(${r}) ${h.parent?"child of id("+(null===(s=null===(i=h.parent)||void 0===i?void 0:i.owner)||void 0===s?void 0:s.id)+")":""}`,t),t=t.add(g)),(a.showAll||a.showName)&&(this._graphicsContext.debug.drawText(`name(${o})`,t),t=t.add(g)),(l.showAll||l.showRotation)&&(this._graphicsContext.drawLine(A.Zero,A.fromAngle(h.rotation).scale(50).add(A.Zero),l.rotationColor,2),this._graphicsContext.debug.drawText(`rot deg(${H(h.rotation).toFixed(2)})`,t),t=t.add(g)),(l.showAll||l.showScale)&&this._graphicsContext.drawLine(A.Zero,h.scale.add(A.Zero),l.scaleColor,2)),_=e.get(ts),_&&(f.showAll||f.showBounds)){_.localBounds.draw(this._graphicsContext,f.boundsColor)}if(m=e.get(Wi),m&&((y.showAll||y.showCollisionGroup)&&(this._graphicsContext.debug.drawText(`collision group(${m.group.name})`,t),t=t.add(g)),(y.showAll||y.showCollisionType)&&(this._graphicsContext.debug.drawText(`collision type(${m.collisionType})`,t),t=t.add(g)),(y.showAll||y.showMass)&&(this._graphicsContext.debug.drawText(`mass(${m.mass})`,t),t=t.add(g)),(y.showAll||y.showMotion)&&(this._graphicsContext.debug.drawText(`motion(${m.sleepMotion})`,t),t=t.add(g)),(y.showAll||y.showSleeping)&&(this._graphicsContext.debug.drawText(`sleeping(${m.canSleep?m.sleeping:"cant sleep"})`,t),t=t.add(g))),this._graphicsContext.restore(),c=e.get(wi),c&&((d.showAll||d.showVelocity)&&(this._graphicsContext.debug.drawText(`vel${c.vel.toString(2)}`,t.add(h.globalPos)),this._graphicsContext.drawLine(h.globalPos,h.globalPos.add(c.vel),d.velocityColor,2),t=t.add(g)),(d.showAll||d.showAcceleration)&&this._graphicsContext.drawLine(h.globalPos,h.globalPos.add(c.acc),d.accelerationColor,2)),u=e.get(Hi),u){const t=u.get();if((p.showAll||p.showGeometry)&&t&&t.debug(this._graphicsContext,p.geometryColor),p.showAll||p.showBounds)if(t instanceof Ri){const e=t.getColliders();for(const t of e){const e=t.bounds,i=S(e.left,e.top);this._graphicsContext.debug.drawRect(i.x,i.y,e.width,e.height,{color:p.boundsColor}),(p.showAll||p.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${t.owner.id})`,i)}u.bounds.draw(this._graphicsContext,p.boundsColor)}else if(t){const t=u.bounds,e=S(t.left,t.top);this._graphicsContext.debug.drawRect(e.x,e.y,t.width,t.height,{color:p.boundsColor}),(p.showAll||p.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${u.owner.id})`,e)}}this._popCameraTransform(h)}if(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(g.showAll||g.showBroadphaseSpacePartitionDebug)&&this._collisionSystem.debug(this._graphicsContext),g.showAll||g.showCollisionContacts||g.showCollisionNormals)for(const[t,e]of this._engine.debug.stats.currFrame.physics.contacts){if(g.showAll||g.showCollisionContacts)for(const t of e.points)this._graphicsContext.debug.drawPoint(t,{size:5,color:g.collisionContactColor});if(g.showAll||g.showCollisionNormals)for(const t of e.points)this._graphicsContext.debug.drawLine(t,e.normal.scale(30).add(t),{color:g.collisionNormalColor})}this._graphicsContext.restore(),w&&(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(w.showAll||w.showFocus)&&this._graphicsContext.drawCircle(this._camera.pos,4,w.focusColor),(w.showAll||w.showZoom)&&this._graphicsContext.debug.drawText(`zoom(${this._camera.zoom})`,this._camera.pos),this._graphicsContext.restore()),this._graphicsContext.flush()}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(yi);e&&(this._graphicsContext.translate(e.pos.x,e.pos.y),this._graphicsContext.scale(e.scale.x,e.scale.y),this._graphicsContext.rotate(e.rotation))}}_pushCameraTransform(t){t.coordPlane===mi.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===mi.World&&this._graphicsContext.restore()}}class An extends Ks{constructor(){super(...arguments),this.types=["ex.transform","ex.pointer"],this.systemType=qs.Update,this.priority=-1,this.lastFrameEntityToPointers=new Map,this.currentFrameEntityToPointers=new Map}initialize(t){this._engine=t.engine,this._receiver=this._engine.input.pointers}sort(t,e){return e.get(yi).z-t.get(yi).z}entityCurrentlyUnderPointer(t,e){return this.currentFrameEntityToPointers.has(t.id)&&this.currentFrameEntityToPointers.get(t.id).includes(e)}entityWasUnderPointer(t,e){return this.lastFrameEntityToPointers.has(t.id)&&this.lastFrameEntityToPointers.get(t.id).includes(e)}entered(t,e){return this.entityCurrentlyUnderPointer(t,e)&&!this.lastFrameEntityToPointers.has(t.id)}left(t,e){return!this.currentFrameEntityToPointers.has(t.id)&&this.entityWasUnderPointer(t,e)}addPointerToEntity(t,e){if(!this.currentFrameEntityToPointers.has(t.id))return void this.currentFrameEntityToPointers.set(t.id,[e]);const i=this.currentFrameEntityToPointers.get(t.id);this.currentFrameEntityToPointers.set(t.id,i.concat(e))}update(t){this._processPointerToEntity(t),this._dispatchEvents(t),this._receiver.update(),this.lastFrameEntityToPointers.clear(),this.lastFrameEntityToPointers=new Map(this.currentFrameEntityToPointers),this.currentFrameEntityToPointers.clear(),this._receiver.clear()}_processPointerToEntity(t){var e;let i,s,n,r;for(const o of t){if(i=o.get(yi),r=null!==(e=o.get(ss))&&void 0!==e?e:new ss,s=o.get(Hi),s&&r.useColliderShape){const t=s.get();if(t)for(const[e,i]of this._receiver.currentFramePointerPositions.entries())t.contains(i)&&this.addPointerToEntity(o,e)}if(n=o.get(ts),n&&r.useGraphicsBounds){const t=n.localBounds.transform(i.getGlobalMatrix());for(const[e,i]of this._receiver.currentFramePointerPositions.entries())t.contains(i)&&this.addPointerToEntity(o,e)}}}_processDownAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameDown)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointerdown",i),this._receiver.isDragStart(i.pointerId)&&t.events.emit("pointerdragstart",i)),e.set(i.pointerId,i);return e}_processUpAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameUp)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointerup",i),this._receiver.isDragEnd(i.pointerId)&&t.events.emit("pointerdragend",i)),e.set(i.pointerId,i);return e}_processMoveAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameMove)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointermove",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragmove",i)),e.set(i.pointerId,i);return e}_processEnterLeaveAndEmit(t,e){for(const i of e){if(i.active&&t.active&&this.entered(t,i.pointerId)){t.events.emit("pointerenter",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragenter",i);break}if(i.active&&t.active&&(this.left(t,i.pointerId)||this.entityCurrentlyUnderPointer(t,i.pointerId)&&"up"===i.type)){t.events.emit("pointerleave",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragleave",i);break}}}_processCancelAndEmit(t){for(const e of this._receiver.currentFrameCancel)e.active&&t.active&&this.entityCurrentlyUnderPointer(t,e.pointerId)&&t.events.emit("pointercancel",e)}_processWheelAndEmit(t){for(const e of this._receiver.currentFrameWheel)e.active&&t.active&&this.entityCurrentlyUnderPointer(t,0)&&t.events.emit("pointerwheel",e)}_dispatchEvents(t){const e=new Set(this.lastFrameEntityToPointers.keys()),i=new Set(this.currentFrameEntityToPointers.keys()),s=t.filter((t=>e.has(t.id)||i.has(t.id)));let n,r,o;for(const t of s){o=this._processDownAndEmit(t),r=this._processUpAndEmit(t),n=this._processMoveAndEmit(t);const e=[...n.values(),...o.values(),...r.values()];this._processEnterLeaveAndEmit(t,e),this._processCancelAndEmit(t),this._processWheelAndEmit(t)}}}class Sn extends Ks{constructor(){super(...arguments),this.types=["ex.actions"],this.systemType=qs.Update,this.priority=-1}update(t,e){let i;for(const s of t)i=s.get(Ss),i.update(e)}}var Pn,En,Tn,Rn,Bn,Dn,Mn,Fn,kn,In=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Ln extends Qe{constructor(){super(),this._logger=_.getInstance(),this.camera=new Vs,this.world=new rn(this),this._isInitialized=!1,this._timers=[],this._cancelQueue=[],this.world.add(new Sn),this.world.add(new an),this.world.add(new un),this.world.add(new An),p.isEnabled(c.LegacyDrawing)?this.world.add(new bn):this.world.add(new xn),this.world.add(new Cn)}get actors(){return this.world.entityManager.entities.filter((t=>t instanceof Es))}get entities(){return this.world.entityManager.entities}get triggers(){return this.world.entityManager.entities.filter((t=>t instanceof Xs))}get tileMaps(){return this.world.entityManager.entities.filter((t=>t instanceof ks))}get screenElements(){return this.actors.filter((t=>t instanceof Ts))}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}onInitialize(t){}onActivate(t,e){}onDeactivate(t,e){}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreDraw(t,e){}onPostDraw(t,e){}_initializeChildren(){for(const t of this.entities)t._initialize(this.engine)}get isInitialized(){return this._isInitialized}_initialize(t){this.isInitialized||(this.engine=t,this.camera._initialize(t),this.onInitialize.call(this,t),this._initializeChildren(),this._logger.debug("Scene.onInitialize",this,t),this.eventDispatcher.emit("initialize",new ee(t,this)),this._isInitialized=!0)}_activate(t,e){this._logger.debug("Scene.onActivate",this),this.onActivate(t,e)}_deactivate(t,e){this._logger.debug("Scene.onDeactivate",this),this.onDeactivate(t,e)}_preupdate(t,e){this.emit("preupdate",new It(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new Lt(t,e,this)),this.onPostUpdate(t,e)}_predraw(t,e){this.emit("predraw",new Dt(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new Mt(t,e,this)),this.onPostDraw(t,e)}update(t,e){let i,s;for(this._preupdate(t,e),this.camera&&this.camera.update(t,e),i=0,s=this._cancelQueue.length;i<s;i++)this.removeTimer(this._cancelQueue[i]);this._cancelQueue.length=0;for(const t of this._timers)t.update(e);this.world.update(qs.Update,e),this._collectActorStats(t),this._postupdate(t,e)}draw(t,e){var i;this._predraw(t,e),this.world.update(qs.Draw,e),(null===(i=this.engine)||void 0===i?void 0:i.isDebug)&&this.debugDraw(t),this._postdraw(t,e)}debugDraw(t){this.emit("predebugdraw",new Ft(t,this)),this.emit("postdebugdraw",new kt(t,this))}contains(t){return this.actors.indexOf(t)>-1}add(t){this.emit("entityadded",{target:t}),this.world.add(t),t.scene=this,t instanceof Bs&&(j(this._timers,t)||this.addTimer(t))}remove(t){t instanceof Zi&&(this.emit("entityremoved",{target:t}),this.world.remove(t)),t instanceof Bs&&this.removeTimer(t)}addScreenElement(t){this.add(t)}removeScreenElement(t){this.remove(t)}addTileMap(t){this.world.add(t)}removeTileMap(t){this.world.remove(t)}addTimer(t){return this._timers.push(t),t.scene=this,t}removeTimer(t){const e=this._timers.indexOf(t);return-1!==e&&this._timers.splice(e,1),t}cancelTimer(t){return this._cancelQueue.push(t),t}isTimerActive(t){return this._timers.indexOf(t)>-1&&!t.complete}isCurrentScene(){return!!this.engine&&this.engine.currentScene===this}_collectActorStats(t){const e=this.actors.filter((t=>t instanceof Ts));for(const i of e)t.stats.currFrame.actors.ui++;for(const e of this.actors){t.stats.currFrame.actors.alive++;for(const i of e.children)Gs(i)?t.stats.currFrame.actors.ui++:t.stats.currFrame.actors.alive++}}}In([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"ScreenElements now are normal actors with a Transform Coordinate Plane of Screen"})],Ln.prototype,"screenElements",null),In([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Scene.add"})],Ln.prototype,"addScreenElement",null),In([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Scene.remove"})],Ln.prototype,"removeScreenElement",null),In([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Scene.add"})],Ln.prototype,"addTileMap",null),In([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Scene.remove"})],Ln.prototype,"removeTileMap",null),function(t){t[t.Protanope=0]="Protanope",t[t.Deuteranope=1]="Deuteranope",t[t.Tritanope=2]="Tritanope"}(Pn||(Pn={}));class On{constructor(t,e=!1,i=Pn.Protanope){this.engine=t,this.simulate=e,this.colorMode=i,this._vertexShader="attribute vec2 a_position;attribute vec2 a_texCoord;uniform vec2 u_resolution;varying vec2 v_texCoord;void main() {vec2 zeroToOne = a_position / u_resolution;vec2 zeroToTwo = zeroToOne * 2.0;vec2 clipSpace = zeroToTwo - 1.0;gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);v_texCoord = a_texCoord;}",this._fragmentShader="precision mediump float;uniform sampler2D u_image;varying vec2 v_texCoord;void main() {vec4 o = texture2D(u_image, v_texCoord);float L = (17.8824 * o.r) + (43.5161 * o.g) + (4.11935 * o.b);float M = (3.45565 * o.r) + (27.1554 * o.g) + (3.86714 * o.b);float S = (0.0299566 * o.r) + (0.184309 * o.g) + (1.46709 * o.b);//MODE CODE//vec4 error;error.r = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s);error.g = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s);error.b = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s);error.a = 1.0;vec4 diff = o - error;vec4 correction;correction.r = 0.0;correction.g = (diff.r * 0.7) + (diff.g * 1.0);correction.b = (diff.r * 0.7) + (diff.b * 1.0);correction = o + correction;correction.a = o.a;//SIMULATE//}",this._internalCanvas=document.createElement("canvas"),this._internalCanvas.width=t.drawWidth,this._internalCanvas.height=t.drawHeight,this._gl=this._internalCanvas.getContext("webgl",{preserveDrawingBuffer:!0}),this._program=this._gl.createProgram();const s=this._getShader("Fragment",this._getFragmentShaderByMode(i)),n=this._getShader("Vertex",this._vertexShader);this._gl.attachShader(this._program,n),this._gl.attachShader(this._program,s),this._gl.linkProgram(this._program),this._gl.getProgramParameter(this._program,this._gl.LINK_STATUS)||_.getInstance().error("Unable to link shader program!"),this._gl.useProgram(this._program)}_getFragmentShaderByMode(t){let e="";return t===Pn.Protanope?e="float l = 0.0 * L + 2.02344 * M + -2.52581 * S;float m = 0.0 * L + 1.0 * M + 0.0 * S;float s = 0.0 * L + 0.0 * M + 1.0 * S;":t===Pn.Deuteranope?e="float l = 1.0 * L + 0.0 * M + 0.0 * S;float m = 0.494207 * L + 0.0 * M + 1.24827 * S;float s = 0.0 * L + 0.0 * M + 1.0 * S;":t===Pn.Tritanope&&(e="float l = 1.0 * L + 0.0 * M + 0.0 * S;float m = 0.0 * L + 1.0 * M + 0.0 * S;float s = -0.395913 * L + 0.801109 * M + 0.0 * S;"),this.simulate?this._fragmentShader=this._fragmentShader.replace("//SIMULATE//","gl_FragColor = error.rgba;"):this._fragmentShader=this._fragmentShader.replace("//SIMULATE//","gl_FragColor = correction.rgba;"),this._fragmentShader.replace("//MODE CODE//",e)}_setRectangle(t,e,i,s){const n=t,r=t+i,o=e,a=e+s;this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array([n,o,r,o,n,a,n,a,r,o,r,a]),this._gl.STATIC_DRAW)}_getShader(t,e){let i;return"Fragment"===t?i=this._gl.createShader(this._gl.FRAGMENT_SHADER):"Vertex"===t?i=this._gl.createShader(this._gl.VERTEX_SHADER):_.getInstance().error("Error unknown shader type",t),this._gl.shaderSource(i,e),this._gl.compileShader(i),this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)?i:(_.getInstance().error("Unable to compile shader!",this._gl.getShaderInfoLog(i)),null)}process(t,e){const i=this._gl.getAttribLocation(this._program,"a_position"),s=this._gl.getAttribLocation(this._program,"a_texCoord"),n=this._gl.createBuffer();this._gl.bindBuffer(this._gl.ARRAY_BUFFER,n),this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this._gl.STATIC_DRAW),this._gl.enableVertexAttribArray(s),this._gl.vertexAttribPointer(s,2,this._gl.FLOAT,!1,0,0);const r=this._gl.createTexture();this._gl.bindTexture(this._gl.TEXTURE_2D,r),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.NEAREST),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.NEAREST),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,1),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);const o=this._gl.getUniformLocation(this._program,"u_resolution");this._gl.uniform2f(o,this._internalCanvas.width,this._internalCanvas.height);const a=this._gl.createBuffer();this._gl.bindBuffer(this._gl.ARRAY_BUFFER,a),this._gl.enableVertexAttribArray(i),this._gl.vertexAttribPointer(i,2,this._gl.FLOAT,!1,0,0),this._setRectangle(0,0,t.width,t.height),this._gl.drawArrays(this._gl.TRIANGLES,0,6);const h=new Uint8Array(t.width*t.height*4);this._gl.readPixels(0,0,t.width,t.height,this._gl.RGBA,this._gl.UNSIGNED_BYTE,h),t.data.set(h),e.putImageData(t,0,0)}}class zn{constructor(t){this._engine=t}correct(t){this._engine.postProcessors.push(new On(this._engine,!1,t))}simulate(t){this._engine.postProcessors.push(new On(this._engine,!0,t))}}class Un{constructor(t){this.stats={currFrame:new Hn,prevFrame:new Hn},this.filter={useFilter:!1,nameQuery:"",ids:[]},this.entity={showAll:!1,showId:!0,showName:!1},this.transform={showAll:!1,showPosition:!1,positionColor:T.Yellow,showScale:!1,scaleColor:T.Green,showRotation:!1,rotationColor:T.Blue},this.graphics={showAll:!1,showBounds:!0,boundsColor:T.Yellow},this.collider={showAll:!1,showBounds:!0,boundsColor:T.Blue,showOwner:!1,showGeometry:!0,geometryColor:T.Green},this.physics={showAll:!1,showBroadphaseSpacePartitionDebug:!1,showCollisionNormals:!1,collisionNormalColor:T.Cyan,showCollisionContacts:!0,collisionContactColor:T.Red},this.motion={showAll:!1,showVelocity:!1,velocityColor:T.Yellow,showAcceleration:!1,accelerationColor:T.Red},this.body={showAll:!1,showCollisionGroup:!1,showCollisionType:!1,showSleeping:!1,showMotion:!1,showMass:!1},this.camera={showAll:!1,showFocus:!1,focusColor:T.Red,showZoom:!1},this._engine=t,this.colorBlindMode=new zn(this._engine)}}class Hn{constructor(){this._id=0,this._delta=0,this._fps=0,this._actorStats={alive:0,killed:0,ui:0,get remaining(){return this.alive-this.killed},get total(){return this.remaining+this.ui}},this._durationStats={update:0,draw:0,get total(){return this.update+this.draw}},this._physicsStats=new Nn,this._graphicsStats={drawCalls:0,drawnImages:0}}reset(t){t?(this.id=t.id,this.delta=t.delta,this.fps=t.fps,this.actors.alive=t.actors.alive,this.actors.killed=t.actors.killed,this.actors.ui=t.actors.ui,this.duration.update=t.duration.update,this.duration.draw=t.duration.draw,this._physicsStats.reset(t.physics),this.graphics.drawCalls=t.graphics.drawCalls,this.graphics.drawnImages=t.graphics.drawnImages):(this.id=this.delta=this.fps=0,this.actors.alive=this.actors.killed=this.actors.ui=0,this.duration.update=this.duration.draw=0,this._physicsStats.reset(),this.graphics.drawnImages=this.graphics.drawCalls=0)}clone(){const t=new Hn;return t.reset(this),t}get id(){return this._id}set id(t){this._id=t}get delta(){return this._delta}set delta(t){this._delta=t}get fps(){return this._fps}set fps(t){this._fps=t}get actors(){return this._actorStats}get duration(){return this._durationStats}get physics(){return this._physicsStats}get graphics(){return this._graphicsStats}}class Nn{constructor(){this._pairs=0,this._collisions=0,this._contacts=new Map,this._fastBodies=0,this._fastBodyCollisions=0,this._broadphase=0,this._narrowphase=0}reset(t){t?(this.pairs=t.pairs,this.collisions=t.collisions,this.contacts=t.contacts,this.fastBodies=t.fastBodies,this.fastBodyCollisions=t.fastBodyCollisions,this.broadphase=t.broadphase,this.narrowphase=t.narrowphase):(this.pairs=this.collisions=this.fastBodies=0,this.fastBodyCollisions=this.broadphase=this.narrowphase=0,this.contacts.clear())}clone(){const t=new Nn;return t.reset(this),t}get pairs(){return this._pairs}set pairs(t){this._pairs=t}get collisions(){return this._collisions}set collisions(t){this._collisions=t}get contacts(){return this._contacts}set contacts(t){this._contacts=t}get fastBodies(){return this._fastBodies}set fastBodies(t){this._fastBodies=t}get fastBodyCollisions(){return this._fastBodyCollisions}set fastBodyCollisions(t){this._fastBodyCollisions=t}get broadphase(){return this._broadphase}set broadphase(t){this._broadphase=t}get narrowphase(){return this._narrowphase}set narrowphase(t){this._narrowphase=t}}!function(t){t.Canvas="Canvas",t.Document="Document"}(En||(En={})),function(t){t.Num0="Numpad0",t.Num1="Numpad1",t.Num2="Numpad2",t.Num3="Numpad3",t.Num4="Numpad4",t.Num5="Numpad5",t.Num6="Numpad6",t.Num7="Numpad7",t.Num8="Numpad8",t.Num9="Numpad9",t.NumAdd="NumpadAdd",t.NumSubtract="NumpadSubtract",t.NumMultiply="NumpadMultiply",t.NumDivide="NumpadDivide",t.NumDecimal="NumpadDecimal",t.Numpad0="Numpad0",t.Numpad1="Numpad1",t.Numpad2="Numpad2",t.Numpad3="Numpad3",t.Numpad4="Numpad4",t.Numpad5="Numpad5",t.Numpad6="Numpad6",t.Numpad7="Numpad7",t.Numpad8="Numpad8",t.Numpad9="Numpad9",t.NumpadAdd="NumpadAdd",t.NumpadSubtract="NumpadSubtract",t.NumpadMultiply="NumpadMultiply",t.NumpadDivide="NumpadDivide",t.NumpadDecimal="NumpadDecimal",t.NumLock="NumLock",t.ShiftLeft="ShiftLeft",t.ShiftRight="ShiftRight",t.AltLeft="AltLeft",t.AltRight="AltRight",t.Key0="Digit0",t.Key1="Digit1",t.Key2="Digit2",t.Key3="Digit3",t.Key4="Digit4",t.Key5="Digit5",t.Key6="Digit6",t.Key7="Digit7",t.Key8="Digit8",t.Key9="Digit9",t.Digit0="Digit0",t.Digit1="Digit1",t.Digit2="Digit2",t.Digit3="Digit3",t.Digit4="Digit4",t.Digit5="Digit5",t.Digit6="Digit6",t.Digit7="Digit7",t.Digit8="Digit8",t.Digit9="Digit9",t.A="KeyA",t.B="KeyB",t.C="KeyC",t.D="KeyD",t.E="KeyE",t.F="KeyF",t.G="KeyG",t.H="KeyH",t.I="KeyI",t.J="KeyJ",t.K="KeyK",t.L="KeyL",t.M="KeyM",t.N="KeyN",t.O="KeyO",t.P="KeyP",t.Q="KeyQ",t.R="KeyR",t.S="KeyS",t.T="KeyT",t.U="KeyU",t.V="KeyV",t.W="KeyW",t.X="KeyX",t.Y="KeyY",t.Z="KeyZ",t.KeyA="KeyA",t.KeyB="KeyB",t.KeyC="KeyC",t.KeyD="KeyD",t.KeyE="KeyE",t.KeyF="KeyF",t.KeyG="KeyG",t.KeyH="KeyH",t.KeyI="KeyI",t.KeyJ="KeyJ",t.KeyK="KeyK",t.KeyL="KeyL",t.KeyM="KeyM",t.KeyN="KeyN",t.KeyO="KeyO",t.KeyP="KeyP",t.KeyQ="KeyQ",t.KeyR="KeyR",t.KeyS="KeyS",t.KeyT="KeyT",t.KeyU="KeyU",t.KeyV="KeyV",t.KeyW="KeyW",t.KeyX="KeyX",t.KeyY="KeyY",t.KeyZ="KeyZ",t.Semicolon="Semicolon",t.Quote="Quote",t.Comma="Comma",t.Minus="Minus",t.Period="Period",t.Slash="Slash",t.Equal="Equal",t.BracketLeft="BracketLeft",t.Backslash="Backslash",t.BracketRight="BracketRight",t.Backquote="Backquote",t.Up="ArrowUp",t.Down="ArrowDown",t.Left="ArrowLeft",t.Right="ArrowRight",t.ArrowUp="ArrowUp",t.ArrowDown="ArrowDown",t.ArrowLeft="ArrowLeft",t.ArrowRight="ArrowRight",t.Space="Space",t.Esc="Escape",t.Escape="Escape"}(Tn||(Tn={}));class Wn extends St{constructor(t,e,i){super(),this.key=t,this.value=e,this.originalEvent=i}}class Vn extends Qe{constructor(){super(),this._keys=[],this._keysUp=[],this._keysDown=[]}on(t,e){super.on(t,e)}init(t){if(!t)try{const e=()=>{};window.top.addEventListener("blur",e),window.top.removeEventListener("blur",e),t=window.top}catch(e){t=window,_.getInstance().warn("Failed to bind to keyboard events to top frame. If you are trying to embed Excalibur in a cross-origin iframe, keyboard events will not fire.")}t.addEventListener("blur",(()=>{this._keys.length=0})),t.addEventListener("keyup",(t=>{const e=t.code,i=this._keys.indexOf(e);this._keys.splice(i,1),this._keysUp.push(e);const s=new Wn(e,t.key,t);this.eventDispatcher.emit("up",s),this.eventDispatcher.emit("release",s)})),t.addEventListener("keydown",(t=>{const e=t.code;if(-1===this._keys.indexOf(e)){this._keys.push(e),this._keysDown.push(e);const i=new Wn(e,t.key,t);this.eventDispatcher.emit("down",i),this.eventDispatcher.emit("press",i)}}))}update(){this._keysDown.length=0,this._keysUp.length=0;for(let t=0;t<this._keys.length;t++)this.eventDispatcher.emit("hold",new Wn(this._keys[t]))}getKeys(){return this._keys}wasPressed(t){return this._keysDown.indexOf(t)>-1}isHeld(t){return this._keys.indexOf(t)>-1}wasReleased(t){return this._keysUp.indexOf(t)>-1}}class Gn extends Qe{constructor(){super(),this.enabled=!1,this.supported=!!navigator.getGamepads,this._gamePadTimeStamps=[0,0,0,0],this._oldPads=[],this._pads=[],this._initSuccess=!1,this._navigator=navigator,this._minimumConfiguration=null}init(){this.supported&&(this._initSuccess||(this._oldPads=this._clonePads(this._navigator.getGamepads()),this._oldPads.length&&this._oldPads[0]&&(this._initSuccess=!0)))}setMinimumGamepadConfiguration(t){this._enableAndUpdate(),this._minimumConfiguration=t}_enableAndUpdate(){this.enabled||(this.enabled=!0,this.update())}_isGamepadValid(t){if(!this._minimumConfiguration)return!0;if(!t)return!1;const e=t.axes.filter((t=>void 0!==typeof t)).length,i=t.buttons.filter((t=>void 0!==typeof t)).length;return e>=this._minimumConfiguration.axis&&i>=this._minimumConfiguration.buttons&&t.connected}on(t,e){this._enableAndUpdate(),super.on(t,e)}off(t,e){this._enableAndUpdate(),super.off(t,e)}update(){if(!this.enabled||!this.supported)return;this.init();const t=this._navigator.getGamepads();for(let e=0;e<t.length;e++){if(!t[e]){const t=this.at(e);t.connected&&this.eventDispatcher.emit("disconnect",new Ht(e,t)),t.connected=!1;continue}if(!this.at(e).connected&&this._isGamepadValid(t[e])&&this.eventDispatcher.emit("connect",new Ut(e,this.at(e))),this.at(e).connected=!0,t[e].timestamp&&t[e].timestamp===this._gamePadTimeStamps[e])continue;let i,s,n,r,o;for(i in this._gamePadTimeStamps[e]=t[e].timestamp,this.at(e).navigatorGamepad=t[e],Rn)s=Rn[i],"number"==typeof s&&t[e].buttons[s]&&(o=t[e].buttons[s].value,o!==this._oldPads[e].getButton(s)&&(t[e].buttons[s].pressed?(this.at(e).updateButton(s,o),this.at(e).eventDispatcher.emit("button",new Nt(s,o,this.at(e)))):this.at(e).updateButton(s,0)));for(n in Bn)r=Bn[n],"number"==typeof r&&(o=t[e].axes[r],o!==this._oldPads[e].getAxes(r)&&(this.at(e).updateAxes(r,o),this.at(e).eventDispatcher.emit("axis",new Wt(r,o,this.at(e)))));this._oldPads[e]=this._clonePad(t[e])}}at(t){if(this._enableAndUpdate(),t>=this._pads.length)for(let e=this._pads.length-1,i=t;e<i;e++)this._pads.push(new jn),this._oldPads.push(new jn);return this._pads[t]}getValidGamepads(){this._enableAndUpdate();const t=[];for(let e=0;e<this._pads.length;e++)this._isGamepadValid(this.at(e).navigatorGamepad)&&this.at(e).connected&&t.push(this.at(e));return t}count(){return this._pads.filter((t=>t.connected)).length}_clonePads(t){const e=[];for(let i=0,s=t.length;i<s;i++)e.push(this._clonePad(t[i]));return e}_clonePad(t){let e,i;const s=new jn;if(!t)return s;for(e=0,i=t.buttons.length;e<i;e++)t.buttons[e]&&s.updateButton(e,t.buttons[e].value);for(e=0,i=t.axes.length;e<i;e++)s.updateAxes(e,t.axes[e]);return s}}Gn.MinAxisMoveThreshold=.05;class jn extends Qe{constructor(){super(),this.connected=!1,this._buttons=new Array(16),this._axes=new Array(4);for(let t=0;t<this._buttons.length;t++)this._buttons[t]=0;for(let t=0;t<this._axes.length;t++)this._axes[t]=0}isButtonPressed(t,e=1){return this._buttons[t]>=e}getButton(t){return this._buttons[t]}getAxes(t){const e=this._axes[t];return Math.abs(e)<Gn.MinAxisMoveThreshold?0:e}updateButton(t,e){this._buttons[t]=e}updateAxes(t,e){this._axes[t]=e}}!function(t){t[t.Face1=0]="Face1",t[t.Face2=1]="Face2",t[t.Face3=2]="Face3",t[t.Face4=3]="Face4",t[t.LeftBumper=4]="LeftBumper",t[t.RightBumper=5]="RightBumper",t[t.LeftTrigger=6]="LeftTrigger",t[t.RightTrigger=7]="RightTrigger",t[t.Select=8]="Select",t[t.Start=9]="Start",t[t.LeftStick=10]="LeftStick",t[t.RightStick=11]="RightStick",t[t.DpadUp=12]="DpadUp",t[t.DpadDown=13]="DpadDown",t[t.DpadLeft=14]="DpadLeft",t[t.DpadRight=15]="DpadRight"}(Rn||(Rn={})),function(t){t[t.LeftStickX=0]="LeftStickX",t[t.LeftStickY=1]="LeftStickY",t[t.RightStickX=2]="RightStickX",t[t.RightStickY=3]="RightStickY"}(Bn||(Bn={}));class Xn{constructor(t){this.nativeComponent=t,this._paused=!1,this._nativeHandlers={}}on(t,e){this._nativeHandlers[t]&&this.off(t,this._nativeHandlers[t]),this._nativeHandlers[t]=this._decorate(e),this.nativeComponent.addEventListener(t,this._nativeHandlers[t])}off(t,e){e||(e=this._nativeHandlers[t]),this.nativeComponent.removeEventListener(t,e),this._nativeHandlers[t]=null}_decorate(t){return e=>{this._paused||t(e)}}pause(){this._paused=!0}resume(){this._paused=!1}clear(){for(const t in this._nativeHandlers)this.off(t)}}class qn{constructor(t,e){this._windowGlobal=t,this._documentGlobal=e,this._windowComponent=new Xn(this._windowGlobal),this._documentComponent=new Xn(this._documentGlobal)}get window(){return this._windowComponent}get document(){return this._documentComponent}pause(){this.window.pause(),this.document.pause()}resume(){this.window.resume(),this.document.resume()}clear(){this.window.clear(),this.document.clear()}}class Kn{constructor(t){this._ex=t,this._debugText=new Ve}drawRect(t,e,i,s){this._ex.__ctx.save(),this._ex.__ctx.strokeStyle="red",this._ex.__ctx.strokeRect(this._ex.snapToPixel?~~t:t,this._ex.snapToPixel?~~e:e,this._ex.snapToPixel?~~i:i,this._ex.snapToPixel?~~s:s),this._ex.__ctx.restore()}drawLine(t,e,i={color:T.Black}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.strokeStyle=i.color.toString(),this._ex.__ctx.moveTo(this._ex.snapToPixel?~~t.x:t.x,this._ex.snapToPixel?~~t.y:t.y),this._ex.__ctx.lineTo(this._ex.snapToPixel?~~e.x:e.x,this._ex.snapToPixel?~~e.y:e.y),this._ex.__ctx.lineWidth=2,this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawPoint(t,e={color:T.Black,size:5}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.fillStyle=e.color.toString(),this._ex.__ctx.arc(this._ex.snapToPixel?~~t.x:t.x,this._ex.snapToPixel?~~t.y:t.y,e.size,0,2*Math.PI),this._ex.__ctx.fill(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawText(t,e){this._debugText.write(this._ex,t,e)}}class Zn{constructor(t){this.backgroundColor=T.ExcaliburBlue,this._state=new it,this.snapToPixel=!0,this.debug=new Kn(this);const{canvasElement:e,enableTransparency:i,snapToPixel:s,smoothing:n,backgroundColor:r}=t;this.__ctx=e.getContext("2d",{alpha:null==i||i}),this.backgroundColor=null!=r?r:this.backgroundColor,this.snapToPixel=null!=s?s:this.snapToPixel,this.smoothing=null!=n?n:this.smoothing}get width(){return this.__ctx.canvas.width}get height(){return this.__ctx.canvas.height}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get smoothing(){return this.__ctx.imageSmoothingEnabled}set smoothing(t){this.__ctx.imageSmoothingEnabled=t}resetTransform(){this.__ctx.resetTransform()}updateViewport(){}drawImage(t,e,i,s,n,r,o,a,h){if(0===s||0===n)return;if(0===a||0===h)return;if(0===t.width||0===t.height)return;this.__ctx.globalAlpha=this.opacity;const l=[t,e,i,s,n,r,o,a,h].filter((t=>void 0!==t)).map((t=>"number"==typeof t&&this.snapToPixel?~~t:t));this.__ctx.drawImage.apply(this.__ctx,l),rt.DrawCallCount++,rt.DrawnImagesCount=1}drawLine(t,e,i,s=1){this.__ctx.save(),this.__ctx.beginPath(),this.__ctx.strokeStyle=i.toString(),this.__ctx.moveTo(this.snapToPixel?~~t.x:t.x,this.snapToPixel?~~t.y:t.y),this.__ctx.lineTo(this.snapToPixel?~~e.x:e.x,this.snapToPixel?~~e.y:e.y),this.__ctx.lineWidth=s,this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}drawRectangle(t,e,i,s){this.__ctx.save(),this.__ctx.fillStyle=s.toString(),this.__ctx.fillRect(this.snapToPixel?~~t.x:t.x,this.snapToPixel?~~t.y:t.y,this.snapToPixel?~~e:e,this.snapToPixel?~~i:i),this.__ctx.restore()}drawCircle(t,e,i){this.__ctx.save(),this.__ctx.beginPath(),this.__ctx.fillStyle=i.toString(),this.__ctx.arc(this.snapToPixel?~~t.x:t.x,this.snapToPixel?~~t.y:t.y,e,0,2*Math.PI),this.__ctx.fill(),this.__ctx.closePath(),this.__ctx.restore()}save(){this.__ctx.save()}restore(){this.__ctx.restore()}translate(t,e){this.__ctx.translate(this.snapToPixel?~~t:t,this.snapToPixel?~~e:e)}rotate(t){this.__ctx.rotate(t)}scale(t,e){this.__ctx.scale(t,e)}clear(){this.__ctx.clearRect(0,0,this.width,this.height),this.__ctx.fillStyle=this.backgroundColor.toString(),this.__ctx.fillRect(0,0,this.width,this.height),rt.clear()}flush(){}}class Yn{constructor(t,e,i){this.worldPos=t,this.pagePos=e,this.screenPos=i}static fromPagePosition(t,e,i){let s,n,r,o;3===arguments.length?(s=t,n=e,r=new A(s,n),o=i):(r=t,s=r.x,n=r.y,o=e);const a=o.screen.pageToScreenCoordinates(r),h=o.screen.screenToWorldCoordinates(a);return new Yn(h,r,a)}}class Qn{constructor(t,e,i,s,n,r){this.type=t,this.pointerId=e,this.button=i,this.pointerType=s,this.coordinates=n,this.nativeEvent=r,this.active=!0}cancel(){this.active=!1}get pagePos(){return this.coordinates.pagePos}get screenPos(){return this.coordinates.screenPos}get worldPos(){return this.coordinates.worldPos}}class $n{constructor(t,e,i,s,n,r,o,a,h,l,c,d){this.x=t,this.y=e,this.pageX=i,this.pageY=s,this.screenX=n,this.screenY=r,this.index=o,this.deltaX=a,this.deltaY=h,this.deltaZ=l,this.deltaMode=c,this.ev=d,this.active=!0}cancel(){this.active=!1}}class Jn extends Qe{constructor(){super(),this.lastPagePos=A.Zero,this.lastScreenPos=A.Zero,this.lastWorldPos=A.Zero,this._onPointerMove=t=>{this.lastPagePos=new A(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new A(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new A(t.worldPos.x,t.worldPos.y)},this._onPointerDown=t=>{this.lastPagePos=new A(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new A(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new A(t.worldPos.x,t.worldPos.y)},this.on("move",this._onPointerMove),this.on("down",this._onPointerDown)}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}}!function(t){t.Pixel="Pixel",t.Line="Line",t.Page="Page"}(Dn||(Dn={})),function(t){t[t.NoButton=-1]="NoButton",t[t.Left=0]="Left",t[t.Middle=1]="Middle",t[t.Right=2]="Right",t[t.Unknown=3]="Unknown"}(Mn||(Mn={})),function(t){t.Left="Left",t.Middle="Middle",t.Right="Right",t.Unknown="Unknown",t.NoButton="NoButton"}(Fn||(Fn={})),function(t){t.Touch="Touch",t.Mouse="Mouse",t.Pen="Pen",t.Unknown="Unknown"}(kn||(kn={}));class tr extends Qe{constructor(t,e){super(),this.target=t,this.engine=e,this.primary=new Jn,this._activeNativePointerIdsToNormalized=new Map,this.lastFramePointerPosition=new Map,this.currentFramePointerPositions=new Map,this.currentFramePointerDown=new Map,this.lastFramePointerDown=new Map,this.currentFrameDown=[],this.currentFrameUp=[],this.currentFrameMove=[],this.currentFrameCancel=[],this.currentFrameWheel=[],this._pointers=[this.primary],this._boundHandle=this._handle.bind(this),this._boundWheel=this._handleWheel.bind(this)}at(t){if(t>=this._pointers.length)for(let e=this._pointers.length-1,i=t;e<i;e++)this._pointers.push(new Jn);return this._pointers[t]}count(){return this._pointers.length}isDown(t){var e;return null!==(e=this.currentFramePointerDown.get(t))&&void 0!==e&&e}wasDown(t){var e;return null!==(e=this.lastFramePointerDown.get(t))&&void 0!==e&&e}isDragging(t){return this.isDown(t)}isDragStart(t){return this.isDown(t)&&!this.wasDown(t)}isDragEnd(t){return!this.isDown(t)&&this.wasDown(t)}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}update(){this.lastFramePointerDown=new Map(this.currentFramePointerDown),this.lastFramePointerPosition=new Map(this.currentFramePointerPositions);for(const t of this.currentFrameDown){this.emit("down",t);this.at(t.pointerId).emit("down",t),this.primary.emit("pointerdown",t)}for(const t of this.currentFrameUp){this.emit("up",t);this.at(t.pointerId).emit("up",t)}for(const t of this.currentFrameMove){this.emit("move",t);this.at(t.pointerId).emit("move",t)}for(const t of this.currentFrameCancel){this.emit("cancel",t);this.at(t.pointerId).emit("cancel",t)}for(const t of this.currentFrameWheel)this.emit("wheel",t),this.primary.emit("pointerwheel",t)}clear(){for(const t of this.currentFrameUp){this.currentFramePointerPositions.delete(t.pointerId);const e=this._activeNativePointerIdsToNormalized.entries();for(const[i,s]of e)s===t.pointerId&&this._activeNativePointerIdsToNormalized.delete(i)}this.currentFrameDown.length=0,this.currentFrameUp.length=0,this.currentFrameMove.length=0,this.currentFrameCancel.length=0,this.currentFrameWheel.length=0}init(){this.engine.canvas.style.touchAction="none",window.PointerEvent?(this.target.addEventListener("pointerdown",this._boundHandle),this.target.addEventListener("pointerup",this._boundHandle),this.target.addEventListener("pointermove",this._boundHandle),this.target.addEventListener("pointercancel",this._boundHandle)):(this.target.addEventListener("touchstart",this._boundHandle),this.target.addEventListener("touchend",this._boundHandle),this.target.addEventListener("touchmove",this._boundHandle),this.target.addEventListener("touchcancel",this._boundHandle),this.target.addEventListener("mousedown",this._boundHandle),this.target.addEventListener("mouseup",this._boundHandle),this.target.addEventListener("mousemove",this._boundHandle));const t={passive:!(this.engine.pageScrollPreventionMode===er.All||this.engine.pageScrollPreventionMode===er.Canvas)};"onwheel"in document.createElement("div")?this.target.addEventListener("wheel",this._boundWheel,t):void 0!==document.onmousewheel?this.target.addEventListener("mousewheel",this._boundWheel,t):this.target.addEventListener("MozMousePixelScroll",this._boundWheel,t)}detach(){window.PointerEvent?(this.target.removeEventListener("pointerdown",this._boundHandle),this.target.removeEventListener("pointerup",this._boundHandle),this.target.removeEventListener("pointermove",this._boundHandle),this.target.removeEventListener("pointercancel",this._boundHandle)):(this.target.removeEventListener("touchstart",this._boundHandle),this.target.removeEventListener("touchend",this._boundHandle),this.target.removeEventListener("touchmove",this._boundHandle),this.target.removeEventListener("touchcancel",this._boundHandle),this.target.removeEventListener("mousedown",this._boundHandle),this.target.removeEventListener("mouseup",this._boundHandle),this.target.removeEventListener("mousemove",this._boundHandle)),"onwheel"in document.createElement("div")?this.target.removeEventListener("wheel",this._boundWheel):void 0!==document.onmousewheel?this.target.addEventListener("mousewheel",this._boundWheel):this.target.addEventListener("MozMousePixelScroll",this._boundWheel)}_normalizePointerId(t){this._activeNativePointerIdsToNormalized.set(t,-1);const e=Array.from(this._activeNativePointerIdsToNormalized.keys()).sort(((t,e)=>t-e)).findIndex((e=>e===t));return this._activeNativePointerIdsToNormalized.set(t,e),e}_handle(t){t.preventDefault();const e=new Map;let i,s;if(n=t,globalThis.TouchEvent&&n instanceof globalThis.TouchEvent){i=Fn.Unknown,s=kn.Touch;for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],n=Yn.fromPagePosition(s.pageX,s.pageY,this.engine),r=i+1,o=this._normalizePointerId(r);this.currentFramePointerPositions.set(o,n.worldPos),e.set(o,n)}}else{i=this._nativeButtonToPointerButton(t.button),s=kn.Mouse;const n=Yn.fromPagePosition(t.pageX,t.pageY,this.engine);let r=1;(function(t){return globalThis.PointerEvent&&t instanceof globalThis.PointerEvent})(t)&&(r=t.pointerId,s=this._stringToPointerType(t.pointerType));const o=this._normalizePointerId(r);this.currentFramePointerPositions.set(o,n.worldPos),e.set(o,n)}var n;for(const[n,r]of e.entries())switch(t.type){case"mousedown":case"pointerdown":case"touchstart":this.currentFrameDown.push(new Qn("down",n,i,s,r,t)),this.currentFramePointerDown.set(n,!0);break;case"mouseup":case"pointerup":case"touchend":this.currentFrameUp.push(new Qn("up",n,i,s,r,t)),this.currentFramePointerDown.set(n,!1);break;case"mousemove":case"pointermove":case"touchmove":this.currentFrameMove.push(new Qn("move",n,i,s,r,t));break;case"touchcancel":case"pointercance":this.currentFrameCancel.push(new Qn("cancel",n,i,s,r,t))}}_handleWheel(t){(this.engine.pageScrollPreventionMode===er.All||this.engine.pageScrollPreventionMode===er.Canvas&&t.target===this.engine.canvas)&&t.preventDefault();const e=this.engine.screen.pageToScreenCoordinates(S(t.pageX,t.pageY)),i=this.engine.screen.screenToWorldCoordinates(e),s=-1/40,n=t.deltaX||t.wheelDeltaX*s||0,r=t.deltaY||t.wheelDeltaY*s||t.wheelDelta*s||t.detail||0,o=t.deltaZ||0;let a=Dn.Pixel;t.deltaMode&&(1===t.deltaMode?a=Dn.Line:2===t.deltaMode&&(a=Dn.Page));const h=new $n(i.x,i.y,t.pageX,t.pageY,e.x,e.y,0,n,r,o,a,t);this.currentFrameWheel.push(h)}triggerEvent(t,e){const i=this.engine.screen.worldToPageCoordinates(e);window.PointerEvent?this._handle(new window.PointerEvent("pointer"+t,{pointerId:0,clientX:i.x,clientY:i.y})):this._handle(new window.MouseEvent("mouse"+t,{clientX:i.x,clientY:i.y}));const s=this.engine.currentScene.world.systemManager.get(An),n=this.engine.currentScene.world.queryManager.createQuery(s.types);s.update(n.getEntities())}_nativeButtonToPointerButton(t){switch(t){case Mn.NoButton:return Fn.NoButton;case Mn.Left:return Fn.Left;case Mn.Middle:return Fn.Middle;case Mn.Right:return Fn.Right;case Mn.Unknown:return Fn.Unknown;default:return Z(t)}}_stringToPointerType(t){switch(t){case"touch":return kn.Touch;case"mouse":return kn.Mouse;case"pen":return kn.Pen;default:return kn.Unknown}}}var er,ir=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};u(),function(t){t[t.None=0]="None",t[t.Canvas=1]="Canvas",t[t.All=2]="All"}(er||(er={}));class sr extends Qe{constructor(t){var e,i,s;super(),this._hasStarted=!1,this.postProcessors=[],this.scenes={},this._animations=[],this._suppressPlayButton=!1,this.pauseAudioWhenHidden=!0,this._isDebug=!1,this.debugColor=new T(255,255,255),this.enableCanvasTransparency=!0,this.onFatalException=t=>{_.getInstance().fatal(t)},this._timescale=1,this._isLoading=!1,this._isInitialized=!1,this._deferredGoTo=null,this._loadingComplete=!1,t=Object.assign(Object.assign({},sr._DEFAULT_ENGINE_OPTIONS),t),p.freeze(),this.browser=new qn(window,document);const n=new ai;if(!t.suppressMinimumBrowserFeatureDetection&&!(this._compatible=n.test())){const e=document.createElement("div");if(e.innerText="Sorry, your browser does not support all the features needed for Excalibur",document.body.appendChild(e),n.failedTests.forEach((function(t){const e=document.createElement("div");e.innerText="Browser feature missing "+t,document.body.appendChild(e)})),t.canvasElementId){const e=document.getElementById(t.canvasElementId);e&&e.parentElement.removeChild(e)}return}this._compatible=!0,console.log&&!t.suppressConsoleBootMessage&&(console.log(`%cPowered by Excalibur.js (v${Vr})`,"background: #176BAA; color: white; border-radius: 5px; padding: 15px; font-size: 1.5em; line-height: 80px;"),console.log("\n /| ________________\nO|===|* >________________>\n \\|"),console.log("Visit","http://excaliburjs.com","for more information")),t.suppressPlayButton&&(this._suppressPlayButton=!0),this._logger=_.getInstance(),this._logger.defaultLevel===d.Debug&&n.logBrowserFeatures(),this._logger.debug("Building engine..."),this.canvasElementId=t.canvasElementId,t.canvasElementId?(this._logger.debug("Using Canvas element specified: "+t.canvasElementId),this.canvas=document.getElementById(t.canvasElementId)):t.canvasElement?(this._logger.debug("Using Canvas element specified:",t.canvasElement),this.canvas=t.canvasElement):(this._logger.debug("Using generated canvas element"),this.canvas=document.createElement("canvas"));let r=null!==(e=t.displayMode)&&void 0!==e?e:Xe.Fixed;if(t.width&&t.height||t.viewport?(void 0===t.displayMode&&(r=Xe.Fixed),this._logger.debug("Engine viewport is size "+t.width+" x "+t.height)):t.displayMode||(this._logger.debug("Engine viewport is fit"),r=Xe.FitScreen),p.isEnabled(c.Canvas)){const e=new Zn({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:t.antialiasing,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel});this.graphicsContext=e,this.ctx=e.__ctx}else{const e=new je({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:t.antialiasing,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel});this.graphicsContext=e,this.ctx=e.__ctx}this.screen=new Ke({canvas:this.canvas,context:this.graphicsContext,antialiasing:null===(i=t.antialiasing)||void 0===i||i,browser:this.browser,viewport:null!==(s=t.viewport)&&void 0!==s?s:t.width&&t.height?{width:t.width,height:t.height}:qe.SVGA,resolution:t.resolution,displayMode:r,position:t.position,pixelRatio:t.suppressHiDPIScaling?1:null}),t.backgroundColor&&(this.backgroundColor=t.backgroundColor.clone()),this.enableCanvasTransparency=t.enableCanvasTransparency,this._loader=new ri,this.debug=new Un(this),this._initialize(t),this.rootScene=this.currentScene=new Ln,this.addScene("root",this.rootScene)}get canvasWidth(){return this.screen.canvasWidth}get halfCanvasWidth(){return this.screen.halfCanvasWidth}get canvasHeight(){return this.screen.canvasHeight}get halfCanvasHeight(){return this.screen.halfCanvasHeight}get drawWidth(){return this.screen.drawWidth}get halfDrawWidth(){return this.screen.halfDrawWidth}get drawHeight(){return this.screen.drawHeight}get halfDrawHeight(){return this.screen.halfDrawHeight}get isHiDpi(){return this.screen.isHiDpi}get stats(){return this.debug.stats}get isFullscreen(){return this.screen.isFullScreen}get displayMode(){return this.screen.displayMode}get pixelRatio(){return this.screen.pixelRatio}get isDebug(){return this._isDebug}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}getWorldBounds(){return this.screen.getWorldBounds()}get timescale(){return this._timescale}set timescale(t){t<=0?_.getInstance().error("Cannot set engine.timescale to a value of 0 or less than 0."):this._timescale=t}playAnimation(t,e,i){this._animations.push(new nr(t,e,i))}addTileMap(t){this.currentScene.addTileMap(t)}removeTileMap(t){this.currentScene.removeTileMap(t)}addTimer(t){return this.currentScene.addTimer(t)}removeTimer(t){return this.currentScene.removeTimer(t)}addScene(t,e){this.scenes[t]&&this._logger.warn("Scene",t,"already exists overwriting"),this.scenes[t]=e}removeScene(t){if(t instanceof Ln)for(const e in this.scenes)this.scenes.hasOwnProperty(e)&&this.scenes[e]===t&&delete this.scenes[e];"string"==typeof t&&delete this.scenes[t]}add(t){2!==arguments.length?this._deferredGoTo&&this.scenes[this._deferredGoTo]?this.scenes[this._deferredGoTo].add(t):this.currentScene.add(t):this.addScene(arguments[0],arguments[1])}remove(t){t instanceof Zi&&this.currentScene.remove(t),t instanceof Ln&&this.removeScene(t),"string"==typeof t&&this.removeScene(t)}goToScene(t){if(this.isInitialized)if(this.scenes[t]){const e=this.currentScene,i=this.scenes[t];this._logger.debug("Going to scene:",t),this.currentScene.isInitialized&&(this.currentScene._deactivate.apply(this.currentScene,[e,i]),this.currentScene.eventDispatcher.emit("deactivate",new se(i,this.currentScene))),this.currentScene=i,this.screen.setCurrentCamera(i.camera),this.currentScene._initialize(this),this.currentScene._activate.apply(this.currentScene,[e,i]),this.currentScene.eventDispatcher.emit("activate",new ie(e,this.currentScene))}else this._logger.error("Scene",t,"does not exist!");else this._deferredGoTo=t}screenToWorldCoordinates(t){return this.screen.screenToWorldCoordinates(t)}worldToScreenCoordinates(t){return this.screen.worldToScreenCoordinates(t)}_initialize(t){this.pageScrollPreventionMode=t.scrollPreventionMode;const e=t&&t.pointerScope===En.Document?document:this.canvas;let i,s;this.input={keyboard:new Vn,pointers:new tr(e,this),gamepads:new Gn},this.input.keyboard.init(),this.input.pointers.init(),this.input.gamepads.init(),void 0!==document.hidden?(i="hidden",s="visibilitychange"):"msHidden"in document?(i="msHidden",s="msvisibilitychange"):"webkitHidden"in document&&(i="webkitHidden",s="webkitvisibilitychange"),this.browser.document.on(s,(()=>{document[i]?(this.eventDispatcher.emit("hidden",new Xt(this)),this._logger.debug("Window hidden")):(this.eventDispatcher.emit("visible",new jt(this)),this._logger.debug("Window visible"))})),this.canvasElementId||t.canvasElement||document.body.appendChild(this.canvas)}onInitialize(t){}setAntialiasing(t){this.screen.antialiasing=t}getAntialiasing(){return this.screen.antialiasing}get isInitialized(){return this._isInitialized}_overrideInitialize(t){this.isInitialized||(this.onInitialize(t),super.emit("initialize",new ee(t,this)),this._isInitialized=!0,this._deferredGoTo?this.goToScene(this._deferredGoTo):this.goToScene("root"))}_update(t){if(this._isLoading)return this._loader.update(this,t),this.input.keyboard.update(),void this.input.gamepads.update();this._overrideInitialize(this),this._preupdate(t),this.currentScene.update(this,t),this._animations=this._animations.filter((function(t){return!t.animation.isDone()})),this.input.keyboard.update(),this.input.gamepads.update(),this._postupdate(t)}_preupdate(t){this.emit("preupdate",new It(this,t,this)),this.onPreUpdate(this,t)}onPreUpdate(t,e){}_postupdate(t){this.emit("postupdate",new Lt(this,t,this)),this.onPostUpdate(this,t)}onPostUpdate(t,e){}_draw(t){const e=this.ctx;if(this._predraw(e,t),this._isLoading)return this._loader.canvas.draw(this.graphicsContext,0,0),void this.graphicsContext.flush();this.graphicsContext.backgroundColor=this.backgroundColor,this.currentScene.draw(this.ctx,t);let i=0;const s=this._animations.length;for(;i<s;i++)this._animations[i].animation.draw(e,this._animations[i].x,this._animations[i].y);if(this.isDebug){this.ctx.font="Consolas",this.ctx.fillStyle=this.debugColor.toString();const t=this.input.keyboard.getKeys();for(let e=0;e<t.length;e++)this.ctx.fillText(t[e].toString()+" : "+(Tn[t[e]]?Tn[t[e]]:"Not Mapped"),100,10*e+10);this.ctx.fillText("FPS:"+this.stats.currFrame.fps.toFixed(2).toString(),10,10)}for(let t=0;t<this.postProcessors.length;t++)this.postProcessors[t].process(this.ctx.getImageData(0,0,this.canvasWidth,this.canvasHeight),this.ctx);this._postdraw(e,t)}_predraw(t,e){this.emit("predraw",new Dt(t,e,this)),this.onPreDraw(t,e)}onPreDraw(t,e){}_postdraw(t,e){this.emit("postdraw",new Mt(t,e,this)),this.onPostDraw(t,e)}onPostDraw(t,e){}showDebug(t){this._isDebug=t}toggleDebug(){return this._isDebug=!this._isDebug,this._isDebug}get loadingComplete(){return this._loadingComplete}start(t){if(!this._compatible)return Promise.reject("Excalibur is incompatible with your browser");let e;return this.screen.pushResolutionAndViewport(),this.screen.resolution=this.screen.viewport,this.screen.applyResolutionAndViewport(),this.graphicsContext.updateViewport(),t?(this._loader=t,this._loader.suppressPlayButton=this._suppressPlayButton||this._loader.suppressPlayButton,this._loader.wireEngine(this),e=this.load(this._loader)):e=Promise.resolve(),e.then((()=>{this.screen.popResolutionAndViewport(),this.screen.applyResolutionAndViewport(),this.graphicsContext.updateViewport(),this.emit("start",new Rt(this)),this._loadingComplete=!0})),this._hasStarted||(this._hasStarted=!0,this._logger.debug("Starting game..."),this.browser.resume(),sr.createMainLoop(this,window.requestAnimationFrame,Date.now)(),this._logger.debug("Game started")),e}static createMainLoop(t,e,i){let s=i();return function n(){if(t._hasStarted)try{t._requestId=e(n),t.emit("preframe",new Ot(t,t.stats.prevFrame));const r=i();let o=Math.floor(r-s)||1;o>200&&(o=1);const a=o*t.timescale,h=t.stats.prevFrame.id+1;t.stats.currFrame.reset(),t.stats.currFrame.id=h,t.stats.currFrame.delta=a,t.stats.currFrame.fps=1/(a/1e3);const l=i();t._update(a);const c=i();t._draw(a);const d=i();t.stats.currFrame.duration.update=c-l,t.stats.currFrame.duration.draw=d-c,s=r,t.emit("postframe",new zt(t,t.stats.currFrame)),t.stats.prevFrame.reset(t.stats.currFrame)}catch(e){window.cancelAnimationFrame(t._requestId),t.stop(),t.onFatalException(e)}}}stop(){this._hasStarted&&(this.emit("stop",new Bt(this)),this.browser.pause(),this._hasStarted=!1,this._logger.debug("Game stopped"))}isPaused(){return!this._hasStarted}screenshot(){const t=new Image,e=this.canvas.toDataURL("image/png");return t.src=e,t}load(t){return new Promise((e=>{this._isLoading=!0,t.load().then((()=>{this._suppressPlayButton?setTimeout((()=>{this._isLoading=!1,e()}),500):(this._isLoading=!1,e())}))}))}}sr._DEFAULT_ENGINE_OPTIONS={width:0,height:0,enableCanvasTransparency:!0,canvasElementId:"",canvasElement:void 0,snapToPixel:!1,pointerScope:En.Canvas,suppressConsoleBootMessage:null,suppressMinimumBrowserFeatureDetection:null,suppressHiDPIScaling:null,suppressPlayButton:null,scrollPreventionMode:er.Canvas,backgroundColor:T.fromHex("#2185d0")},ir([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Actor.graphics"})],sr.prototype,"playAnimation",null);let nr=class{constructor(t,e,i){this.animation=t,this.x=e,this.y=i}};nr=ir([b({message:"Will be removed in excalibur v0.26.0"})],nr);class rr extends St{constructor(t,e="MediaEvent"){super(),this.target=t,this._name=e}set bubbles(t){}get bubbles(){return!1}get _path(){return null}set _path(t){}stopPropagation(){}action(){}propagate(){}layPath(t){}}class or extends rr{constructor(t,e){super(t,"NativeSoundEvent"),this.track=e}}class ar extends rr{constructor(t,e){super(t,"NativeSoundProcessedEvent"),this._processedData=e,this.data=this._processedData}}class hr extends bt{constructor(t={}){var e,i,s,n,r,o,a,h,l,c,d,u;super(t),this.quality=2,this.family="sans-serif",this.style=Le.Normal,this.bold=!1,this.unit=Fe.Px,this.textAlign=ke.Left,this.baseAlign=Ie.Alphabetic,this.direction=Oe.LeftToRight,this.size=10,this.shadow=null,this._textBounds=new B,this._textWidth=0,this._textHeight=0,this.family=null!==(e=null==t?void 0:t.family)&&void 0!==e?e:this.family,this.style=null!==(i=null==t?void 0:t.style)&&void 0!==i?i:this.style,this.bold=null!==(s=null==t?void 0:t.bold)&&void 0!==s?s:this.bold,this.size=null!==(n=null==t?void 0:t.size)&&void 0!==n?n:this.size,this.unit=null!==(r=null==t?void 0:t.unit)&&void 0!==r?r:this.unit,this.textAlign=null!==(o=null==t?void 0:t.textAlign)&&void 0!==o?o:this.textAlign,this.baseAlign=null!==(a=null==t?void 0:t.baseAlign)&&void 0!==a?a:this.baseAlign,this.direction=null!==(h=null==t?void 0:t.direction)&&void 0!==h?h:this.direction,this.quality=null!==(l=null==t?void 0:t.quality)&&void 0!==l?l:this.quality,(null==t?void 0:t.shadow)&&(this.shadow={},this.shadow.blur=null!==(c=t.shadow.blur)&&void 0!==c?c:this.shadow.blur,this.shadow.offset=null!==(d=t.shadow.offset)&&void 0!==d?d:this.shadow.offset,this.shadow.color=null!==(u=t.shadow.color)&&void 0!==u?u:this.shadow.color),this.flagDirty()}clone(){return new hr(Object.assign(Object.assign(Object.assign({},this.cloneGraphicOptions()),this.cloneRasterOptions()),{size:this.size,unit:this.unit,family:this.family,style:this.style,bold:this.bold,textAlign:this.textAlign,baseAlign:this.baseAlign,direction:this.direction,shadow:this.shadow?{blur:this.shadow.blur,offset:this.shadow.offset,color:this.shadow.color}:null}))}get fontString(){return`${this.style} ${this.bold?"bold":""} ${this.size}${this.unit} ${this.family}`}get width(){return this._textWidth}set width(t){this._textWidth=t}get height(){var t,e;const i=null!==(e=null===(t=this._lines)||void 0===t?void 0:t.length)&&void 0!==e?e:1;return this._textHeight*i}set height(t){var e,i;const s=null!==(i=null===(e=this._lines)||void 0===e?void 0:e.length)&&void 0!==i?i:1;this._textHeight=t/s}get _rasterWidth(){return this._bitmap.width}get _rasterHeight(){return this._bitmap.height}get _halfRasterWidth(){return Math.floor(this._bitmap.width/2)}get _halfRasterHeight(){return Math.floor(this._bitmap.height/2)}get localBounds(){return this._textBounds}_drawImage(t,e,i){this.dirty&&this.rasterize(),t.drawImage(this._bitmap,0,0,this._rasterWidth,this._rasterHeight,e-this._rasterWidth/this.quality/2,i-this._rasterHeight/this.quality/2,this._rasterWidth/this.quality,this._rasterHeight/this.quality)}_rotate(t){var e;const i=null!==(e=this.origin)&&void 0!==e?e:this._textBounds.center;t.translate(i.x,i.y),t.rotate(this.rotation),t.translate(-i.x,-i.y)}_flip(t){this.flipHorizontal&&(t.translate(this._textBounds.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,-this._textBounds.height/2/this.scale.y),t.scale(1,-1))}updateText(t){this._text!==t&&(this._text=t,this._lines=this._text.split("\n"),this._updateDimensions(),this.flagDirty())}_updateDimensions(){if(this._text){this._applyFont(this._ctx);const t=this._lines.reduce(((t,e)=>t.length>e.length?t:e)),e=this._ctx.measureText(t);this._textWidth=Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight),this._textHeight=Math.abs(e.actualBoundingBoxAscent)+Math.abs(e.actualBoundingBoxDescent);const i=this._textHeight*this._lines.length;this._bitmap.width=2*(this._textWidth+2*this.padding)*this.quality,this._bitmap.height=2*(i+2*this.padding)*this.quality;const s=0,n=0,r=i-Math.abs(e.actualBoundingBoxAscent);this._textBounds=new B({left:s-Math.abs(e.actualBoundingBoxLeft)-this.padding,top:n-Math.abs(e.actualBoundingBoxAscent)-this.padding,bottom:n+r+this.padding,right:s+Math.abs(e.actualBoundingBoxRight)+this.padding})}}_preDraw(t,e,i){this.dirty&&this._updateDimensions(),super._preDraw(t,e,i)}_postDraw(t){this.showDebug&&t.debug.drawRect(-this._halfRasterWidth,-this._halfRasterHeight,this._rasterWidth,this._rasterHeight),t.restore()}_applyFont(t){t.translate(this.padding+this._halfRasterWidth,this.padding+this._halfRasterHeight),t.scale(this.quality,this.quality),t.textAlign=this.textAlign,t.textBaseline=this.baseAlign,t.font=this.fontString,t.direction=this.direction,this.shadow&&(t.shadowColor=this.shadow.color.toString(),t.shadowBlur=this.shadow.blur,t.shadowOffsetX=this.shadow.offset.x,t.shadowOffsetY=this.shadow.offset.y)}execute(t){if(this._text){this._applyRasterProperites(t),this._applyFont(t);const e=this._textHeight;for(let i=0;i<this._lines.length;i++){const s=this._lines[i];this.color&&t.fillText(s,0,i*e),this.strokeColor&&t.strokeText(s,0,i*e)}this.showDebug&&($e(t,T.Red,-this._halfRasterWidth,0,this._halfRasterWidth,0,2),$e(t,T.Red,0,-this._halfRasterHeight,0,this._halfRasterHeight,2))}}render(t,e,i,s){this.updateText(e),this.draw(t,i,s)}}class lr extends wt{constructor(t){var e,i;super(t),this._text="",this.font=null!==(e=t.font)&&void 0!==e?e:new hr,this.color=null!==(i=t.color)&&void 0!==i?i:this.color,this.text=t.text}clone(){return new lr({text:this.text.slice(),color:this.color.clone(),font:this.font.clone()})}get text(){return this._text}set text(t){this._text=t,this.font.updateText(t)}get color(){return this.font instanceof hr?this.font.color:T.Black}set color(t){this.font instanceof hr&&(this.font.color=t)}get font(){return this._font}set font(t){this._font=t instanceof hr?vt(t,(t=>t.flagDirty())):t}get width(){return this.font.width}get height(){return this.font.height}get localBounds(){return this.font.localBounds}_rotate(t){}_flip(t){}_drawImage(t,e,i){this.font instanceof hr&&(this.font.color=this.color),this.font.flipHorizontal=this.flipHorizontal,this.font.flipVertical=this.flipVertical,this.font.scale=this.scale,this.font.rotation=this.rotation,this.font.origin=this.origin,this.font.opacity=this.opacity,this.font.render(t,this._text,e,i)}}var cr=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class dr extends Es{constructor(t){super(t),this.font=new hr,this._text=new lr({text:"",font:this.font}),this.letterSpacing=0,this.caseInsensitive=!0;const{text:e,pos:i,x:s,y:n,spriteFont:r,font:o,color:a}=t;this.pos=null!=i?i:s&&n?S(s,n):this.pos,this.text=null!=e?e:this.text,this.spriteFont=null!=r?r:this.spriteFont,this.font=null!=o?o:this.font,this.color=null!=a?a:this.color;const h=this.get(ts);h.anchor=A.Zero,h.use(this._text)}get text(){return this._text.text}set text(t){this._text.text=t}get color(){return this._text.color}set color(t){this._text.color=t}get opacity(){return this._text.opacity}set opacity(t){this._text.opacity=t}get bold(){return this.font.bold}set bold(t){this.font.bold=t}get fontFamily(){return this.font.family}set fontFamily(t){this.font.family=t}get fontSize(){return this.font.size}set fontSize(t){this.font.size=t}get fontStyle(){return this.font.style}set fontStyle(t){this.font.style=t}get fontUnit(){return this.font.unit}set fontUnit(t){this.font.unit=t}get textAlign(){return this.font.textAlign}set textAlign(t){this.font.textAlign=t}get baseAlign(){return this.font.baseAlign}set baseAlign(t){this.font.baseAlign=t}get spriteFont(){return this._legacySpriteFont}set spriteFont(t){if(t){if(t instanceof He)return this._legacySpriteFont=t,this._spriteFont=We.fromLegacySpriteFont(t),void(this._text.font=this._spriteFont);this._spriteFont=t,this._text.font=this._spriteFont}}_initialize(t){super._initialize(t),this._graphicsContext=t.graphicsContext}getTextWidth(){return this._text.width}setTextShadow(t,e,i){this.font.shadow={offset:S(t,e),blur:2,color:i}}useTextShadow(t){this.spriteFont&&this.spriteFont.useTextShadow(t)}clearTextShadow(){this.font.shadow=null}draw(t,e){const i=this._graphicsContext;this._text.draw(i,0,0)}}cr([b({message:"Label.bold will be removed in v0.26.0",alternateMethod:"Use Label.font.bold"})],dr.prototype,"bold",null),cr([b({message:"Label.fontFamily will be removed in v0.26.0",alternateMethod:"Use Label.font.family"})],dr.prototype,"fontFamily",null),cr([b({message:"Label.fontSize will be removed in v0.26.0",alternateMethod:"Use Label.font.size"})],dr.prototype,"fontSize",null),cr([b({message:"Label.fontStyle will be removed in v0.26.0",alternateMethod:"Use Lable.font.style"})],dr.prototype,"fontStyle",null),cr([b({message:"Label.fontUnit will be removed in v0.26.0",alternateMethod:"Use Label.font.unit"})],dr.prototype,"fontUnit",null),cr([b({message:"Label.textAlign will be removed in v0.26.0",alternateMethod:"Use Label.font.textAlign"})],dr.prototype,"textAlign",null),cr([b({message:"Label.baseAlign will be removed in v0.26.0",alternateMethod:"Use Label.font.baseAlign"})],dr.prototype,"baseAlign",null),cr([b()],dr.prototype,"spriteFont",null),cr([b({message:"Label.setTextShadow will be removed in v0.26.0",alternateMethod:"Use Label.font.shadow"})],dr.prototype,"setTextShadow",null),cr([b({message:"Label.useTextShadow will be removed in v0.26.0",alternateMethod:"Use Label.font.shadow"})],dr.prototype,"useTextShadow",null),cr([b({message:"Label.clearTextShadow will be removed in v0.26.0",alternateMethod:"Use Label.font.shadow"})],dr.prototype,"clearTextShadow",null);class ur{static create(t,e){if(this._CURRENT_GROUP>this._MAX_GROUPS)throw new Error(`Cannot have more than ${this._MAX_GROUPS} collision groups`);if(this._GROUPS.get(t))throw new Error(`Collision group ${t} already exists`);const i=new vi(t,this._CURRENT_BIT,void 0!==e?e:~this._CURRENT_BIT);return this._CURRENT_BIT=this._CURRENT_BIT<<1|0,this._CURRENT_GROUP++,this._GROUPS.set(t,i),i}static get groups(){return Array.from(this._GROUPS.values())}static groupByName(t){return this._GROUPS.get(t)}static reset(){this._GROUPS=new Map,this._CURRENT_BIT=this._STARTING_BIT,this._CURRENT_GROUP=1}}ur._STARTING_BIT=1,ur._MAX_GROUPS=32,ur._CURRENT_GROUP=1,ur._CURRENT_BIT=ur._STARTING_BIT,ur._GROUPS=new Map;var pr=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};let gr=class{constructor(t){this.lineWidth=5,this.filled=!1,this._points=[],this.anchor=A.Zero,this.offset=A.Zero,this.rotation=0,this.scale=A.One,this.opacity=1,this._points=t;const e=this._points.reduce(((t,e)=>Math.min(t,e.x)),0),i=this._points.reduce(((t,e)=>Math.max(t,e.x)),0);this.drawWidth=i-e;const s=this._points.reduce(((t,e)=>Math.min(t,e.y)),0),n=this._points.reduce(((t,e)=>Math.max(t,e.y)),0);this.drawHeight=n-s,this.height=this.drawHeight,this.width=this.drawWidth}addEffect(){}removeEffect(){}clearEffects(){}reset(){}draw(t,e,i){t instanceof CanvasRenderingContext2D?this._drawWithOptions({ctx:t,x:e,y:i}):this._drawWithOptions(t)}_drawWithOptions(t){var e,i,s,n,r,o,a,h,l;const{ctx:c,x:d,y:u,rotation:p,drawWidth:g,drawHeight:_,anchor:f,offset:m,opacity:y,flipHorizontal:w,flipVertical:v}=Object.assign(Object.assign({},t),{rotation:null!==(e=t.rotation)&&void 0!==e?e:this.rotation,drawWidth:null!==(i=t.drawWidth)&&void 0!==i?i:this.drawWidth,drawHeight:null!==(s=t.drawHeight)&&void 0!==s?s:this.drawHeight,flipHorizontal:null!==(n=t.flipHorizontal)&&void 0!==n?n:this.flipHorizontal,flipVertical:null!==(r=t.flipVertical)&&void 0!==r?r:this.flipVertical,anchor:null!==(o=t.anchor)&&void 0!==o?o:this.anchor,offset:null!==(a=t.offset)&&void 0!==a?a:this.offset,opacity:(null!==(h=t.opacity)&&void 0!==h?h:1)*(null!==(l=this.opacity)&&void 0!==l?l:1)}),x=g*f.x+m.x+d,b=_*f.y+m.y+u;c.save(),c.translate(x,b),c.scale(this.scale.x,this.scale.y),c.rotate(p),c.beginPath(),c.lineWidth=this.lineWidth;const C=this._points[0];c.moveTo(C.x,C.y);let A=0;const S=this._points.length;for(;A<S;A++)c.lineTo(this._points[A].x,this._points[A].y);c.lineTo(C.x,C.y),c.closePath(),this.filled&&(c.fillStyle=this.fillColor.toString(),c.fill()),c.strokeStyle=this.lineColor.toString(),w&&(c.translate(g,0),c.scale(-1,1)),v&&(c.translate(0,_),c.scale(1,-1));const P=c.globalAlpha;c.globalAlpha=y,c.stroke(),c.globalAlpha=P,c.restore()}};gr=pr([b({message:"Polygon will be removed in v0.26.0",alternateMethod:"Use Graphics.Polygon"})],gr);class _r{}function fr(t){return!!t._initialize}function mr(t){return!!t.onInitialize}function yr(t){return!!t._preupdate}function wr(t){return!!t.onPreUpdate}function vr(t){return!!t.onPostUpdate}function xr(t){return!!t.onPostUpdate}function br(t){return!!t.onPreDraw}function Cr(t){return!!t.onPostDraw}_r.type={any:"",blob:"blob",json:"json",text:"text",document:"document",arraybuffer:"arraybuffer"};class Ar{constructor(t){this._src=t,this._volume=1,this._duration=void 0,this._loop=!1,this._isPlaying=!1,this._isPaused=!1,this._audioContext=Ze.create(),this._volumeNode=this._audioContext.createGain(),this._currentOffset=0,this._createNewBufferSource()}set loop(t){this._loop=t,this._instance&&(this._instance.loop=t,this._wireUpOnEnded())}get loop(){return this._loop}set volume(t){t=L(t,0,1),this._volume=t,this._isPlaying&&this._volumeNode.gain.setTargetAtTime?this._volumeNode.gain.setTargetAtTime(t,this._audioContext.currentTime,.1):this._volumeNode.gain.value=t}get volume(){return this._volume}set duration(t){this._duration=t}get duration(){return this._duration}get _playbackRate(){return this._instance?1/(this._instance.playbackRate.value||1):null}isPlaying(){return this._isPlaying}play(t=(()=>{})){return this._isPaused&&(this._resumePlayBack(),t()),this._isPlaying||(this._startPlayBack(),t()),this._playingPromise}pause(){this._isPlaying&&(this._isPaused=!0,this._isPlaying=!1,this._instance.stop(0),this._setPauseOffset())}stop(){this._isPlaying&&(this._isPlaying=!1,this._isPaused=!1,this._currentOffset=0,this._instance.stop(0),this._instance.onended||this._handleOnEnded())}_startPlayBack(){this._isPlaying=!0,this._isPaused=!1,this._playingPromise=new Promise((t=>{this._playingResolve=t})),this._instance||this._createNewBufferSource(),this._rememberStartTime(),this._volumeNode.connect(this._audioContext.destination),this._instance.start(0,0),this._currentOffset=0,this._wireUpOnEnded()}_resumePlayBack(){if(!this._isPaused)return;this._isPaused=!1,this._isPlaying=!0,this._instance.onended=null,this._createNewBufferSource();const t=this._playbackRate*this._src.duration,e=this._currentOffset%t;this._rememberStartTime(-1e3*e),this._instance.start(0,e),this._wireUpOnEnded()}_wireUpOnEnded(){this.loop||(this._instance.onended=()=>this._handleOnEnded())}_handleOnEnded(){this._isPaused||(this._isPlaying=!1,this._playingResolve(!0))}_rememberStartTime(t){this._startTime=(new Date).getTime()+(0|t)}_setPauseOffset(){this._currentOffset=((new Date).getTime()-this._startTime)*this._playbackRate/1e3}_createNewBufferSource(){this._instance=this._audioContext.createBufferSource(),this._instance.buffer=this._src,this._instance.loop=this.loop,this._instance.playbackRate.setValueAtTime(1,0),this._instance.connect(this._volumeNode)}}function Sr(t){try{const e=new Audio,i=/.*\.([A-Za-z0-9]+)$/,s=t.match(i)[1];return!!e.canPlayType("audio/"+s)}catch(t){return _.getInstance().warn("Cannot determine audio support, assuming no support for the Audio Tag",t),!1}}var Pr=function(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((s=s.apply(t,e||[])).next())}))};class Er extends Qe{constructor(...t){super(),this.logger=_.getInstance(),this._loop=!1,this._volume=1,this._duration=void 0,this._isStopped=!1,this._isPaused=!1,this._tracks=[],this._wasPlayingOnHidden=!1,this._audioContext=Ze.create(),this._resource=new le("",_r.type.arraybuffer);for(const e of t)if(Sr(e)){this.path=e;break}this.path||(this.logger.warn("This browser does not support any of the audio files specified:",t.join(", ")),this.logger.warn("Attempting to use",t[0]),this.path=t[0])}set loop(t){this._loop=t;for(const t of this._tracks)t.loop=this._loop;this.logger.debug("Set loop for all instances of sound",this.path,"to",this._loop)}get loop(){return this._loop}set volume(t){this._volume=t;for(const t of this._tracks)t.volume=this._volume;this.emit("volumechange",new or(this)),this.logger.debug("Set loop for all instances of sound",this.path,"to",this._volume)}get volume(){return this._volume}get duration(){return this._duration}get instances(){return this._tracks}get path(){return this._resource.path}set path(t){this._resource.path=t}isLoaded(){return!!this.data}load(){return Pr(this,void 0,void 0,(function*(){if(this.data)return this.data;const t=yield this._resource.load(),e=yield this.decodeAudio(t.slice(0));return this._duration="object"==typeof e?e.duration:void 0,this.emit("processed",new ar(this,e)),this.data=e}))}decodeAudio(t){return Pr(this,void 0,void 0,(function*(){try{return yield this._audioContext.decodeAudioData(t.slice(0))}catch(t){return this.logger.error("Unable to decode this browser may not fully support this format, or the file may be corrupt, if this is an mp3 try removing id3 tags and album art from the file."),yield Promise.reject()}}))}wireEngine(t){t&&(this._engine=t,this._engine.on("hidden",(()=>{t.pauseAudioWhenHidden&&this.isPlaying()&&(this._wasPlayingOnHidden=!0,this.pause())})),this._engine.on("visible",(()=>{t.pauseAudioWhenHidden&&this._wasPlayingOnHidden&&(this.play(),this._wasPlayingOnHidden=!1)})),this._engine.on("start",(()=>{this._isStopped=!1})),this._engine.on("stop",(()=>{this.stop(),this._isStopped=!0})))}instanceCount(){return this._tracks.length}isPlaying(){return this._tracks.some((t=>t.isPlaying()))}play(t){return this.isLoaded()?this._isStopped?(this.logger.warn("Cannot start playing. Engine is in a stopped state."),Promise.resolve(!1)):(this.volume=t||this.volume,this._isPaused?this._resumePlayback():this._startPlayback()):(this.logger.warn("Cannot start playing. Resource",this.path,"is not loaded yet"),Promise.resolve(!0))}pause(){if(this.isPlaying()){for(const t of this._tracks)t.pause();this._isPaused=!0,this.emit("pause",new or(this)),this.logger.debug("Paused all instances of sound",this.path)}}stop(){for(const t of this._tracks)t.stop();this.emit("stop",new or(this)),this._isPaused=!1,this._tracks.length=0,this.logger.debug("Stopped all instances of sound",this.path)}getTrackId(t){return this._tracks.indexOf(t)}_resumePlayback(){return Pr(this,void 0,void 0,(function*(){if(this._isPaused){const t=[];for(const e of this._tracks)t.push(e.play());this._isPaused=!1,this.emit("resume",new or(this)),this.logger.debug("Resuming paused instances for sound",this.path,this._tracks),yield Promise.all(t)}return!0}))}_startPlayback(){return Pr(this,void 0,void 0,(function*(){const t=yield this._getTrackInstance(this.data),e=yield t.play((()=>{this.emit("playbackstart",new or(this,t)),this.logger.debug("Playing new instance for sound",this.path)}));return this.emit("playbackend",new or(this,t)),this._tracks.splice(this.getTrackId(t),1),e}))}_getTrackInstance(t){const e=new Ar(t);return e.loop=this.loop,e.volume=this.volume,e.duration=this.duration,this._tracks.push(e),e}}var Tr=function(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{h(s.next(t))}catch(t){r(t)}}function a(t){try{h(s.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}h((s=s.apply(t,e||[])).next())}))};class Rr{constructor(t,e=T.Magenta,i=!0){this.path=t,this.color=e,this.bustCache=i,this._stream=null,this._gif=null,this._textures=[],this._animation=null,this._transparentColor=null,this._resource=new le(t,"arraybuffer",i),this._transparentColor=e}load(){return Tr(this,void 0,void 0,(function*(){const t=yield this._resource.load();this._stream=new Mr(t),this._gif=new Fr(this._stream,this._transparentColor);const e=this._gif.images.map((t=>new Re(t.src,!1)));return yield Promise.all(e.map((t=>t.load()))),this.data=this._textures=e}))}isLoaded(){return!!this.data}toLegacySprite(t=0){return Ee.toLegacySprite(this.toSprite(t))}toLegacySpriteSheet(){return Ne.toLegacySpriteSheet(this.toSpriteSheet())}toLegacyAnimation(t,e){return fn.toLegacyAnimation(t,this.toAnimation(e))}toSprite(t=0){return this._textures[t].toSprite()}toSpriteSheet(){const t=this._textures.map((t=>t.toSprite()));return new Ne({sprites:t})}toAnimation(t){const e=this.toSpriteSheet(),i=e.sprites.length;return this._animation=fn.fromSpriteSheet(e,Y(0,i),t),this._animation}get readCheckBytes(){return this._gif.checkBytes}}const Br=t=>t.reduce((function(t,e){return 2*t+e}),0),Dr=t=>{const e=[];for(let i=7;i>=0;i--)e.push(!!(t&1<<i));return e};class Mr{constructor(t){if(this.data=null,this.len=0,this.position=0,this.readByte=()=>{if(this.position>=this.data.byteLength)throw new Error("Attempted to read past end of stream.");return this.data[this.position++]},this.readBytes=t=>{const e=[];for(let i=0;i<t;i++)e.push(this.readByte());return e},this.read=t=>{let e="";for(let i=0;i<t;i++)e+=String.fromCharCode(this.readByte());return e},this.readUnsigned=()=>{const t=this.readBytes(2);return(t[1]<<8)+t[0]},this.data=new Uint8Array(t),this.len=this.data.byteLength,0===this.len)throw new Error("No data loaded from file")}}class Fr{constructor(t,e=T.Magenta){this._st=null,this._handler={},this._transparentColor=null,this.frames=[],this.images=[],this.globalColorTable=[],this.checkBytes=[],this.parseColorTable=t=>{const e=[];for(let i=0;i<t;i++){const t="#"+this._st.readBytes(3).map((t=>{const e=t.toString(16);return 1===e.length?"0"+e:e})).join("");e.push(t)}return e},this.readSubBlocks=()=>{let t,e;e="";do{t=this._st.readByte(),e+=this._st.read(t)}while(0!==t);return e},this.parseHeader=()=>{const t={sig:null,ver:null,width:null,height:null,colorRes:null,globalColorTableSize:null,gctFlag:null,sorted:null,globalColorTable:[],bgColor:null,pixelAspectRatio:null};if(t.sig=this._st.read(3),t.ver=this._st.read(3),"GIF"!==t.sig)throw new Error("Not a GIF file.");t.width=this._st.readUnsigned(),t.height=this._st.readUnsigned();const e=Dr(this._st.readByte());t.gctFlag=e.shift(),t.colorRes=Br(e.splice(0,3)),t.sorted=e.shift(),t.globalColorTableSize=Br(e.splice(0,3)),t.bgColor=this._st.readByte(),t.pixelAspectRatio=this._st.readByte(),t.gctFlag&&(t.globalColorTable=this.parseColorTable(1<<t.globalColorTableSize+1),this.globalColorTable=t.globalColorTable),this._handler.hdr&&this._handler.hdr(t)&&this.checkBytes.push(this._handler.hdr)},this.parseExt=t=>{const e=t=>{this.checkBytes.push(this._st.readByte());const e=Dr(this._st.readByte());t.reserved=e.splice(0,3),t.disposalMethod=Br(e.splice(0,3)),t.userInput=e.shift(),t.transparencyGiven=e.shift(),t.delayTime=this._st.readUnsigned(),t.transparencyIndex=this._st.readByte(),t.terminator=this._st.readByte(),this._handler.gce&&this._handler.gce(t)&&this.checkBytes.push(this._handler.gce)},i=t=>{t.comment=this.readSubBlocks(),this._handler.com&&this._handler.com(t)&&this.checkBytes.push(this._handler.com)},s=t=>{this.checkBytes.push(this._st.readByte()),t.ptHeader=this._st.readBytes(12),t.ptData=this.readSubBlocks(),this._handler.pte&&this._handler.pte(t)&&this.checkBytes.push(this._handler.pte)},n=t=>{const e=t=>{this.checkBytes.push(this._st.readByte()),t.unknown=this._st.readByte(),t.iterations=this._st.readUnsigned(),t.terminator=this._st.readByte(),this._handler.app&&this._handler.app.NETSCAPE&&this._handler.app.NETSCAPE(t)&&this.checkBytes.push(this._handler.app)},i=t=>{t.appData=this.readSubBlocks(),this._handler.app&&this._handler.app[t.identifier]&&this._handler.app[t.identifier](t)&&this.checkBytes.push(this._handler.app[t.identifier])};if(this.checkBytes.push(this._st.readByte()),t.identifier=this._st.read(8),t.authCode=this._st.read(3),"NETSCAPE"===t.identifier)e(t);else i(t)},r=t=>{t.data=this.readSubBlocks(),this._handler.unknown&&this._handler.unknown(t)&&this.checkBytes.push(this._handler.unknown)};switch(t.label=this._st.readByte(),t.label){case 249:t.extType="gce",e(t);break;case 254:t.extType="com",i(t);break;case 1:t.extType="pte",s(t);break;case 255:t.extType="app",n(t);break;default:t.extType="unknown",r(t)}},this.parseImg=t=>{t.leftPos=this._st.readUnsigned(),t.topPos=this._st.readUnsigned(),t.width=this._st.readUnsigned(),t.height=this._st.readUnsigned();const e=Dr(this._st.readByte());t.lctFlag=e.shift(),t.interlaced=e.shift(),t.sorted=e.shift(),t.reserved=e.splice(0,2),t.lctSize=Br(e.splice(0,3)),t.lctFlag&&(t.lct=this.parseColorTable(1<<t.lctSize+1)),t.lzwMinCodeSize=this._st.readByte();const i=this.readSubBlocks();t.pixels=function(t,e){let i=0;const s=function(t){let s=0;for(let n=0;n<t;n++)e.charCodeAt(i>>3)&1<<(7&i)&&(s|=1<<n),i++;return s},n=[],r=1<<t,o=r+1;let a=t+1,h=[];const l=function(){h=[],a=t+1;for(let t=0;t<r;t++)h[t]=[t];h[r]=[],h[o]=null};let c,d;for(;;)if(d=c,c=s(a),c!==r){if(c===o)break;if(c<h.length)d!==r&&h.push(h[d].concat(h[c][0]));else{if(c!==h.length)throw new Error("Invalid LZW code.");h.push(h[d].concat(h[d][0]))}n.push.apply(n,h[c]),h.length===1<<a&&a<12&&a++}else l();return n}(t.lzwMinCodeSize,i),t.interlaced&&(t.pixels=((t,e)=>{const i=new Array(t.length),s=t.length/e,n=(s,n)=>{const r=t.slice(n*e,(n+1)*e);i.splice.apply(i,[s*e,e].concat(r))},r=[0,4,2,1],o=[8,8,4,2];let a=0;for(let t=0;t<4;t++)for(let e=r[t];e<s;e+=o[t])n(e,a),a++;return i})(t.pixels,t.width)),this.frames.push(t),this.arrayToImage(t),this._handler.img&&this._handler.img(t)&&this.checkBytes.push(this._handler)},this.parseBlock=()=>{const t={sentinel:this._st.readByte(),type:""};switch(String.fromCharCode(t.sentinel)){case"!":t.type="ext",this.parseExt(t);break;case",":t.type="img",this.parseImg(t);break;case";":t.type="eof",this._handler.eof&&this._handler.eof(t)&&this.checkBytes.push(this._handler.eof);break;default:throw new Error("Unknown block: 0x"+t.sentinel.toString(16))}"eof"!==t.type&&this.parseBlock()},this.arrayToImage=t=>{let e=0;const i=document.createElement("canvas");i.id=e.toString(),i.width=t.width,i.height=t.height,e++;const s=i.getContext("2d");let n=0,r=0;for(let e=0;e<t.pixels.length;e++)r%t.width==0&&(n++,r=0),this.globalColorTable[t.pixels[e]]===this._transparentColor.toHex()?s.fillStyle="rgba(0, 0, 0, 0)":s.fillStyle=this.globalColorTable[t.pixels[e]],s.fillRect(r,n,1,1),r++;const o=new Image;o.src=i.toDataURL(),this.images.push(o)},this._st=t,this._handler={},this._transparentColor=e,this.parseHeader(),this.parseBlock()}}class kr extends bt{constructor(t){super(t),this.points=t.points,this.rasterize()}get points(){return this._points}set points(t){this._points=t;const e=this.minPoint;this.width=this._points.reduce(((t,e)=>Math.max(e.x,t)),0)-e.x,this.height=this._points.reduce(((t,e)=>Math.max(e.y,t)),0)-e.y,this.flagDirty()}get minPoint(){return S(this._points.reduce(((t,e)=>Math.min(e.x,t)),1/0),this._points.reduce(((t,e)=>Math.min(e.y,t)),1/0))}clone(){return new kr(Object.assign(Object.assign({points:this.points.map((t=>t.clone()))},this.cloneGraphicOptions()),this.cloneRasterOptions()))}execute(t){if(this.points&&this.points.length){t.beginPath();const e=this.minPoint.negate(),i=this.points[0].add(e);t.moveTo(i.x,i.y),this.points.forEach((i=>{t.lineTo(i.x+e.x,i.y+e.y)})),t.lineTo(i.x,i.y),t.closePath(),this.color&&t.fill(),this.strokeColor&&t.stroke()}}}var Ir=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};let Lr=class{constructor(t){this._getComparable=t}find(t){return this._find(this._root,t)}_find(t,e){return null!=t&&(this._getComparable(e)===t.getKey()?t.getData().indexOf(e)>-1:this._getComparable(e)<t.getKey()?this._find(t.getLeft(),e):this._find(t.getRight(),e))}get(t){return this._get(this._root,t)}_get(t,e){return null==t?[]:e===t.getKey()?t.getData():e<t.getKey()?this._get(t.getLeft(),e):this._get(t.getRight(),e)}add(t){return null==this._root?(this._root=new Or(this._getComparable(t),[t],null,null),!0):this._insert(this._root,t)}_insert(t,e){return null!=t&&(this._getComparable(e)===t.getKey()?!(t.getData().indexOf(e)>-1)&&(t.getData().push(e),!0):this._getComparable(e)<t.getKey()?null==t.getLeft()?(t.setLeft(new Or(this._getComparable(e),[e],null,null)),!0):this._insert(t.getLeft(),e):null==t.getRight()?(t.setRight(new Or(this._getComparable(e),[e],null,null)),!0):this._insert(t.getRight(),e))}removeByComparable(t){this._root=this._remove(this._root,t)}_remove(t,e){if(null==t)return null;if(this._getComparable(e)!==t.getKey())return this._getComparable(e)<t.getKey()?(t.setLeft(this._remove(t.getLeft(),e)),t):(t.setRight(this._remove(t.getRight(),e)),t);{const i=t.getData().indexOf(e);if(i>-1){if(t.getData().splice(i,1),0===t.getData().length){if(null==t.getLeft()&&null==t.getRight())return null;if(null==t.getLeft())return t.getRight();if(null==t.getRight())return t.getLeft();const e=this._findMinNode(t.getRight());return t.setKey(e.getKey()),t.setData(e.getData()),t.setRight(this._cleanup(t.getRight(),e)),t}return t}}return null}_cleanup(t,e){const i=e.getKey();if(null==t)return null;if(i===t.getKey()){if(null==t.getLeft()&&null==t.getRight())return null;if(null==t.getLeft())return t.getRight();if(null==t.getRight())return t.getLeft();const e=this._findMinNode(t.getRight());return t.setKey(e.getKey()),t.setData(e.getData()),t.setRight(this._cleanup(t.getRight(),e)),t}return e.getKey()<t.getKey()?(t.setLeft(this._cleanup(t.getLeft(),e)),t):(t.setRight(this._cleanup(t.getRight(),e)),t)}_findMinNode(t){let e=t;for(;null!=e.getLeft();)e=e.getLeft();return e}list(){const t=new Array;return this._list(this._root,t),t}_list(t,e){null!=t&&(this._list(t.getLeft(),e),t.getData().forEach((t=>{e.push(t)})),this._list(t.getRight(),e))}};Lr=Ir([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use built in JS array.sort"})],Lr);let Or=class{constructor(t,e,i,s){this._key=t,this._data=e,this._left=i,this._right=s}getKey(){return this._key}setKey(t){this._key=t}getData(){return this._data}setData(t){this._data=t}getLeft(){return this._left}setLeft(t){this._left=t}getRight(){return this._right}setRight(t){this._right=t}};Or=Ir([b({message:"Will be removed in excalibur v0.26.0"})],Or);class zr{constructor(t){this._key=0,this._key=t}getTheKey(){return this._key}setKey(t){this._key=t}}var Ur,Hr,Nr=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};!function(t){t[t.Resolved=0]="Resolved",t[t.Rejected=1]="Rejected",t[t.Pending=2]="Pending"}(Hr||(Hr={}));let Wr=Ur=class{constructor(){this._state=Hr.Pending,this._successCallbacks=[],this._rejectCallback=()=>{}}static resolve(t){return(new Ur).resolve(t)}static reject(t){return(new Ur).reject(t)}static join(){let t=[];if(arguments.length>0&&!Array.isArray(arguments[0]))for(let e=0;e<arguments.length;e++)t[e-0]=arguments[e];else 1===arguments.length&&Array.isArray(arguments[0])&&(t=arguments[0]);const e=new Ur;if(!t||!t.length)return e.resolve();const i=t.length;let s=0,n=0;const r=[];return t.forEach((t=>{t.then((()=>{s+=1,s===i?e.resolve():s+n+r.length===i&&e.reject(r)}),(()=>{n+=1,s+n+r.length===i&&e.reject(r)})).error((t=>{r.push(t),r.length+s+n===i&&e.reject(r)}))})),e}then(t,e){if(t&&(this._successCallbacks.push(t),this.state()===Hr.Resolved))try{t.call(this,this._value)}catch(t){this._handleError(t)}if(e&&(this._rejectCallback=e,this.state()===Hr.Rejected))try{e.call(this,this._value)}catch(t){this._handleError(t)}return this}error(t){return t&&(this._errorCallback=t),this}resolve(t){if(this._state!==Hr.Pending)throw new Error("Cannot resolve a promise that is not in a pending state!");this._value=t;try{this._state=Hr.Resolved,this._successCallbacks.forEach((t=>{t.call(this,this._value)}))}catch(t){this._handleError(t)}return this}reject(t){if(this._state!==Hr.Pending)throw new Error("Cannot reject a promise that is not in a pending state!");this._value=t;try{this._state=Hr.Rejected,this._rejectCallback.call(this,this._value)}catch(t){this._handleError(t)}return this}state(){return this._state}_handleError(t){if(!this._errorCallback)throw t;this._errorCallback.call(this,t)}};Wr=Ur=Nr([b({message:"ex.Promises are being replaced by native browser promises in v0.26.0",alternateMethod:"Use browser native promises"})],Wr);const Vr="0.26.0-alpha.310+5f94c2f";u()})(),s})()}));
|
|
2
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ex=e():t.ex=e()}(self,(function(){return(()=>{var t={4662:(t,e,i)=>{i(3430);var s=i(8791);t.exports=s("Array","sort")},8343:(t,e,i)=>{i(4769);var s=i(9276);t.exports=s.Object.keys},7111:(t,e,i)=>{var s=i(9859),n=i(6733),r=i(9821),o=s.TypeError;t.exports=function(t){if(n(t))return t;throw o(r(t)+" is not a function")}},1176:(t,e,i)=>{var s=i(9859),n=i(5052),r=s.String,o=s.TypeError;t.exports=function(t){if(n(t))return t;throw o(r(t)+" is not an object")}},9540:(t,e,i)=>{var s=i(905),n=i(3231),r=i(9646),o=function(t){return function(e,i,o){var a,h=s(e),l=r(h),c=n(o,l);if(t&&i!=i){for(;l>c;)if((a=h[c++])!=a)return!0}else for(;l>c;c++)if((t||c in h)&&h[c]===i)return t||c||0;return!t&&-1}};t.exports={includes:o(!0),indexOf:o(!1)}},6038:(t,e,i)=>{"use strict";var s=i(4229);t.exports=function(t,e){var i=[][t];return!!i&&s((function(){i.call(null,e||function(){throw 1},1)}))}},1909:(t,e,i)=>{var s=i(5968);t.exports=s([].slice)},3867:(t,e,i)=>{var s=i(1909),n=Math.floor,r=function(t,e){var i=t.length,h=n(i/2);return i<8?o(t,e):a(t,r(s(t,0,h),e),r(s(t,h),e),e)},o=function(t,e){for(var i,s,n=t.length,r=1;r<n;){for(s=r,i=t[r];s&&e(t[s-1],i)>0;)t[s]=t[--s];s!==r++&&(t[s]=i)}return t},a=function(t,e,i,s){for(var n=e.length,r=i.length,o=0,a=0;o<n||a<r;)t[o+a]=o<n&&a<r?s(e[o],i[a])<=0?e[o++]:i[a++]:o<n?e[o++]:i[a++];return t};t.exports=r},7079:(t,e,i)=>{var s=i(5968),n=s({}.toString),r=s("".slice);t.exports=function(t){return r(n(t),8,-1)}},1589:(t,e,i)=>{var s=i(9859),n=i(1601),r=i(6733),o=i(7079),a=i(95)("toStringTag"),h=s.Object,l="Arguments"==o(function(){return arguments}());t.exports=n?o:function(t){var e,i,s;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=h(t),a))?i:l?o(e):"Object"==(s=o(e))&&r(e.callee)?"Arguments":s}},7081:(t,e,i)=>{var s=i(8270),n=i(4826),r=i(7933),o=i(1787);t.exports=function(t,e){for(var i=n(e),a=o.f,h=r.f,l=0;l<i.length;l++){var c=i[l];s(t,c)||a(t,c,h(e,c))}}},5762:(t,e,i)=>{var s=i(7400),n=i(1787),r=i(5358);t.exports=s?function(t,e,i){return n.f(t,e,r(1,i))}:function(t,e,i){return t[e]=i,t}},5358:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},7400:(t,e,i)=>{var s=i(4229);t.exports=!s((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},2635:(t,e,i)=>{var s=i(9859),n=i(5052),r=s.document,o=n(r)&&n(r.createElement);t.exports=function(t){return o?r.createElement(t):{}}},2671:(t,e,i)=>{var s=i(598).match(/firefox\/(\d+)/i);t.exports=!!s&&+s[1]},8506:(t,e,i)=>{var s=i(598);t.exports=/MSIE|Trident/.test(s)},598:(t,e,i)=>{var s=i(1333);t.exports=s("navigator","userAgent")||""},6358:(t,e,i)=>{var s,n,r=i(9859),o=i(598),a=r.process,h=r.Deno,l=a&&a.versions||h&&h.version,c=l&&l.v8;c&&(n=(s=c.split("."))[0]>0&&s[0]<4?1:+(s[0]+s[1])),!n&&o&&(!(s=o.match(/Edge\/(\d+)/))||s[1]>=74)&&(s=o.match(/Chrome\/(\d+)/))&&(n=+s[1]),t.exports=n},9811:(t,e,i)=>{var s=i(598).match(/AppleWebKit\/(\d+)\./);t.exports=!!s&&+s[1]},8791:(t,e,i)=>{var s=i(9859),n=i(5968);t.exports=function(t,e){return n(s[t].prototype[e])}},3837:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},3103:(t,e,i)=>{var s=i(9859),n=i(7933).f,r=i(5762),o=i(7487),a=i(2079),h=i(7081),l=i(6541);t.exports=function(t,e){var i,c,d,u,p,g=t.target,_=t.global,m=t.stat;if(i=_?s:m?s[g]||a(g,{}):(s[g]||{}).prototype)for(c in e){if(u=e[c],d=t.noTargetGet?(p=n(i,c))&&p.value:i[c],!l(_?c:g+(m?".":"#")+c,t.forced)&&void 0!==d){if(typeof u==typeof d)continue;h(u,d)}(t.sham||d&&d.sham)&&r(u,"sham",!0),o(i,c,u,t)}}},4229:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},266:t=>{var e=Function.prototype.call;t.exports=e.bind?e.bind(e):function(){return e.apply(e,arguments)}},1805:(t,e,i)=>{var s=i(7400),n=i(8270),r=Function.prototype,o=s&&Object.getOwnPropertyDescriptor,a=n(r,"name"),h=a&&"something"===function(){}.name,l=a&&(!s||s&&o(r,"name").configurable);t.exports={EXISTS:a,PROPER:h,CONFIGURABLE:l}},5968:t=>{var e=Function.prototype,i=e.bind,s=e.call,n=i&&i.bind(s);t.exports=i?function(t){return t&&n(s,t)}:function(t){return t&&function(){return s.apply(t,arguments)}}},1333:(t,e,i)=>{var s=i(9859),n=i(6733),r=function(t){return n(t)?t:void 0};t.exports=function(t,e){return arguments.length<2?r(s[t]):s[t]&&s[t][e]}},5300:(t,e,i)=>{var s=i(7111);t.exports=function(t,e){var i=t[e];return null==i?void 0:s(i)}},9859:(t,e,i)=>{var s=function(t){return t&&t.Math==Math&&t};t.exports=s("object"==typeof globalThis&&globalThis)||s("object"==typeof window&&window)||s("object"==typeof self&&self)||s("object"==typeof i.g&&i.g)||function(){return this}()||Function("return this")()},8270:(t,e,i)=>{var s=i(5968),n=i(2991),r=s({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,e){return r(n(t),e)}},5977:t=>{t.exports={}},4394:(t,e,i)=>{var s=i(7400),n=i(4229),r=i(2635);t.exports=!s&&!n((function(){return 7!=Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a}))},9337:(t,e,i)=>{var s=i(9859),n=i(5968),r=i(4229),o=i(7079),a=s.Object,h=n("".split);t.exports=r((function(){return!a("z").propertyIsEnumerable(0)}))?function(t){return"String"==o(t)?h(t,""):a(t)}:a},8511:(t,e,i)=>{var s=i(5968),n=i(6733),r=i(5353),o=s(Function.toString);n(r.inspectSource)||(r.inspectSource=function(t){return o(t)}),t.exports=r.inspectSource},6407:(t,e,i)=>{var s,n,r,o=i(8694),a=i(9859),h=i(5968),l=i(5052),c=i(5762),d=i(8270),u=i(5353),p=i(4399),g=i(5977),_="Object already initialized",m=a.TypeError,f=a.WeakMap;if(o||u.state){var w=u.state||(u.state=new f),y=h(w.get),v=h(w.has),x=h(w.set);s=function(t,e){if(v(w,t))throw new m(_);return e.facade=t,x(w,t,e),e},n=function(t){return y(w,t)||{}},r=function(t){return v(w,t)}}else{var b=p("state");g[b]=!0,s=function(t,e){if(d(t,b))throw new m(_);return e.facade=t,c(t,b,e),e},n=function(t){return d(t,b)?t[b]:{}},r=function(t){return d(t,b)}}t.exports={set:s,get:n,has:r,enforce:function(t){return r(t)?n(t):s(t,{})},getterFor:function(t){return function(e){var i;if(!l(e)||(i=n(e)).type!==t)throw m("Incompatible receiver, "+t+" required");return i}}}},6733:t=>{t.exports=function(t){return"function"==typeof t}},6541:(t,e,i)=>{var s=i(4229),n=i(6733),r=/#|\.prototype\./,o=function(t,e){var i=h[a(t)];return i==c||i!=l&&(n(e)?s(e):!!e)},a=o.normalize=function(t){return String(t).replace(r,".").toLowerCase()},h=o.data={},l=o.NATIVE="N",c=o.POLYFILL="P";t.exports=o},5052:(t,e,i)=>{var s=i(6733);t.exports=function(t){return"object"==typeof t?null!==t:s(t)}},4231:t=>{t.exports=!1},9395:(t,e,i)=>{var s=i(9859),n=i(1333),r=i(6733),o=i(1321),a=i(6969),h=s.Object;t.exports=a?function(t){return"symbol"==typeof t}:function(t){var e=n("Symbol");return r(e)&&o(e.prototype,h(t))}},9646:(t,e,i)=>{var s=i(4237);t.exports=function(t){return s(t.length)}},3839:(t,e,i)=>{var s=i(6358),n=i(4229);t.exports=!!Object.getOwnPropertySymbols&&!n((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&s&&s<41}))},8694:(t,e,i)=>{var s=i(9859),n=i(6733),r=i(8511),o=s.WeakMap;t.exports=n(o)&&/native code/.test(r(o))},1787:(t,e,i)=>{var s=i(9859),n=i(7400),r=i(4394),o=i(1176),a=i(9310),h=s.TypeError,l=Object.defineProperty;e.f=n?l:function(t,e,i){if(o(t),e=a(e),o(i),r)try{return l(t,e,i)}catch(t){}if("get"in i||"set"in i)throw h("Accessors not supported");return"value"in i&&(t[e]=i.value),t}},7933:(t,e,i)=>{var s=i(7400),n=i(266),r=i(9195),o=i(5358),a=i(905),h=i(9310),l=i(8270),c=i(4394),d=Object.getOwnPropertyDescriptor;e.f=s?d:function(t,e){if(t=a(t),e=h(e),c)try{return d(t,e)}catch(t){}if(l(t,e))return o(!n(r.f,t,e),t[e])}},8151:(t,e,i)=>{var s=i(140),n=i(3837).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return s(t,n)}},894:(t,e)=>{e.f=Object.getOwnPropertySymbols},1321:(t,e,i)=>{var s=i(5968);t.exports=s({}.isPrototypeOf)},140:(t,e,i)=>{var s=i(5968),n=i(8270),r=i(905),o=i(9540).indexOf,a=i(5977),h=s([].push);t.exports=function(t,e){var i,s=r(t),l=0,c=[];for(i in s)!n(a,i)&&n(s,i)&&h(c,i);for(;e.length>l;)n(s,i=e[l++])&&(~o(c,i)||h(c,i));return c}},5632:(t,e,i)=>{var s=i(140),n=i(3837);t.exports=Object.keys||function(t){return s(t,n)}},9195:(t,e)=>{"use strict";var i={}.propertyIsEnumerable,s=Object.getOwnPropertyDescriptor,n=s&&!i.call({1:2},1);e.f=n?function(t){var e=s(this,t);return!!e&&e.enumerable}:i},2914:(t,e,i)=>{var s=i(9859),n=i(266),r=i(6733),o=i(5052),a=s.TypeError;t.exports=function(t,e){var i,s;if("string"===e&&r(i=t.toString)&&!o(s=n(i,t)))return s;if(r(i=t.valueOf)&&!o(s=n(i,t)))return s;if("string"!==e&&r(i=t.toString)&&!o(s=n(i,t)))return s;throw a("Can't convert object to primitive value")}},4826:(t,e,i)=>{var s=i(1333),n=i(5968),r=i(8151),o=i(894),a=i(1176),h=n([].concat);t.exports=s("Reflect","ownKeys")||function(t){var e=r.f(a(t)),i=o.f;return i?h(e,i(t)):e}},9276:(t,e,i)=>{var s=i(9859);t.exports=s},7487:(t,e,i)=>{var s=i(9859),n=i(6733),r=i(8270),o=i(5762),a=i(2079),h=i(8511),l=i(6407),c=i(1805).CONFIGURABLE,d=l.get,u=l.enforce,p=String(String).split("String");(t.exports=function(t,e,i,h){var l,d=!!h&&!!h.unsafe,g=!!h&&!!h.enumerable,_=!!h&&!!h.noTargetGet,m=h&&void 0!==h.name?h.name:e;n(i)&&("Symbol("===String(m).slice(0,7)&&(m="["+String(m).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),(!r(i,"name")||c&&i.name!==m)&&o(i,"name",m),(l=u(i)).source||(l.source=p.join("string"==typeof m?m:""))),t!==s?(d?!_&&t[e]&&(g=!0):delete t[e],g?t[e]=i:o(t,e,i)):g?t[e]=i:a(e,i)})(Function.prototype,"toString",(function(){return n(this)&&d(this).source||h(this)}))},8885:(t,e,i)=>{var s=i(9859).TypeError;t.exports=function(t){if(null==t)throw s("Can't call method on "+t);return t}},2079:(t,e,i)=>{var s=i(9859),n=Object.defineProperty;t.exports=function(t,e){try{n(s,t,{value:e,configurable:!0,writable:!0})}catch(i){s[t]=e}return e}},4399:(t,e,i)=>{var s=i(3036),n=i(1441),r=s("keys");t.exports=function(t){return r[t]||(r[t]=n(t))}},5353:(t,e,i)=>{var s=i(9859),n=i(2079),r="__core-js_shared__",o=s[r]||n(r,{});t.exports=o},3036:(t,e,i)=>{var s=i(4231),n=i(5353);(t.exports=function(t,e){return n[t]||(n[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.19.1",mode:s?"pure":"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})},3231:(t,e,i)=>{var s=i(3329),n=Math.max,r=Math.min;t.exports=function(t,e){var i=s(t);return i<0?n(i+e,0):r(i,e)}},905:(t,e,i)=>{var s=i(9337),n=i(8885);t.exports=function(t){return s(n(t))}},3329:t=>{var e=Math.ceil,i=Math.floor;t.exports=function(t){var s=+t;return s!=s||0===s?0:(s>0?i:e)(s)}},4237:(t,e,i)=>{var s=i(3329),n=Math.min;t.exports=function(t){return t>0?n(s(t),9007199254740991):0}},2991:(t,e,i)=>{var s=i(9859),n=i(8885),r=s.Object;t.exports=function(t){return r(n(t))}},2066:(t,e,i)=>{var s=i(9859),n=i(266),r=i(5052),o=i(9395),a=i(5300),h=i(2914),l=i(95),c=s.TypeError,d=l("toPrimitive");t.exports=function(t,e){if(!r(t)||o(t))return t;var i,s=a(t,d);if(s){if(void 0===e&&(e="default"),i=n(s,t,e),!r(i)||o(i))return i;throw c("Can't convert object to primitive value")}return void 0===e&&(e="number"),h(t,e)}},9310:(t,e,i)=>{var s=i(2066),n=i(9395);t.exports=function(t){var e=s(t,"string");return n(e)?e:e+""}},1601:(t,e,i)=>{var s={};s[i(95)("toStringTag")]="z",t.exports="[object z]"===String(s)},3326:(t,e,i)=>{var s=i(9859),n=i(1589),r=s.String;t.exports=function(t){if("Symbol"===n(t))throw TypeError("Cannot convert a Symbol value to a string");return r(t)}},9821:(t,e,i)=>{var s=i(9859).String;t.exports=function(t){try{return s(t)}catch(t){return"Object"}}},1441:(t,e,i)=>{var s=i(5968),n=0,r=Math.random(),o=s(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+o(++n+r,36)}},6969:(t,e,i)=>{var s=i(3839);t.exports=s&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},95:(t,e,i)=>{var s=i(9859),n=i(3036),r=i(8270),o=i(1441),a=i(3839),h=i(6969),l=n("wks"),c=s.Symbol,d=c&&c.for,u=h?c:c&&c.withoutSetter||o;t.exports=function(t){if(!r(l,t)||!a&&"string"!=typeof l[t]){var e="Symbol."+t;a&&r(c,t)?l[t]=c[t]:l[t]=h&&d?d(e):u(e)}return l[t]}},3430:(t,e,i)=>{"use strict";var s=i(3103),n=i(5968),r=i(7111),o=i(2991),a=i(9646),h=i(3326),l=i(4229),c=i(3867),d=i(6038),u=i(2671),p=i(8506),g=i(6358),_=i(9811),m=[],f=n(m.sort),w=n(m.push),y=l((function(){m.sort(void 0)})),v=l((function(){m.sort(null)})),x=d("sort"),b=!l((function(){if(g)return g<70;if(!(u&&u>3)){if(p)return!0;if(_)return _<603;var t,e,i,s,n="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(s=0;s<47;s++)m.push({k:e+s,v:i})}for(m.sort((function(t,e){return e.v-t.v})),s=0;s<m.length;s++)e=m[s].k.charAt(0),n.charAt(n.length-1)!==e&&(n+=e);return"DGBEFHACIJK"!==n}}));s({target:"Array",proto:!0,forced:y||!v||!x||!b},{sort:function(t){void 0!==t&&r(t);var e=o(this);if(b)return void 0===t?f(e):f(e,t);var i,s,n=[],l=a(e);for(s=0;s<l;s++)s in e&&w(n,e[s]);for(c(n,function(t){return function(e,i){return void 0===i?-1:void 0===e?1:void 0!==t?+t(e,i)||0:h(e)>h(i)?1:-1}}(t)),i=n.length,s=0;s<i;)e[s]=n[s++];for(;s<l;)delete e[s++];return e}})},4769:(t,e,i)=>{var s=i(3103),n=i(2991),r=i(5632);s({target:"Object",stat:!0,forced:i(4229)((function(){r(1)}))},{keys:function(t){return r(n(t))}})},1388:(t,e,i)=>{"use strict";i.d(e,{Z:()=>a});var s=i(272),n=i.n(s),r=i(2609),o=i.n(r)()(n());o.push([t.id,"/* Buttons styles start */\n\nbutton#excalibur-play {\n display: inline-block;\n position: relative;\n z-index: 999;\n border-radius: 6px;\n border: none;\n /*border: 3px solid;\n border-color: white;\n box-shadow: 0 0 10px #ccc;*/\n padding: 1rem 1.5rem 1rem 4rem;\n margin: 0;\n text-decoration: none;\n background: #00b233;\n color: #ffffff;\n font-family: sans-serif;\n font-size: 2rem;\n white-space: nowrap;\n line-height: 1;\n cursor: pointer;\n text-align: center;\n transition: background 250ms ease-in-out, transform 150ms ease;\n -webkit-appearance: none;\n -moz-appearance: none;\n\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\n animation: excalibur-button-fadein 200ms;\n}\n\n/*\nbutton#excalibur-play {\n display: none;\n}*/\n\nbutton#excalibur-play:after {\n position: absolute;\n content: '';\n border: 8px solid;\n border-color: transparent transparent transparent white;\n left: 35px;\n top: 24px;\n width: 0;\n height: 0;\n}\n\nbutton#excalibur-play:before {\n position: absolute;\n content: '';\n border: 3px solid;\n left: 19px;\n top: 14px;\n border-radius: 20px;\n width: 30px;\n height: 30px;\n}\n\nbutton#excalibur-play:hover,\nbutton#excalibur-play:focus {\n background: #00982c;\n}\n\nbutton#excalibur-play:focus {\n outline: 1px solid #fff;\n outline-offset: -4px;\n}\n\nbutton#excalibur-play:active {\n transform: scale(0.99);\n}\n\n@keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Firefox < 16 */\n@-moz-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Safari, Chrome and Opera > 12.1 */\n@-webkit-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Internet Explorer */\n@-ms-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Opera < 12.1 */\n@-o-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n","",{version:3,sources:["webpack://./Loader.css"],names:[],mappings:"AAAA,yBAAyB;;AAEzB;EACE,qBAAqB;EACrB,kBAAkB;EAClB,YAAY;EACZ,kBAAkB;EAClB,YAAY;EACZ;;+BAE6B;EAC7B,8BAA8B;EAC9B,SAAS;EACT,qBAAqB;EACrB,mBAAmB;EACnB,cAAc;EACd,uBAAuB;EACvB,eAAe;EACf,mBAAmB;EACnB,cAAc;EACd,eAAe;EACf,kBAAkB;EAClB,8DAA8D;EAC9D,wBAAwB;EACxB,qBAAqB;;EAErB,gDAAgD,EAAE,oCAAoC;EACtF,6CAA6C,EAAE,iBAAiB;EAChE,4CAA4C,EAAE,sBAAsB;EACpE,2CAA2C,EAAE,iBAAiB;EAC9D,wCAAwC;AAC1C;;AAEA;;;EAGE;;AAEF;EACE,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,uDAAuD;EACvD,UAAU;EACV,SAAS;EACT,QAAQ;EACR,SAAS;AACX;;AAEA;EACE,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,WAAW;EACX,YAAY;AACd;;AAEA;;EAEE,mBAAmB;AACrB;;AAEA;EACE,uBAAuB;EACvB,oBAAoB;AACtB;;AAEA;EACE,sBAAsB;AACxB;;AAEA;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,iBAAiB;AACjB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,oCAAoC;AACpC;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,sBAAsB;AACtB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF;;AAEA,iBAAiB;AACjB;EACE;IACE,UAAU;EACZ;EACA;IACE,UAAU;EACZ;AACF",sourcesContent:["/* Buttons styles start */\n\nbutton#excalibur-play {\n display: inline-block;\n position: relative;\n z-index: 999;\n border-radius: 6px;\n border: none;\n /*border: 3px solid;\n border-color: white;\n box-shadow: 0 0 10px #ccc;*/\n padding: 1rem 1.5rem 1rem 4rem;\n margin: 0;\n text-decoration: none;\n background: #00b233;\n color: #ffffff;\n font-family: sans-serif;\n font-size: 2rem;\n white-space: nowrap;\n line-height: 1;\n cursor: pointer;\n text-align: center;\n transition: background 250ms ease-in-out, transform 150ms ease;\n -webkit-appearance: none;\n -moz-appearance: none;\n\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\n animation: excalibur-button-fadein 200ms;\n}\n\n/*\nbutton#excalibur-play {\n display: none;\n}*/\n\nbutton#excalibur-play:after {\n position: absolute;\n content: '';\n border: 8px solid;\n border-color: transparent transparent transparent white;\n left: 35px;\n top: 24px;\n width: 0;\n height: 0;\n}\n\nbutton#excalibur-play:before {\n position: absolute;\n content: '';\n border: 3px solid;\n left: 19px;\n top: 14px;\n border-radius: 20px;\n width: 30px;\n height: 30px;\n}\n\nbutton#excalibur-play:hover,\nbutton#excalibur-play:focus {\n background: #00982c;\n}\n\nbutton#excalibur-play:focus {\n outline: 1px solid #fff;\n outline-offset: -4px;\n}\n\nbutton#excalibur-play:active {\n transform: scale(0.99);\n}\n\n@keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Firefox < 16 */\n@-moz-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Safari, Chrome and Opera > 12.1 */\n@-webkit-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Internet Explorer */\n@-ms-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Opera < 12.1 */\n@-o-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n"],sourceRoot:""}]);const a=o},2609:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var i="",s=void 0!==e[5];return e[4]&&(i+="@supports (".concat(e[4],") {")),e[2]&&(i+="@media ".concat(e[2]," {")),s&&(i+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),i+=t(e),s&&(i+="}"),e[2]&&(i+="}"),e[4]&&(i+="}"),i})).join("")},e.i=function(t,i,s,n,r){"string"==typeof t&&(t=[[null,t,void 0]]);var o={};if(s)for(var a=0;a<this.length;a++){var h=this[a][0];null!=h&&(o[h]=!0)}for(var l=0;l<t.length;l++){var c=[].concat(t[l]);s&&o[c[0]]||(void 0!==r&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=r),i&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=i):c[2]=i),n&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=n):c[4]="".concat(n)),e.push(c))}},e}},272:t=>{"use strict";t.exports=function(t){var e=t[1],i=t[3];if(!i)return e;if("function"==typeof btoa){var s=btoa(unescape(encodeURIComponent(JSON.stringify(i)))),n="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(s),r="/*# ".concat(n," */"),o=i.sources.map((function(t){return"/*# sourceURL=".concat(i.sourceRoot||"").concat(t," */")}));return[e].concat(o).concat([r]).join("\n")}return[e].join("\n")}}},e={};function i(s){var n=e[s];if(void 0!==n)return n.exports;var r=e[s]={id:s,exports:{}};return t[s](r,r.exports,i),r.exports}i.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return i.d(e,{a:e}),e},i.d=(t,e)=>{for(var s in e)i.o(e,s)&&!i.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var s={};return(()=>{"use strict";i.r(s),i.d(s,{ActionContext:()=>vs,ActionQueue:()=>ss,ActionsComponent:()=>xs,ActionsSystem:()=>xn,ActivateEvent:()=>ie,Actor:()=>Cs,AddedComponent:()=>Ni,AddedEntity:()=>Xs,Animation:()=>un,AnimationDirection:()=>ln,AnimationStrategy:()=>cn,ArcadeSolver:()=>rn,AudioContextFactory:()=>je,Axis:()=>Es,BaseAlign:()=>De,BinaryTreeNode:()=>Ir,Blink:()=>gs,BodyComponent:()=>Oi,BoundingBox:()=>B,BroadphaseStrategy:()=>oi,BrowserComponent:()=>Wn,BrowserEvents:()=>Vn,Camera:()=>Us,Canvas:()=>Ct,Cell:()=>Ds,Circle:()=>$i,CircleCollider:()=>Ri,Class:()=>Ke,Clock:()=>$n,ClosestLine:()=>Ei,ClosestLineJumpTable:()=>Ti,Collider:()=>Ai,ColliderComponent:()=>Li,CollisionContact:()=>Bi,CollisionEndEvent:()=>te,CollisionGroup:()=>mi,CollisionGroupManager:()=>ur,CollisionJumpTable:()=>Di,CollisionPostSolveEvent:()=>$t,CollisionPreSolveEvent:()=>Qt,CollisionResolutionStrategy:()=>ri,CollisionSolver:()=>nn,CollisionStartEvent:()=>Jt,CollisionSystem:()=>hn,CollisionType:()=>ni,Color:()=>T,ColorBlindCorrector:()=>Fn,ColorBlindFlags:()=>kn,ColorBlindness:()=>bn,Component:()=>di,CompositeCollider:()=>Si,Configurable:()=>xe,ConsoleAppender:()=>m,ContactConstraintPoint:()=>on,ContactEndEvent:()=>Yt,ContactStartEvent:()=>Zt,CoordPlane:()=>pi,CullingBox:()=>Ui,DeactivateEvent:()=>se,Debug:()=>In,DebugSystem:()=>yn,DebugText:()=>He,DegreeOfFreedom:()=>zi,Detector:()=>si,Die:()=>fs,Direction:()=>ke,DisplayMode:()=>Ve,DynamicTree:()=>xi,DynamicTreeCollisionProcessor:()=>Ci,EX_VERSION:()=>Nr,EaseTo:()=>ps,EasingFunctions:()=>is,EdgeCollider:()=>Fi,ElasticToActorStrategy:()=>Ls,EmitterType:()=>dn,Engine:()=>sr,EnterTriggerEvent:()=>oe,EnterViewPortEvent:()=>re,Entity:()=>Xi,EntityManager:()=>Zs,EventDispatcher:()=>he,EventTypes:()=>At,Events:()=>t,ExResponse:()=>_r,ExcaliburGraphicsContext2DCanvas:()=>Xn,ExcaliburGraphicsContextWebGL:()=>We,ExitTriggerEvent:()=>ae,ExitViewPortEvent:()=>ne,Experiments:()=>l,Fade:()=>_s,Flags:()=>p,Follow:()=>ws,Font:()=>hr,FontStyle:()=>Fe,FontUnit:()=>Be,FpsSampler:()=>Qn,FrameStats:()=>Ln,GameEvent:()=>St,GameStartEvent:()=>Rt,GameStopEvent:()=>Bt,GamepadAxisEvent:()=>Wt,GamepadButtonEvent:()=>Nt,GamepadConnectEvent:()=>Ut,GamepadDisconnectEvent:()=>Ht,Gif:()=>Er,GlobalCoordinates:()=>jn,Graphic:()=>yt,GraphicsComponent:()=>Yi,GraphicsGroup:()=>pn,GraphicsLayer:()=>Ki,GraphicsLayers:()=>Zi,GraphicsSystem:()=>fn,HiddenEvent:()=>jt,ImageSource:()=>Pe,InitializeEvent:()=>ee,Input:()=>o,Integrator:()=>ai,KillEvent:()=>Pt,Label:()=>dr,Legacy:()=>c,LegacyDrawing:()=>r,LimitCameraBoundsStrategy:()=>Os,Line:()=>Pi,Loader:()=>ei,LockCameraToActorAxisStrategy:()=>Is,LockCameraToActorStrategy:()=>ks,LogLevel:()=>d,Logger:()=>_,Matrix:()=>tt,MatrixLocations:()=>$,MediaEvent:()=>rr,Meet:()=>ys,MockedElement:()=>Lr,MotionComponent:()=>_i,MotionSystem:()=>sn,MoveBy:()=>os,MoveTo:()=>as,NativeSoundEvent:()=>or,NativeSoundProcessedEvent:()=>ar,Observable:()=>fi,Pair:()=>wi,ParseGif:()=>Mr,Particle:()=>_n,ParticleEmitter:()=>mn,Physics:()=>li,PhysicsStats:()=>zn,PointerComponent:()=>Ji,Polygon:()=>Dr,PolygonCollider:()=>ki,Pool:()=>ot,PostCollisionEvent:()=>Kt,PostDebugDrawEvent:()=>kt,PostDrawEvent:()=>Dt,PostFrameEvent:()=>Ot,PostKillEvent:()=>Tt,PostUpdateEvent:()=>Lt,PreCollisionEvent:()=>qt,PreDebugDrawEvent:()=>Ft,PreDrawEvent:()=>Mt,PreFrameEvent:()=>zt,PreKillEvent:()=>Et,PreUpdateEvent:()=>It,Projection:()=>yi,Promise:()=>Hr,PromiseState:()=>Or,Query:()=>Qs,QueryManager:()=>$s,RadiusAroundActorStrategy:()=>zs,Random:()=>D,Raster:()=>bt,Ray:()=>bi,RealisticSolver:()=>an,Rectangle:()=>Qi,RemovedComponent:()=>Vi,RemovedEntity:()=>qs,Repeat:()=>ns,RepeatForever:()=>rs,Resolution:()=>Ge,Resource:()=>le,RotateBy:()=>ls,RotateTo:()=>hs,RotationType:()=>ts,ScaleBy:()=>ds,ScaleTo:()=>cs,Scene:()=>Dn,Screen:()=>Xe,ScreenAppender:()=>f,ScreenElement:()=>As,ScrollPreventionMode:()=>er,Shape:()=>Ii,Side:()=>P,SortedList:()=>kr,Sound:()=>Pr,Sprite:()=>Se,SpriteFont:()=>Ue,SpriteSheet:()=>Oe,StandardClock:()=>Jn,StrategyContainer:()=>Fs,Stream:()=>Br,SubscribeEvent:()=>Vt,System:()=>Gs,SystemManager:()=>Js,SystemType:()=>Vs,TagComponent:()=>ui,TestClock:()=>tr,Text:()=>lr,TextAlign:()=>Me,TileMap:()=>Bs,Timer:()=>Ps,Traits:()=>a,TransformComponent:()=>gi,TreeNode:()=>vi,Trigger:()=>Ws,UnsubscribeEvent:()=>Gt,Util:()=>h,Vector:()=>A,VectorView:()=>ci,VisibleEvent:()=>Xt,WebAudio:()=>qe,WebAudioInstance:()=>Ar,World:()=>tn,canonicalizeAngle:()=>U,clamp:()=>L,createId:()=>g,hasGraphicsTick:()=>qi,hasOnInitialize:()=>fr,hasOnPostUpdate:()=>xr,hasOnPreUpdate:()=>yr,hasPostDraw:()=>Cr,hasPreDraw:()=>br,has_initialize:()=>mr,has_postupdate:()=>vr,has_preupdate:()=>wr,isAddedComponent:()=>Wi,isAddedSystemEntity:()=>js,isRemoveSystemEntity:()=>Ks,isRemovedComponent:()=>Gi,maxMessages:()=>w,obsolete:()=>b,randomInRange:()=>z,randomIntInRange:()=>O,range:()=>Y,resetObsoleteCounter:()=>v,toDegrees:()=>H,toRadians:()=>N,vec:()=>S});var t={};i.r(t),i.d(t,{ActivateEvent:()=>ie,CollisionEndEvent:()=>te,CollisionPostSolveEvent:()=>$t,CollisionPreSolveEvent:()=>Qt,CollisionStartEvent:()=>Jt,ContactEndEvent:()=>Yt,ContactStartEvent:()=>Zt,DeactivateEvent:()=>se,EnterTriggerEvent:()=>oe,EnterViewPortEvent:()=>re,EventTypes:()=>At,ExitTriggerEvent:()=>ae,ExitViewPortEvent:()=>ne,GameEvent:()=>St,GameStartEvent:()=>Rt,GameStopEvent:()=>Bt,GamepadAxisEvent:()=>Wt,GamepadButtonEvent:()=>Nt,GamepadConnectEvent:()=>Ut,GamepadDisconnectEvent:()=>Ht,HiddenEvent:()=>jt,InitializeEvent:()=>ee,KillEvent:()=>Pt,PostCollisionEvent:()=>Kt,PostDebugDrawEvent:()=>kt,PostDrawEvent:()=>Dt,PostFrameEvent:()=>Ot,PostKillEvent:()=>Tt,PostUpdateEvent:()=>Lt,PreCollisionEvent:()=>qt,PreDebugDrawEvent:()=>Ft,PreDrawEvent:()=>Mt,PreFrameEvent:()=>zt,PreKillEvent:()=>Et,PreUpdateEvent:()=>It,SubscribeEvent:()=>Vt,UnsubscribeEvent:()=>Gt,VisibleEvent:()=>Xt});var e={};i.r(e),i.d(e,{Colorize:()=>ge,Darken:()=>me,Desaturate:()=>we,Fill:()=>ye,Grayscale:()=>de,Invert:()=>ue,Lighten:()=>_e,Opacity:()=>pe,Saturate:()=>fe});var n={};i.r(n),i.d(n,{circle:()=>Je,line:()=>Ze,point:()=>Ye,roundRect:()=>$e,vector:()=>Qe});var r={};i.r(r),i.d(r,{Animation:()=>Re,CanvasDrawComponent:()=>ji,CanvasDrawingSystem:()=>wn,Effects:()=>e,Polygon:()=>gr,Sprite:()=>Ae,SpriteFont:()=>ze,SpriteSheet:()=>Le,Texture:()=>ve});var o={};i.r(o),i.d(o,{Axes:()=>Pn,Buttons:()=>Sn,Gamepad:()=>Nn,Gamepads:()=>Hn,KeyEvent:()=>On,Keyboard:()=>Un,Keys:()=>An,NativePointerButton:()=>Tn,PointerButton:()=>Rn,PointerComponent:()=>Ji,PointerEvent:()=>qn,PointerEventReceiver:()=>Yn,PointerScope:()=>Cn,PointerSystem:()=>vn,PointerType:()=>Bn,WheelDeltaMode:()=>En,WheelEvent:()=>Kn});var a={};i.r(a),i.d(a,{OffscreenCulling:()=>Hi});var h={};i.r(h),i.d(h,{Collection:()=>K,ConsoleAppender:()=>m,DrawUtil:()=>n,EasingFunctions:()=>is,LogLevel:()=>d,Logger:()=>_,Observable:()=>fi,ScreenAppender:()=>f,TwoPI:()=>F,addItemToArray:()=>V,base64Encode:()=>k,canonicalizeAngle:()=>U,clamp:()=>L,contains:()=>X,delay:()=>Q,fail:()=>Z,getOppositeSide:()=>j,getPosition:()=>W,getSideFromDirection:()=>q,nullish:()=>I,randomInRange:()=>z,randomIntInRange:()=>O,range:()=>Y,removeItemFromArray:()=>G,toDegrees:()=>H,toRadians:()=>N});var l,c,d;i(4662),i(8343);function u(){if("undefined"==typeof window&&(window={audioContext:function(){}}),"undefined"==typeof window||window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(t){window.setInterval(t,1e3/60)}),"undefined"==typeof window||window.cancelAnimationFrame||(window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(){}),"undefined"!=typeof window&&!window.AudioContext){if(window.webkitAudioContext){const t=window.webkitAudioContext.prototype.decodeAudioData;window.webkitAudioContext.prototype.decodeAudioData=function(e){return new Promise(((i,s)=>{t.call(this,e,i,s)}))}}window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext}"undefined"==typeof window||window.devicePixelRatio||(window.devicePixelRatio=window.devicePixelRatio||1)}!function(t){t.WebGL="use-webgl"}(l||(l={})),function(t){t.Canvas="use-canvas-context",t.LegacyDrawing="use-legacy-drawing"}(c||(c={}));class p{static freeze(){p._FROZEN=!0}static _reset(){p._FROZEN=!1,p._FLAGS={}}static useWebGL(){p.enable(l.WebGL)}static useCanvasGraphicsContext(){p.enable(c.Canvas)}static useLegacyDrawing(){p.enable(c.LegacyDrawing)}static enable(t){if(this._FROZEN)throw Error("Feature flags can only be enabled before Engine constructor time");p._FLAGS[t]=!0}static disable(t){if(this._FROZEN)throw Error("Feature flags can only be disabled before Engine constructor time");p._FLAGS[t]=!1}static isEnabled(t){return!!p._FLAGS[t]}static show(){return Object.keys(p._FLAGS)}}function g(t,e){return{type:t,value:e}}p._FROZEN=!1,p._FLAGS={},function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error",t[t.Fatal=4]="Fatal"}(d||(d={}));class _{constructor(){if(this._appenders=[],this.defaultLevel=d.Info,_._INSTANCE)throw new Error("Logger is a singleton");return _._INSTANCE=this,_._INSTANCE.addAppender(new m),_._INSTANCE}static getInstance(){return null==_._INSTANCE&&(_._INSTANCE=new _),_._INSTANCE}addAppender(t){this._appenders.push(t)}clearAppenders(){this._appenders.length=0}_log(t,e){null==t&&(t=this.defaultLevel);const i=this._appenders.length;for(let s=0;s<i;s++)t>=this.defaultLevel&&this._appenders[s].log(t,e)}debug(...t){this._log(d.Debug,t)}info(...t){this._log(d.Info,t)}warn(...t){this._log(d.Warn,t)}error(...t){this._log(d.Error,t)}fatal(...t){this._log(d.Fatal,t)}}_._INSTANCE=null;class m{log(t,e){if(!console&&!console.log&&console.warn&&console.error)return;const i=[];i.unshift.apply(i,e),i.unshift("["+d[t]+"] : "),t<d.Warn?console.log.apply?console.log.apply(console,i):console.log(i.join(" ")):t<d.Error?console.warn.apply?console.warn.apply(console,i):console.warn(i.join(" ")):console.error.apply?console.error.apply(console,i):console.error(i.join(" "))}}class f{constructor(t,e){this._messages=[],this._canvas=document.createElement("canvas"),this._canvas.width=t||window.innerWidth,this._canvas.height=e||window.innerHeight,this._canvas.style.position="absolute",this._ctx=this._canvas.getContext("2d"),document.body.appendChild(this._canvas)}log(t,e){const i=e.join(",");this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._messages.unshift("["+d[t]+"] : "+i);let s=10,n=1;for(let t=0;t<this._messages.length;t++)this._ctx.fillStyle="rgba(255,255,255,"+n.toFixed(2)+")",this._ctx.fillText(this._messages[t],200,s),s+=10,n=n>0?n-.05:0}}const w=5,y={},v=()=>{for(const t in y)y[t]=0},x=(t,e)=>{const i=p.isEnabled("suppress-obsolete-message");y[t]<w&&!i&&(_.getInstance().warn(t),console.trace&&e.showStackTrace&&console.trace()),y[t]++};function b(t){return t={message:"This feature will be removed in future versions of Excalibur.",alternateMethod:null,showStackTrace:!1,...t},function(e,i,s){if(s&&"function"!=typeof s.value&&"function"!=typeof s.get&&"function"!=typeof s.set)throw new SyntaxError("Only classes/functions/getters/setters can be marked as obsolete");const n=`${`${e.name||""}${e.name&&i?".":""}${i||""}`} is marked obsolete: ${t.message}`+(t.alternateMethod?` Use ${t.alternateMethod} instead`:"");y[n]||(y[n]=0);const r=s?{...s}:e;if(!s){class e extends r{constructor(...e){x(n,t),super(...e)}}return e}return s&&s.value?(r.value=function(){return x(n,t),s.value.apply(this,arguments)},r):(s&&s.get&&(r.get=function(){return x(n,t),s.get.apply(this,arguments)}),s&&s.set&&(r.set=function(){return x(n,t),s.set.apply(this,arguments)}),r)}}var C=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class A{constructor(t,e){this._x=0,this._y=0,this._x=t,this._y=e}static get Zero(){return new A(0,0)}static get One(){return new A(1,1)}static get Half(){return new A(.5,.5)}static get Up(){return new A(0,-1)}static get Down(){return new A(0,1)}static get Left(){return new A(-1,0)}static get Right(){return new A(1,0)}static fromAngle(t){return new A(Math.cos(t),Math.sin(t))}static isValid(t){return null!=t&&(!isNaN(t.x)&&!isNaN(t.y)&&(t.x!==1/0&&t.y!==1/0&&t.x!==-1/0&&t.y!==-1/0))}static distance(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}setTo(t,e){this.x=t,this.y=e}equals(t,e=.001){return Math.abs(this.x-t.x)<=e&&Math.abs(this.y-t.y)<=e}distance(t){return t||(t=A.Zero),Math.sqrt(Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2))}squareDistance(t){return t||(t=A.Zero),Math.pow(this.x-t.x,2)+Math.pow(this.y-t.y,2)}magnitude(){return this.distance()}get size(){return this.distance()}set size(t){const e=this.normalize().scale(t);this.setTo(e.x,e.y)}normalize(){const t=this.distance();return t>0?new A(this.x/t,this.y/t):new A(0,1)}average(t){return this.add(t).scale(.5)}scale(t){return t instanceof A?new A(this.x*t.x,this.y*t.y):new A(this.x*t,this.y*t)}add(t){return new A(this.x+t.x,this.y+t.y)}sub(t){return new A(this.x-t.x,this.y-t.y)}addEqual(t){return this.setTo(this.x+t.x,this.y+t.y),this}subEqual(t){return this.setTo(this.x-t.x,this.y-t.y),this}scaleEqual(t){return this.setTo(this.x*t,this.y*t),this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return t instanceof A?this.x*t.y-this.y*t.x:"number"==typeof t?new A(t*this.y,-t*this.x):void 0}static cross(t,e){return new A(-t*e.y,t*e.x)}perpendicular(){return new A(this.y,-this.x)}normal(){return this.perpendicular().normalize()}negate(){return this.scale(-1)}toAngle(){return Math.atan2(this.y,this.x)}rotate(t,e){e||(e=new A(0,0));const i=Math.sin(t),s=Math.cos(t),n=s*(this.x-e.x)-i*(this.y-e.y)+e.x,r=i*(this.x-e.x)+s*(this.y-e.y)+e.y;return new A(n,r)}clone(){return new A(this.x,this.y)}toString(t){return t?`(${this.x.toFixed(t)}, ${this.y.toFixed(t)})`:`(${this.x}, ${this.y})`}}function S(t,e){return new A(t,e)}C([b({message:"will be removed in favour of `.size` in version 0.25.0"})],A.prototype,"magnitude",null);var P,E=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class T{constructor(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=null!=s?s:1}static fromRGB(t,e,i,s){return new T(t,e,i,s)}static fromRGBString(t){let e=null;if(e=t.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i)){const t=parseInt(e[1],10),i=parseInt(e[2],10),s=parseInt(e[3],10);let n=1;return e[4]&&(n=parseFloat(e[4])),new T(t,i,s,n)}throw new Error("Invalid rgb/a string: "+t)}static fromHex(t){let e=null;if(e=t.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i)){const t=parseInt(e[1],16),i=parseInt(e[2],16),s=parseInt(e[3],16);let n=1;return e[4]&&(n=parseInt(e[4],16)/255),new T(t,i,s,n)}throw new Error("Invalid hex string: "+t)}static fromHSL(t,e,i,s=1){return new R(t,e,i,s).toRGBA()}lighten(t=.1){const e=R.fromRGBA(this.r,this.g,this.b,this.a);return e.l+=(1-e.l)*t,e.toRGBA()}darken(t=.1){const e=R.fromRGBA(this.r,this.g,this.b,this.a);return e.l-=e.l*t,e.toRGBA()}saturate(t=.1){const e=R.fromRGBA(this.r,this.g,this.b,this.a);return e.s+=e.s*t,e.toRGBA()}desaturate(t=.1){const e=R.fromRGBA(this.r,this.g,this.b,this.a);return e.s-=e.s*t,e.toRGBA()}multiply(t){const e=t.r/255*this.r/255*255,i=t.g/255*this.g/255*255,s=t.b/255*this.b/255*255,n=t.a*this.a;return new T(e,i,s,n)}mulitiply(t){return this.multiply(t)}screen(t){const e=t.invert(),i=t.invert();return e.multiply(i).invert()}invert(){return new T(255-this.r,255-this.g,255-this.b,1-this.a)}average(t){const e=(t.r+this.r)/2,i=(t.g+this.g)/2,s=(t.b+this.b)/2,n=(t.a+this.a)/2;return new T(e,i,s,n)}equal(t){return this.toString()===t.toString()}toString(t="rgb"){switch(t){case"rgb":return this.toRGBA();case"hsl":return this.toHSLA();case"hex":return this.toHex();default:throw new Error("Invalid Color format")}}_componentToHex(t){const e=t.toString(16);return 1===e.length?"0"+e:e}toHex(){return"#"+this._componentToHex(this.r)+this._componentToHex(this.g)+this._componentToHex(this.b)}toRGBA(){const t=String(this.r.toFixed(0))+", "+String(this.g.toFixed(0))+", "+String(this.b.toFixed(0));return void 0!==this.a||null!==this.a?"rgba("+t+", "+String(this.a)+")":"rgb("+t+")"}toHSLA(){return R.fromRGBA(this.r,this.g,this.b,this.a).toString()}fillStyle(){return this.toString()}clone(){return new T(this.r,this.g,this.b,this.a)}static get Black(){return T.fromHex("#000000")}static get White(){return T.fromHex("#FFFFFF")}static get Gray(){return T.fromHex("#808080")}static get LightGray(){return T.fromHex("#D3D3D3")}static get DarkGray(){return T.fromHex("#A9A9A9")}static get Yellow(){return T.fromHex("#FFFF00")}static get Orange(){return T.fromHex("#FFA500")}static get Red(){return T.fromHex("#FF0000")}static get Vermilion(){return T.fromHex("#FF5B31")}static get Vermillion(){return T.Vermilion}static get Rose(){return T.fromHex("#FF007F")}static get Magenta(){return T.fromHex("#FF00FF")}static get Violet(){return T.fromHex("#7F00FF")}static get Blue(){return T.fromHex("#0000FF")}static get Azure(){return T.fromHex("#007FFF")}static get Cyan(){return T.fromHex("#00FFFF")}static get Viridian(){return T.fromHex("#59978F")}static get Green(){return T.fromHex("#00FF00")}static get Chartreuse(){return T.fromHex("#7FFF00")}static get Transparent(){return T.fromHex("#FFFFFF00")}static get ExcaliburBlue(){return T.fromHex("#176BAA")}}E([b({message:"Alias for incorrect spelling used in older versions, use multiply instead, will be removed in v0.25.0"})],T.prototype,"mulitiply",null),E([b({message:"Alias for incorrect spelling used in older versions",alternateMethod:"Vermilion"})],T,"Vermillion",null);class R{constructor(t,e,i,s){this.h=t,this.s=e,this.l=i,this.a=s}static hue2rgb(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}static fromRGBA(t,e,i,s){t/=255,e/=255,i/=255;const n=Math.max(t,e,i),r=Math.min(t,e,i);let o,a;const h=(n+r)/2;if(n===r)o=a=0;else{const s=n-r;switch(a=h>.5?s/(2-n-r):s/(n+r),n){case t:o=(e-i)/s+(e<i?6:0);break;case e:o=(i-t)/s+2;break;case i:o=(t-e)/s+4}o/=6}return new R(o,a,h,s)}toRGBA(){let t,e,i;if(0===this.s)t=e=i=this.l;else{const s=this.l<.5?this.l*(1+this.s):this.l+this.s-this.l*this.s,n=2*this.l-s;t=R.hue2rgb(n,s,this.h+1/3),e=R.hue2rgb(n,s,this.h),i=R.hue2rgb(n,s,this.h-1/3)}return new T(255*t,255*e,255*i,this.a)}toString(){return`hsla(${this.h.toFixed(0)}, ${this.s.toFixed(0)}, ${this.l.toFixed(0)}, ${this.a.toFixed(0)})`}}!function(t){t.None="None",t.Top="Top",t.Bottom="Bottom",t.Left="Left",t.Right="Right"}(P||(P={})),function(t){t.getOpposite=function(e){return e===t.Top?t.Bottom:e===t.Bottom?t.Top:e===t.Left?t.Right:e===t.Right?t.Left:t.None},t.fromDirection=function(e){const i=[A.Left,A.Right,A.Up,A.Down],s=[t.Left,t.Right,t.Top,t.Bottom];let n=-Number.MAX_VALUE,r=-1;for(let t=0;t<i.length;t++)i[t].dot(e)>n&&(n=i[t].dot(e),r=t);return s[r]}}(P||(P={}));class B{constructor(t=0,e=0,i=0,s=0){"object"==typeof t?(this.left=t.left,this.top=t.top,this.right=t.right,this.bottom=t.bottom):"number"==typeof t&&(this.left=t,this.top=e,this.right=i,this.bottom=s)}static getSideFromIntersection(t){return t&&t?Math.abs(t.x)>Math.abs(t.y)?t.x<0?P.Right:P.Left:t.y<0?P.Bottom:P.Top:P.None}static fromPoints(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(let r=0;r<t.length;r++)t[r].x<e&&(e=t[r].x),t[r].x>s&&(s=t[r].x),t[r].y<i&&(i=t[r].y),t[r].y>n&&(n=t[r].y);return new B(e,i,s,n)}static fromDimension(t,e,i=A.Half,s=A.Zero){return new B(-t*i.x+s.x,-e*i.y+s.y,t-t*i.x+s.x,e-e*i.y+s.y)}get width(){return this.right-this.left}get height(){return this.bottom-this.top}hasZeroDimensions(){return 0===this.width||0===this.height}get center(){return new A((this.left+this.right)/2,(this.top+this.bottom)/2)}translate(t){return new B(this.left+t.x,this.top+t.y,this.right+t.x,this.bottom+t.y)}rotate(t,e=A.Zero){const i=this.getPoints().map((i=>i.rotate(t,e)));return B.fromPoints(i)}scale(t,e=A.Zero){const i=this.translate(e);return new B(i.left*t.x,i.top*t.y,i.right*t.x,i.bottom*t.y)}transform(t){const e=this.getPoints().map((e=>t.multv(e)));return B.fromPoints(e)}getPerimeter(){return 2*(this.width+this.height)}getPoints(){const t=[];return t.push(new A(this.left,this.top)),t.push(new A(this.right,this.top)),t.push(new A(this.right,this.bottom)),t.push(new A(this.left,this.bottom)),t}rayCast(t,e=1/0){let i=-1/0,s=1/0;const n=0===t.dir.x?Number.MAX_VALUE:1/t.dir.x,r=0===t.dir.y?Number.MAX_VALUE:1/t.dir.y,o=(this.left-t.pos.x)*n,a=(this.right-t.pos.x)*n;i=Math.min(o,a),s=Math.max(o,a);const h=(this.top-t.pos.y)*r,l=(this.bottom-t.pos.y)*r;return i=Math.max(i,Math.min(h,l)),s=Math.min(s,Math.max(h,l)),s>=Math.max(0,i)&&i<e}rayCastTime(t,e=1/0){let i=-1/0,s=1/0;const n=0===t.dir.x?Number.MAX_VALUE:1/t.dir.x,r=0===t.dir.y?Number.MAX_VALUE:1/t.dir.y,o=(this.left-t.pos.x)*n,a=(this.right-t.pos.x)*n;i=Math.min(o,a),s=Math.max(o,a);const h=(this.top-t.pos.y)*r,l=(this.bottom-t.pos.y)*r;return i=Math.max(i,Math.min(h,l)),s=Math.min(s,Math.max(h,l)),s>=Math.max(0,i)&&i<e?i:-1}contains(t){return t instanceof A?this.left<=t.x&&this.top<=t.y&&this.bottom>=t.y&&this.right>=t.x:t instanceof B&&(this.left<t.left&&this.top<t.top&&t.bottom<this.bottom&&t.right<this.right)}combine(t){return new B(Math.min(this.left,t.left),Math.min(this.top,t.top),Math.max(this.right,t.right),Math.max(this.bottom,t.bottom))}get dimensions(){return new A(this.width,this.height)}intersect(t){const e=this.combine(t);if(e.width<t.width+this.width&&e.height<t.height+this.height&&!e.dimensions.equals(t.dimensions)&&!e.dimensions.equals(this.dimensions)){let e=0;e=this.right>=t.left&&this.right<=t.right?t.left-this.right:t.right-this.left;let i=0;return i=this.top<=t.bottom&&this.top>=t.top?t.bottom-this.top:t.top-this.bottom,Math.abs(e)<Math.abs(i)?new A(e,0):new A(0,i)}if(e.dimensions.equals(t.dimensions)||e.dimensions.equals(this.dimensions)){let e=0;e=this.width-t.width>=0?this.right-t.right<=t.left-this.left?t.left-this.right:t.right-this.left:t.right-this.right<=this.left-t.left?this.left-t.right:this.right-t.left;let i=0;return i=this.height-t.height>=0?this.bottom-t.bottom<=t.top-this.top?t.top-this.bottom:t.bottom-this.top:t.bottom-this.bottom<=this.top-t.top?this.top-t.bottom:this.bottom-t.top,Math.abs(e)<Math.abs(i)?new A(e,0):new A(0,i)}return null}intersectWithSide(t){const e=this.intersect(t);return B.getSideFromIntersection(e)}debugDraw(t,e=T.Yellow){t.strokeStyle=e.toString(),t.strokeRect(this.left,this.top,this.width,this.height)}draw(t,e=T.Yellow){t.debug.drawRect(this.left,this.top,this.width,this.height,{color:e})}}const M=4294967295;class D{constructor(t){this.seed=t,this._lowerMask=2147483647,this._upperMask=2147483648,this._w=32,this._n=624,this._m=397,this._a=2567483615,this._u=11,this._s=7,this._b=2636928640,this._t=15,this._c=4022730752,this._l=18,this._f=1812433253,this._mt=new Array(this._n),this._mt[0]=(t||Date.now())>>>0;for(let t=1;t<this._n;t++){const e=this._mt[t-1]^this._mt[t-1]>>>this._w-2;this._mt[t]=(this._f*((4294901760&e)>>>16)<<16)+this._f*(65535&e)+t>>>0}this._index=this._n}_twist(){const t=[0,this._a];let e=0,i=0;for(;i<this._n-this._m;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+this._m]^e>>>1^t[1&e]&M;for(;i<this._n-1;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+(this._m-this._n)]^e>>>1^t[1&e]&M;e=this._mt[this._n-1]&this._upperMask|this._mt[0]&this._lowerMask,this._mt[this._n-1]=this._mt[this._m-1]^e>>>1^t[1&e]&M,this._index=0}nextInt(){this._index>=this._n&&this._twist();let t=this._mt[this._index++];return t^=t>>>this._u,t^=t<<this._s&this._b,t^=t<<this._t&this._c,t^=t>>>this._l,t>>>0}next(){return this.nextInt()*(1/4294967296)}floating(t,e){return(e-t)*this.next()+t}integer(t,e){return Math.floor((e-t+1)*this.next()+t)}bool(t=.5){return this.next()<=t}pickOne(t){return t[this.integer(0,t.length-1)]}pickSet(t,e,i=!1){return i?this._pickSetWithDuplicates(t,e):this._pickSetWithoutDuplicates(t,e)}_pickSetWithoutDuplicates(t,e){if(e>t.length||e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 < n <= length");if(e===t.length)return t;const i=new Array(e);let s=0;const n=t.slice(0);for(;s<e;){const t=this.integer(0,n.length-1);i[s++]=n[t],n.splice(t,1)}return i}_pickSetWithDuplicates(t,e){if(e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 <= n < MAX_INT");const i=new Array(e);for(let s=0;s<e;s++)i[s]=this.pickOne(t);return i}shuffle(t){const e=t.slice(0);let i=null;for(let t=0;t<e.length-2;t++){const s=this.integer(t,e.length-1);i=e[t],e[t]=e[s],e[s]=i}return e}range(t,e,i){const s=new Array(t);for(let n=0;n<t;n++)s[n]=this.integer(e,i);return s}d4(){return this.integer(1,4)}d6(){return this.integer(1,6)}d8(){return this.integer(1,8)}d10(){return this.integer(1,10)}d12(){return this.integer(1,12)}d20(){return this.integer(1,20)}}const F=2*Math.PI;function k(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i="",s=0;for(;s<t.length;){const n=255&t.charCodeAt(s++),r=255&t.charCodeAt(s++),o=255&t.charCodeAt(s++),a=n>>2,h=(3&n)<<4|r>>4;let l,c;isNaN(r)?l=c=64:(l=(15&r)<<2|o>>6,c=isNaN(o)?64:63&o),i+=e.charAt(a)+e.charAt(h)+e.charAt(l)+e.charAt(c)}return i}function I(t,e){return null!=t?t:e}function L(t,e,i){return Math.min(Math.max(e,t),i)}function z(t,e,i=new D){return i?i.floating(t,e):t+Math.random()*(e-t)}function O(t,e,i=new D){return i?i.integer(t,e):Math.round(z(t,e))}function U(t){let e=t;if(t>F)for(;e>F;)e-=F;if(t<0)for(;e<0;)e+=F;return e}function H(t){return 180/Math.PI*t}function N(t){return t/180*Math.PI}function W(t){let e=0,i=0;const s=t=>{e+=t.offsetLeft,t.offsetParent&&s(t.offsetParent)},n=t=>{i+=t.offsetTop,t.offsetParent&&n(t.offsetParent)};return s(t),n(t),new A(e,i)}function V(t,e){return-1===e.indexOf(t)&&(e.push(t),!0)}function G(t,e){let i=-1;return(i=e.indexOf(t))>-1&&(e.splice(i,1),!0)}function X(t,e){for(let i=0;i<t.length;i++)if(t[i]===e)return!0;return!1}function j(t){return t===P.Top?P.Bottom:t===P.Bottom?P.Top:t===P.Left?P.Right:t===P.Right?P.Left:P.None}function q(t){const e=[A.Left,A.Right,A.Up,A.Down],i=[P.Left,P.Right,P.Top,P.Bottom];let s=-Number.MAX_VALUE,n=-1;for(let i=0;i<e.length;i++)e[i].dot(t)>s&&(s=e[i].dot(t),n=i);return i[n]}class K{constructor(t=K.DefaultSize){this._internalArray=null,this._endPointer=0,this._internalArray=new Array(t)}_resize(){const t=2*this._internalArray.length,e=new Array(t),i=this.count();for(let t=0;t<i;t++)e[t]=this._internalArray[t];delete this._internalArray,this._internalArray=e}push(t){return this._endPointer===this._internalArray.length&&this._resize(),this._internalArray[this._endPointer++]=t}pop(){return this._endPointer=this._endPointer-1<0?0:this._endPointer-1,this._internalArray[this._endPointer]}count(){return this._endPointer}clear(){this._endPointer=0}internalSize(){return this._internalArray.length}elementAt(t){if(t>=this.count())throw new Error("Invalid index "+t);return this._internalArray[t]}insert(t,e){return t>=this.count()&&this._resize(),this._internalArray[t]=e}remove(t){const e=this.count();if(0===e)throw new Error("Invalid parameter "+t);const i=this._internalArray[t];for(let i=t;i<e;i++)this._internalArray[i]=this._internalArray[i+1];return this._endPointer--,i}removeElement(t){const e=this._internalArray.indexOf(t);this.remove(e)}toArray(){return this._internalArray.slice(0,this._endPointer)}forEach(t){let e=0;const i=this.count();for(;e<i;e++)t.call(this,this._internalArray[e],e)}map(t){const e=this.count();for(let i=0;i<e;i++)this._internalArray[i]=t.call(this,this._internalArray[i],i)}}function Z(t){throw new Error(t)}K.DefaultSize=200;const Y=(t,e)=>Array.from(new Array(e-t+1),((e,i)=>i+t));function Q(t,e){var i;const s=null!==(i=null==e?void 0:e.schedule.bind(e))&&void 0!==i?i:setTimeout;return new Promise((e=>{s((()=>{e()}),t)}))}var $;!function(t){t[t.X=12]="X",t[t.Y=13]="Y"}($||($={}));const J=t=>0===t?0:t<0?-1:1;class tt{constructor(){this.data=new Float32Array(16),this._scaleSignX=1,this._scaleSignY=1}static ortho(t,e,i,s,n,r){const o=new tt;return o.data[0]=2/(e-t),o.data[1]=0,o.data[2]=0,o.data[3]=0,o.data[4]=0,o.data[5]=2/(s-i),o.data[6]=0,o.data[7]=0,o.data[8]=0,o.data[9]=0,o.data[10]=-2/(r-n),o.data[11]=0,o.data[12]=-(e+t)/(e-t),o.data[13]=-(s+i)/(s-i),o.data[14]=-(r+n)/(r-n),o.data[15]=1,o}clone(){const t=new tt;return t.data[0]=this.data[0],t.data[1]=this.data[1],t.data[2]=this.data[2],t.data[3]=this.data[3],t.data[4]=this.data[4],t.data[5]=this.data[5],t.data[6]=this.data[6],t.data[7]=this.data[7],t.data[8]=this.data[8],t.data[9]=this.data[9],t.data[10]=this.data[10],t.data[11]=this.data[11],t.data[12]=this.data[12],t.data[13]=this.data[13],t.data[14]=this.data[14],t.data[15]=this.data[15],t}static identity(){const t=new tt;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}static translation(t,e){const i=tt.identity();return i.data[12]=t,i.data[13]=e,i}static scale(t,e){const i=tt.identity();return i.data[0]=t,i.data[5]=e,i.data[10]=1,i.data[15]=1,i}static rotation(t){const e=tt.identity();return e.data[0]=Math.cos(t),e.data[4]=-Math.sin(t),e.data[1]=Math.sin(t),e.data[5]=Math.cos(t),e}multv(t){if(t instanceof A)return new A(t.x*this.data[0]+t.y*this.data[4]+0*this.data[6]+1*this.data[12],t.x*this.data[1]+t.y*this.data[5]+0*this.data[9]+1*this.data[13]);return[t[0]*this.data[0]+t[1]*this.data[4]+0*this.data[6]+1*this.data[12],t[0]*this.data[1]+t[1]*this.data[5]+0*this.data[9]+1*this.data[13]]}multm(t){const e=new tt,i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=this.data[8],d=this.data[9],u=this.data[10],p=this.data[11],g=this.data[12],_=this.data[13],m=this.data[14],f=this.data[15],w=t.data[0],y=t.data[1],v=t.data[2],x=t.data[3],b=t.data[4],C=t.data[5],A=t.data[6],S=t.data[7],P=t.data[8],E=t.data[9],T=t.data[10],R=t.data[11],B=t.data[12],M=t.data[13],D=t.data[14],F=t.data[15];e.data[0]=i*w+o*y+c*v+g*x,e.data[1]=s*w+a*y+d*v+_*x,e.data[2]=n*w+h*y+u*v+m*x,e.data[3]=r*w+l*y+p*v+f*x,e.data[4]=i*b+o*C+c*A+g*S,e.data[5]=s*b+a*C+d*A+_*S,e.data[6]=n*b+h*C+u*A+m*S,e.data[7]=r*b+l*C+p*A+f*S,e.data[8]=i*P+o*E+c*T+g*R,e.data[9]=s*P+a*E+d*T+_*R,e.data[10]=n*P+h*E+u*T+m*R,e.data[11]=r*P+l*E+p*T+f*R,e.data[12]=i*B+o*M+c*D+g*F,e.data[13]=s*B+a*M+d*D+_*F,e.data[14]=n*B+h*M+u*D+m*F,e.data[15]=r*B+l*M+p*D+f*F;const k=this.getScale();return e._scaleSignX=J(k.x)*J(e._scaleSignX),e._scaleSignY=J(k.y)*J(e._scaleSignY),e}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=this.data[8],d=this.data[9],u=this.data[10],p=this.data[11],g=this.data[12],_=this.data[13],m=this.data[14],f=this.data[15];return this.data[12]=i*t+o*e+0*c+1*g,this.data[13]=s*t+a*e+0*d+1*_,this.data[14]=n*t+h*e+0*u+1*m,this.data[15]=r*t+l*e+0*p+1*f,this}setPosition(t,e){this.data[12]=t,this.data[13]=e}getPosition(){return S(this.data[12],this.data[13])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],r=this.data[4],o=this.data[5],a=this.data[6],h=this.data[7],l=Math.sin(t),c=Math.cos(t);return this.data[0]=c*e+l*r,this.data[1]=c*i+l*o,this.data[2]=c*s+l*a,this.data[3]=c*n+l*h,this.data[4]=c*r-l*e,this.data[5]=c*o-l*i,this.data[6]=c*a-l*s,this.data[7]=c*h-l*n,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],r=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*t,this.data[3]=r*t,this.data[4]=o*e,this.data[5]=a*e,this.data[6]=h*e,this.data[7]=l*e,this}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[4]=-i*e.x,this.data[5]=s*e.y}getRotation(){return U(Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX()))}getScaleX(){const t=S(this.data[0],this.data[4]).size;return this._scaleSignX*t}getScaleY(){const t=S(this.data[1],this.data[5]).size;return this._scaleSignY*t}getScale(){return S(this.getScaleX(),this.getScaleY())}setScaleX(t){this._scaleSignX=J(t);const e=S(this.data[0]*this._scaleSignX,this.data[4]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[4]=e.y*t}setScaleY(t){this._scaleSignY=J(t);const e=S(this.data[1]*this._scaleSignY,this.data[5]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[5]=e.y*t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}getBasisDeterminant(){return this.data[0]*this.data[5]-this.data[1]*this.data[4]}getAffineInverse(){const t=1/this.getBasisDeterminant(),e=this.data[0],i=this.data[4],s=this.data[1],n=this.data[5],r=tt.identity();r.data[0]=n*t,r.data[1]=-s*t,r.data[4]=-i*t,r.data[5]=e*t;const o=this.data[12],a=this.data[13];return r.data[12]=-(o*r.data[0]+a*r.data[4]),r.data[13]=-(o*r.data[1]+a*r.data[5]),r}isIdentity(){return 1===this.data[0]&&0===this.data[1]&&0===this.data[2]&&0===this.data[3]&&0===this.data[4]&&1===this.data[5]&&0===this.data[6]&&0===this.data[7]&&0===this.data[8]&&0===this.data[9]&&1===this.data[10]&&0===this.data[11]&&0===this.data[12]&&0===this.data[13]&&0===this.data[14]&&1===this.data[15]}toString(){return`\n[${this.data[0]} ${this.data[4]} ${this.data[8]} ${this.data[12]}]\n[${this.data[1]} ${this.data[5]} ${this.data[9]} ${this.data[13]}]\n[${this.data[2]} ${this.data[6]} ${this.data[10]} ${this.data[14]}]\n[${this.data[3]} ${this.data[7]} ${this.data[11]} ${this.data[15]}]\n`}}class et{constructor(){this._transforms=[],this._currentTransform=tt.identity()}save(){this._transforms.push(this._currentTransform),this._currentTransform=this._currentTransform.clone()}restore(){this._currentTransform=this._transforms.pop()}translate(t,e){return this._currentTransform.translate(t,e)}rotate(t){return this._currentTransform.rotate(t)}scale(t,e){return this._currentTransform.scale(t,e)}set current(t){this._currentTransform=t}get current(){return this._currentTransform}}class it{constructor(){this._states=[],this._currentState=this._getDefaultState()}_getDefaultState(){return{opacity:1}}_cloneState(){return{opacity:this._currentState.opacity}}save(){this._states.push(this._currentState),this._currentState=this._cloneState()}restore(){this._currentState=this._states.pop()}get current(){return this._currentState}}class st{constructor(t,e,i){this._gl=t,this._vertexSource=e,this._fragmentSource=i,this.program=null,this.uniforms={},this.attributes={},this.layout=[],this.compile(t)}_createProgram(t,e,i){const s=t.createProgram();if(null===s)throw Error("Could not create graphics shader program");t.attachShader(s,e),t.attachShader(s,i),t.linkProgram(s);if(!t.getProgramParameter(s,t.LINK_STATUS))throw Error(`Could not link the program: [${t.getProgramInfoLog(s)}]`);return s}_compileShader(t,e,i){const s=t.createShader(i);if(null===s)throw Error(`Could not build shader: [${e}]`);t.shaderSource(s,e),t.compileShader(s);if(!t.getShaderParameter(s,t.COMPILE_STATUS))throw Error(`Could not compile shader [${t.getShaderInfoLog(s)}]`);return s}compile(t){const e=this._compileShader(t,this._vertexSource,t.VERTEX_SHADER),i=this._compileShader(t,this._fragmentSource,t.FRAGMENT_SHADER),s=this._createProgram(t,e,i);return this.program=s}addUniformMatrix(t,e){if(!e)throw Error(`Shader Uniform Matrix '${t}' was set to null or undefined`);const i=this._gl;this.uniforms[t]={name:t,type:"matrix",location:i.getUniformLocation(this.program,t),data:e}}addUniformIntegerArray(t,e){if(!e)throw Error(`Shader Uniform Integery Array '${t}' was set to null or undefined`);const i=this._gl;this.uniforms[t]={name:t,type:"numbers",location:i.getUniformLocation(this.program,t),data:e}}addAttribute(t,e,i,s=!1){const n=this._gl.getAttribLocation(this.program,t);this.attributes[t]={name:t,size:e,glType:i,normalized:s,location:n},this.layout.push(this.attributes[t])}get vertexAttributeSize(){let t=0;for(const e of this.layout)t+=e.size;return t}get totalVertexSizeBytes(){let t=0;for(const e of this.layout){let i=1;if(e.glType===this._gl.FLOAT)i=4;else i=1;t+=i*e.size}return t}getAttributeSize(t){let e=1;if(this.attributes[t].glType===this._gl.FLOAT)e=4;else e=1;return e*this.attributes[t].size}use(){const t=this._gl;t.useProgram(this.program);let e=0;for(const i of this.layout)t.vertexAttribPointer(i.location,i.size,i.glType,i.normalized,this.totalVertexSizeBytes,e),t.enableVertexAttribArray(i.location),e+=this.getAttributeSize(i.name);for(const e in this.uniforms){const i=this.uniforms[e];switch(i.type){case"matrix":t.uniformMatrix4fv(i.location,!1,i.data);break;case"numbers":t.uniform1iv(i.location,i.data)}}}}class nt{constructor(t){this.max=t,this._pool=void 0,this.commands=[]}isFull(){return this.commands.length>=this.max}canAdd(){return!this.isFull()}add(t){this.commands.push(t)}dispose(){return this.commands.length=0,this}}class rt{static clear(){rt.DrawCallCount=0,rt.DrawnImagesCount=0}}rt.DrawCallCount=0,rt.DrawnImagesCount=0;class ot{constructor(t,e,i=100){this.builder=t,this.recycler=e,this.maxObjects=i,this.totalAllocations=0,this.index=0,this.objects=[],this._logger=_.getInstance()}using(t){const e=t(this);return e?this.done(...e):this.done()}borrow(t){t(this.get()),this.index--}get(...t){if(this.index===this.maxObjects&&(this._logger.warn("Max pooled objects reached, possible memory leak? Doubling"),this.maxObjects=2*this.maxObjects),this.objects[this.index])return this.recycler(this.objects[this.index++],...t);{this.totalAllocations++;const e=this.objects[this.index++]=this.builder(...t);return e._pool=this,e}}done(...t){this.index=0;for(const e of t){const t=this.objects.indexOf(e);this.objects[t]=this.builder(),this.objects[t]._pool=this,this.totalAllocations++,e._pool=void 0}return t}}class at{constructor(t){var e,i,s;this.priority=0,this._buffer=null,this._maxCommandsPerBatch=2e3,this._batches=[],this._gl=t.gl;const n=t.command;this._verticesPerCommand=null!==(e=null==t?void 0:t.verticesPerCommand)&&void 0!==e?e:1,this._maxCommandsPerBatch=null!==(i=null==t?void 0:t.maxCommandsPerBatch)&&void 0!==i?i:this._maxCommandsPerBatch;const r=null!==(s=null==t?void 0:t.batchFactory)&&void 0!==s?s:()=>new nt(this._maxCommandsPerBatch);this.commands=new ot((()=>new n),(t=>t.dispose()),this._maxCommandsPerBatch),this._batchPool=new ot(r,(t=>t.dispose()),100)}init(){const t=this._gl;this.shader=this.buildShader(t),this._vertices=new Float32Array(this.shader.vertexAttributeSize*this._verticesPerCommand*this._maxCommandsPerBatch),this._buffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._buffer),t.bufferData(t.ARRAY_BUFFER,this._vertices,t.DYNAMIC_DRAW)}get vertexSize(){return this.shader.vertexAttributeSize}addCommand(t){0===this._batches.length&&this._batches.push(this._batchPool.get());const e=this._batches[this._batches.length-1];if(e.canAdd())e.add(t);else{const e=this._batchPool.get();e.add(t),this._batches.push(e)}}render(){const t=this._gl;t.bindBuffer(t.ARRAY_BUFFER,this._buffer),this.shader.use();let e=0,i=0;for(const s of this._batches){const n=this.buildBatchVertices(this._vertices,s);t.bufferSubData(t.ARRAY_BUFFER,0,this._vertices),this.renderBatch(t,s,n),i+=s.commands.length,e++}this.commands.done(),this._batchPool.done(),this._batches.length=0,rt.DrawCallCount+=e,rt.DrawnImagesCount+=i}}class ht{constructor(){this.color=T.Black,this.start=A.Zero,this.end=A.Zero}dispose(){return this.color.r=0,this.color.g=0,this.color.b=0,this.color.a=1,this.start.setTo(0,0),this.end.setTo(0,0),this}}class lt extends at{constructor(t,e){super({gl:t,command:ht,verticesPerCommand:2}),this._contextInfo=e,this.init()}buildShader(t){const e=new st(t,"attribute vec4 a_position;\nattribute vec4 a_color;\n\nvarying lowp vec4 v_color;\n\nuniform mat4 u_matrix;\n\n\nvoid main() {\n // Set the vertex position using the ortho transform matrix\n gl_Position = u_matrix * a_position;\n\n // Passthrough the color\n v_color = a_color;\n}","precision mediump float;\n\n// Color\nvarying lowp vec4 v_color;\n\n\nvoid main() {\n gl_FragColor = v_color;\n}");return e.addAttribute("a_position",2,t.FLOAT),e.addAttribute("a_color",4,t.FLOAT),e.addUniformMatrix("u_matrix",this._contextInfo.matrix.data),e}addLine(t,e,i){const s=this.commands.get();s.start=this._contextInfo.transform.current.multv(t),s.end=this._contextInfo.transform.current.multv(e),s.color.r=i.r,s.color.g=i.g,s.color.b=i.b,s.color.a=s.color.a*this._contextInfo.state.current.opacity,this.addCommand(s)}buildBatchVertices(t,e){let i=0;for(const s of e.commands)t[i++]=s.start.x,t[i++]=s.start.y,t[i++]=s.color.r/255,t[i++]=s.color.g/255,t[i++]=s.color.b/255,t[i++]=s.color.a,t[i++]=s.end.x,t[i++]=s.end.y,t[i++]=s.color.r/255,t[i++]=s.color.g/255,t[i++]=s.color.b/255,t[i++]=s.color.a;return i/this.vertexSize}renderBatch(t,e,i){t.drawArrays(t.LINES,0,i)}}var ct;!function(t){t.Image="image",t.Line="line",t.Rectangle="rectangle",t.Circle="circle"}(ct||(ct={}));class dt{constructor(t,e,i,s,n,r,o,a,h){this._pool=void 0,this.snapToPixel=!0,this.type=ct.Image,this.opacity=1,this.width=0,this.height=0,this.dest=[0,0],this.view=[0,0,0,0],this._geom=[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],this.init(t,e,i,s,n,r,o,a,h)}init(t,e,i,s,n,r,o,a,h){this.type=ct.Image,this.image=t,this.width=(null==t?void 0:t.width)||s||0,this.height=(null==t?void 0:t.height)||n||0,this.view=[0,0,null!=s?s:null==t?void 0:t.width,null!=n?n:null==t?void 0:t.height],this.dest=[e,i],void 0!==r&&void 0!==o&&void 0!==a&&void 0!==h&&(this.view=[e,i,null!=s?s:null==t?void 0:t.width,null!=n?n:null==t?void 0:t.height],this.dest=[r,o],this.width=a,this.height=h);let l=0;if(this._geom[l++]=[this.dest[0],this.dest[1]],this._geom[l++]=[this.dest[0],this.dest[1]+this.height],this._geom[l++]=[this.dest[0]+this.width,this.dest[1]],this._geom[l++]=[this.dest[0]+this.width,this.dest[1]],this._geom[l++]=[this.dest[0],this.dest[1]+this.height],this._geom[l++]=[this.dest[0]+this.width,this.dest[1]+this.height],this.snapToPixel)for(const t of this._geom)t[0]=~~t[0],t[1]=~~t[1];return this}initRect(t,e,i,s){this.type=ct.Rectangle,this.color=t,this.width=i,this.height=s;let n=0;if(this._geom[n++]=[e.x,e.y],this._geom[n++]=[e.x,e.y+this.height],this._geom[n++]=[e.x+this.width,e.y],this._geom[n++]=[e.x+this.width,e.y],this._geom[n++]=[e.x,e.y+this.height],this._geom[n++]=[e.x+this.width,e.y+this.height],this.snapToPixel)for(const t of this._geom)t[0]=~~t[0],t[1]=~~t[1];return this}initLine(t,e,i,s){this.type=ct.Line,this.color=t;const n=i.sub(e).normalize().perpendicular(),r=s/2,o=n.scale(r).add(e),a=n.scale(-r).add(e),h=n.scale(r).add(i),l=n.scale(-r).add(i);let c=0;if(this._geom[c++]=[o.x,o.y],this._geom[c++]=[h.x,h.y],this._geom[c++]=[a.x,a.y],this._geom[c++]=[a.x,a.y],this._geom[c++]=[h.x,h.y],this._geom[c++]=[l.x,l.y],this.snapToPixel)for(const t of this._geom)t[0]=~~t[0],t[1]=~~t[1];return this}initCircle(t,e,i){this.type=ct.Circle,this.color=i;const s=t.add(S(-e,-e)),n=t.add(S(e,-e)),r=t.add(S(e,e)),o=t.add(S(-e,e));let a=0;if(this._geom[a++]=[s.x,s.y],this._geom[a++]=[n.x,n.y],this._geom[a++]=[o.x,o.y],this._geom[a++]=[o.x,o.y],this._geom[a++]=[n.x,n.y],this._geom[a++]=[r.x,r.y],this.snapToPixel)for(const t of this._geom)t[0]=~~t[0],t[1]=~~t[1];return this}dispose(){this.image=null,this.width=0,this.height=0,this.view=[0,0,0,0],this.dest=[0,0];let t=0;return this._geom[t++]=[this.dest[0],this.dest[1]],this._geom[t++]=[this.dest[0],this.dest[1]+this.height],this._geom[t++]=[this.dest[0]+this.width,this.dest[1]],this._geom[t++]=[this.dest[0]+this.width,this.dest[1]],this._geom[t++]=[this.dest[0],this.dest[1]+this.height],this._geom[t++]=[this.dest[0]+this.width,this.dest[1]+this.height],this}applyTransform(t,e){if(t)for(let e=0;e<this._geom.length;e++)this._geom[e]=t.multv(this._geom[e]),this.snapToPixel&&(this._geom[e]=[~~this._geom[e][0],~~this._geom[e][1]]);this.opacity=e}get geometry(){return this._geom}}function ut(t){return 0==(t&t-1)}function pt(t){return ut(t)?t:function(t){--t;for(let e=1;e<32;e<<=1)t|=t>>e;return t+1}(t)}class gt{static registerContext(t){gt._GL=t}static get(t){return gt._TEXTURE_MAP.get(t)}static has(t){return gt._TEXTURE_MAP.has(t)}static load(t,e=!1){const i=gt._GL;if(!i)return null;let s=null;if(gt.has(t)&&(s=gt.get(t)),s){if(e){i.bindTexture(i.TEXTURE_2D,s);const e=gt.toPowerOfTwoImage(t);i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,e)}return s}s=i.createTexture();const n=gt.toPowerOfTwoImage(t);return i.bindTexture(i.TEXTURE_2D,s),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,n),gt._TEXTURE_MAP.set(t,s),s}static toPowerOfTwoImage(t){const e=gt._POT_CANVAS,i=gt._POT_CTX;return ut(t.width)&&ut(t.height)||(e.width=pt(t.width),e.height=pt(t.height),i.imageSmoothingEnabled=!1,i.clearRect(0,0,e.width,e.height),i.drawImage(t,0,0,t.width,t.height),t=e),t}}gt._POT_CANVAS=document.createElement("canvas"),gt._POT_CTX=gt._POT_CANVAS.getContext("2d"),gt._TEXTURE_MAP=new Map;class _t extends nt{constructor(t,e){super(t),this.maxDraws=t,this.maxTextures=e,this.textures=[],this.commands=[],this._graphicMap={}}isFull(){return this.commands.length>=this.maxDraws||this.textures.length>=this.maxTextures}canAdd(){return!(this.commands.length>=this.maxDraws)&&this.textures.length<this.maxTextures}_isCommandFull(){return this.commands.length>=this.maxDraws}_isTextureFull(){return this.textures.length>=this.maxTextures}_wouldAddTexture(t){return!this._graphicMap[t.image.id]}maybeAdd(t){return(!this._isCommandFull()&&!this._isTextureFull()||!this._wouldAddTexture(t))&&(this.add(t),!0)}add(t){if(t.type===ct.Image){const e=gt.load(t.image);-1===this.textures.indexOf(e)&&this.textures.push(e)}this.commands.push(t)}bindTextures(t){for(let e=0;e<this.maxTextures;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this.textures[e]||this.textures[0])}getBatchTextureId(t){return t.image?this.textures.indexOf(gt.get(t.image)):-1}dispose(){return this.clear(),this}clear(){this.commands.length=0,this.textures.length=0,this._graphicMap={}}}class mt extends at{constructor(t,e){super({gl:t,command:dt,verticesPerCommand:6,maxCommandsPerBatch:2e3,batchFactory:()=>new _t(2e3,t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS))}),this._contextInfo=e,gt.registerContext(t),this.init()}buildShader(t){const e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),i=new st(t,"attribute vec4 a_position;\n\n// Opacity \nattribute float a_opacity;\nvarying float v_opacity;\n\nattribute vec4 a_color;\nvarying vec4 v_color;\n\n// UV coordinate\nattribute vec2 a_texcoord;\nvarying vec2 v_texcoord;\n\n// Texture number\nattribute lowp float a_textureIndex;\nvarying lowp float v_textureIndex;\n\nuniform mat4 u_matrix;\n\n\nvoid main() {\n // Set the vertex position using the ortho transform matrix\n gl_Position = u_matrix * a_position;\n\n // Pass through the Opacity to the fragment shader\n v_opacity = a_opacity;\n // Pass through the UV coord to the fragment shader\n v_texcoord = a_texcoord;\n // Pass through the texture number to the fragment shader\n v_textureIndex = a_textureIndex;\n // Pass through the color to the fragment shader\n v_color = a_color;\n}",this._transformFragmentSource("#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision mediump float;\n\n// UV coord\nvarying vec2 v_texcoord;\n\n// Texture index\nvarying lowp float v_textureIndex;\n\n// Color coord to blend with image\nvarying lowp vec4 v_color;\n\n// Opacity\nvarying float v_opacity;\n\nuniform sampler2D u_textures[%%count%%];\n\nfloat circle(in vec2 st, in float radius) {\n vec2 dist = st - vec2(0.5);\n float r = dot(dist, dist) * 4.0;\n float delta = fwidth(r);\n return 1.0 - smoothstep(radius - delta, radius + delta, r);\n}\n\nvoid main() {\n float r = 0.0, delta = 0.0, alpha = 1.0;\n // In order to support the most efficient sprite batching, we have multiple\n // textures loaded into the gpu (usually 8) this picker logic skips over textures\n // that do not apply to a particular sprite.\n\n vec4 color;\n // -1 If there is no texture to sample we are drawing a solid geometry (rectangles)\n if (v_textureIndex == -1.0) {\n color = v_color;\n color.w = color.w * v_opacity;\n // -2 If there is no texture we are drawing a circle\n } else if (v_textureIndex == -2.0) {\n color = v_color;\n color.a = color.a * circle(v_texcoord, .95);\n } else {\n // GLSL is templated out to pick the right texture and set the vec4 color\n %%texture_picker%%\n }\n color.w = color.w * v_opacity;\n gl_FragColor = color;\n}",e));return i.addAttribute("a_position",3,t.FLOAT),i.addAttribute("a_texcoord",2,t.FLOAT),i.addAttribute("a_textureIndex",1,t.FLOAT),i.addAttribute("a_opacity",1,t.FLOAT),i.addAttribute("a_color",4,t.FLOAT),i.addUniformMatrix("u_matrix",this._contextInfo.matrix.data),i.addUniformIntegerArray("u_textures",[...Array(e)].map(((t,e)=>e))),i}_transformFragmentSource(t,e){let i=t.replace("%%count%%",e.toString()),s="";for(let t=0;t<e;t++)s+=0===t?`if (v_textureIndex <= ${t}.5) {\n`:` else if (v_textureIndex <= ${t}.5) {\n`,s+=` color = texture2D(u_textures[${t}], v_texcoord);\n`,s+=" }\n";return i=i.replace("%%texture_picker%%",s),i}addCircle(t,e,i){const s=this.commands.get().initCircle(t,e,i);s.applyTransform(this._contextInfo.transform.current,this._contextInfo.state.current.opacity),this.addCommand(s)}addRectangle(t,e,i,s){const n=this.commands.get().initRect(t,e,i,s);n.applyTransform(this._contextInfo.transform.current,this._contextInfo.state.current.opacity),this.addCommand(n)}addLine(t,e,i,s=1){const n=this.commands.get().initLine(t,e,i,s);n.applyTransform(this._contextInfo.transform.current,this._contextInfo.state.current.opacity),this.addCommand(n)}addImage(t,e,i,s,n,r,o,a,h){const l=this.commands.get().init(t,e,i,s,n,r,o,a,h);l.applyTransform(this._contextInfo.transform.current,this._contextInfo.state.current.opacity),this.addCommand(l)}renderBatch(t,e,i){e.bindTextures(t),t.drawArrays(t.TRIANGLES,0,i)}buildBatchVertices(t,e){var i,s;let n=0,r=0,o=0,a=0,h=0,l=1,c=1,d=0,u=T.Transparent;for(const p of e.commands){r=p.view[0],o=p.view[1],a=p.view[2],h=p.view[3],l=pt((null===(i=p.image)||void 0===i?void 0:i.width)||p.width),c=pt((null===(s=p.image)||void 0===s?void 0:s.height)||p.height),d=e.getBatchTextureId(p),p.type!==ct.Line&&p.type!==ct.Rectangle||(d=-1,u=p.color),p.type===ct.Circle&&(d=-2,u=p.color);let g=r/l,_=o/c,m=(r+a)/l,f=(o+h)/c;-2===d&&(g=0,_=0,m=1,f=1),t[n++]=p.geometry[0][0],t[n++]=p.geometry[0][1],t[n++]=0,t[n++]=g,t[n++]=_,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[1][0],t[n++]=p.geometry[1][1],t[n++]=0,t[n++]=g,t[n++]=f,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[2][0],t[n++]=p.geometry[2][1],t[n++]=0,t[n++]=m,t[n++]=_,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[3][0],t[n++]=p.geometry[3][1],t[n++]=0,t[n++]=m,t[n++]=_,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[4][0],t[n++]=p.geometry[4][1],t[n++]=0,t[n++]=g,t[n++]=f,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a,t[n++]=p.geometry[5][0],t[n++]=p.geometry[5][1],t[n++]=0,t[n++]=m,t[n++]=f,t[n++]=d,t[n++]=p.opacity,t[n++]=u.r/255,t[n++]=u.g/255,t[n++]=u.b/255,t[n++]=u.a}return n/this.vertexSize}}class ft{constructor(){this.point=A.Zero,this.color=T.Black,this.size=1}dispose(){return this.point.setTo(0,0),this.color.r=0,this.color.g=0,this.color.b=0,this.color.a=1,this.size=1,this}}class wt extends at{constructor(t,e){super({gl:t,command:ft,verticesPerCommand:1}),this._contextInfo=e,this.init()}buildShader(t){t.getExtension("OES_standard_derivatives");const e=new st(t,"attribute vec4 a_position;\nattribute vec4 a_color;\nattribute float a_size;\nvarying lowp vec4 v_color;\nuniform mat4 u_matrix;\n\nvoid main() {\n gl_Position = u_matrix * a_position;\n gl_PointSize = a_size * 2.0;\n v_color = a_color;\n}","#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n\nprecision mediump float;\nvarying lowp vec4 v_color;\n\nvoid main() {\n float r = 0.0, delta = 0.0, alpha = 1.0;\n vec2 cxy = 2.0 * gl_PointCoord - 1.0;\n r = dot(cxy, cxy);\n \n#ifdef GL_OES_standard_derivatives\n delta = fwidth(r);\n alpha = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r);\n#else\n if (r > 1.0) {\n discard;\n }\n#endif\n gl_FragColor = vec4(v_color.rgb, v_color.a * alpha);\n}");return e.addAttribute("a_position",2,t.FLOAT),e.addAttribute("a_color",4,t.FLOAT),e.addAttribute("a_size",1,t.FLOAT),e.addUniformMatrix("u_matrix",this._contextInfo.matrix.data),e}addPoint(t,e,i){const s=this.commands.get();s.point=this._contextInfo.transform.current.multv(t),s.color.r=e.r,s.color.g=e.g,s.color.b=e.b,s.color.a=e.a*this._contextInfo.state.current.opacity,s.size=i*Math.max(this._contextInfo.transform.current.getScaleX(),this._contextInfo.transform.current.getScaleY()),this.addCommand(s)}buildBatchVertices(t,e){let i=0;for(const s of e.commands)t[i++]=s.point.x,t[i++]=s.point.y,t[i++]=s.color.r/255,t[i++]=s.color.g/255,t[i++]=s.color.b/255,t[i++]=s.color.a,t[i++]=s.size;return i/this.vertexSize}renderBatch(t,e,i){t.drawArrays(t.POINTS,0,i)}}class yt{constructor(t){var e,i,s,n,r,o;this.id=yt._ID++,this.showDebug=!1,this.flipHorizontal=!1,this.flipVertical=!1,this.rotation=0,this.opacity=1,this.scale=A.One,this.origin=null,this._width=0,this._height=0,t&&(this.origin=null!==(e=t.origin)&&void 0!==e?e:this.origin,this.flipHorizontal=null!==(i=t.flipHorizontal)&&void 0!==i?i:this.flipHorizontal,this.flipVertical=null!==(s=t.flipVertical)&&void 0!==s?s:this.flipVertical,this.rotation=null!==(n=t.rotation)&&void 0!==n?n:this.rotation,this.opacity=null!==(r=t.opacity)&&void 0!==r?r:this.opacity,this.scale=null!==(o=t.scale)&&void 0!==o?o:this.scale)}cloneGraphicOptions(){return{origin:this.origin?this.origin.clone():null,flipHorizontal:this.flipHorizontal,flipVertical:this.flipVertical,rotation:this.rotation,opacity:this.opacity,scale:this.scale?this.scale.clone():null}}get width(){return Math.abs(this._width*this.scale.x)}get height(){return Math.abs(this._height*this.scale.y)}set width(t){this._width=t}set height(t){this._height=t}get localBounds(){return B.fromDimension(this.width,this.height,A.Zero)}draw(t,e,i){this._preDraw(t,e,i),this._drawImage(t,0,0),this._postDraw(t)}_preDraw(t,e,i){t.save(),t.translate(e,i),t.scale(Math.abs(this.scale.x),Math.abs(this.scale.y)),this._rotate(t),this._flip(t),t.opacity=t.opacity*this.opacity}_rotate(t){var e;const i=this.scale.x>0?1:-1,s=this.scale.y>0?1:-1,n=null!==(e=this.origin)&&void 0!==e?e:S(this.width/2,this.height/2);t.translate(n.x,n.y),t.rotate(this.rotation),t.scale(i,s),t.translate(-n.x,-n.y)}_flip(t){this.flipHorizontal&&(t.translate(this.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,this.height/this.scale.y),t.scale(1,-1))}_postDraw(t){this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}}function vt(t,e){return t&&void 0===t.__isProxy?new Proxy(t,{set:(t,i,s)=>(t[i]!==s&&(t[i]=s,"string"==typeof i&&"_"!==i[0]&&e(t)),!0),get:(t,e)=>"__isProxy"===e||t[e]}):t}function xt(t,e){return t&&void 0===t.__isProxy?new Proxy(t,{set:(t,i,s)=>(t[i]=s,"string"==typeof i&&"_"!==i[0]&&e(t),!0),get:(t,e)=>"__isProxy"===e||t[e]}):t}yt._ID=0;class bt extends yt{constructor(t){var e,i,s,n,r,o,a;super(t),this._dirty=!0,this._smoothing=!1,this._color=vt(T.Black,(()=>this.flagDirty())),this._lineWidth=1,this._lineDash=[],this._padding=0,t&&(this.color=null!==(e=t.color)&&void 0!==e?e:T.Black,this.strokeColor=null==t?void 0:t.strokeColor,this.smoothing=null!==(i=t.smoothing)&&void 0!==i?i:this.smoothing,this.lineWidth=null!==(s=t.lineWidth)&&void 0!==s?s:this.lineWidth,this.lineDash=null!==(n=t.lineDash)&&void 0!==n?n:this.lineDash,this.padding=null!==(r=t.padding)&&void 0!==r?r:this.padding),this._bitmap=document.createElement("canvas");const h=null!==(o=null==t?void 0:t.width)&&void 0!==o?o:this._bitmap.width,l=null!==(a=null==t?void 0:t.height)&&void 0!==a?a:this._bitmap.height;this.width=pt(h),this.height=pt(l);const c=this._bitmap.getContext("2d");if(!c)throw new Error("Browser does not support 2d canvas drawing, cannot create Raster graphic");this._ctx=c}cloneRasterOptions(){return{color:this.color?this.color.clone():null,strokeColor:this.strokeColor?this.strokeColor.clone():null,smoothing:this.smoothing,lineWidth:this.lineWidth,lineDash:this.lineDash,padding:this.padding}}get dirty(){return this._dirty}flagDirty(){this._dirty=!0}get width(){return this._getTotalWidth()}set width(t){this._bitmap.width=t,this._originalWidth=t,this.flagDirty()}get height(){return this._getTotalHeight()}set height(t){this._bitmap.height=t,this._originalHeight=t,this.flagDirty()}_getTotalWidth(){var t;return(null!==(t=this._originalWidth)&&void 0!==t?t:this._bitmap.width)+2*this.padding}_getTotalHeight(){var t;return(null!==(t=this._originalHeight)&&void 0!==t?t:this._bitmap.height)+2*this.padding}get localBounds(){return B.fromDimension(this._getTotalWidth()*this.scale.x,this._getTotalHeight()*this.scale.y,A.Zero)}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this.flagDirty()}get color(){return this._color}set color(t){var e;(null===(e=this._color)||void 0===e?void 0:e.equal(t))||this.flagDirty(),this._color=vt(t,(()=>this.flagDirty()))}get strokeColor(){return this._strokeColor}set strokeColor(t){var e;(null===(e=this._strokeColor)||void 0===e?void 0:e.equal(t))||this.flagDirty(),this._strokeColor=vt(t,(()=>this.flagDirty()))}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t,this.flagDirty()}get lineDash(){return this._lineDash}set lineDash(t){this._lineDash=t,this.flagDirty()}get padding(){return this._padding}set padding(t){this._padding=t,this.flagDirty()}rasterize(){this._dirty=!1,this._ctx.clearRect(0,0,this._getTotalWidth(),this._getTotalHeight()),this._ctx.save(),this._applyRasterProperites(this._ctx),this.execute(this._ctx),this._ctx.restore(),gt.load(this._bitmap,!0)}_applyRasterProperites(t){var e,i,s;this._bitmap.width=this._getTotalWidth(),this._bitmap.height=this._getTotalHeight(),t.translate(this.padding,this.padding),t.imageSmoothingEnabled=this.smoothing,t.lineWidth=this.lineWidth,t.setLineDash(null!==(e=this.lineDash)&&void 0!==e?e:t.getLineDash()),t.strokeStyle=null===(i=this.strokeColor)||void 0===i?void 0:i.toString(),t.fillStyle=null===(s=this.color)||void 0===s?void 0:s.toString()}_drawImage(t,e,i){this._dirty&&this.rasterize(),t.drawImage(this._bitmap,e,i)}}class Ct extends bt{constructor(t){super(t),this._options=t}get ctx(){return this._ctx}clone(){return new Ct({...this._options,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){var e,i;(null===(e=this._options)||void 0===e?void 0:e.draw)&&(null===(i=this._options)||void 0===i||i.draw(t)),this._options.cache||this.flagDirty()}}var At;!function(t){t.Kill="kill",t.PreKill="prekill",t.PostKill="postkill",t.PreDraw="predraw",t.PostDraw="postdraw",t.PreDebugDraw="predebugdraw",t.PostDebugDraw="postdebugdraw",t.PreUpdate="preupdate",t.PostUpdate="postupdate",t.PreFrame="preframe",t.PostFrame="postframe",t.PreCollision="precollision",t.CollisionStart="collisionstart",t.CollisionEnd="collisionend",t.PostCollision="postcollision",t.Initialize="initialize",t.Activate="activate",t.Deactivate="deactivate",t.ExitViewport="exitviewport",t.EnterViewport="enterviewport",t.ExitTrigger="exit",t.EnterTrigger="enter",t.Connect="connect",t.Disconnect="disconnect",t.Button="button",t.Axis="axis",t.Subscribe="subscribe",t.Unsubscribe="unsubscribe",t.Visible="visible",t.Hidden="hidden",t.Start="start",t.Stop="stop",t.PointerUp="pointerup",t.PointerDown="pointerdown",t.PointerMove="pointermove",t.PointerEnter="pointerenter",t.PointerLeave="pointerleave",t.PointerCancel="pointercancel",t.PointerWheel="pointerwheel",t.Up="up",t.Down="down",t.Move="move",t.Enter="enter",t.Leave="leave",t.Cancel="cancel",t.Wheel="wheel",t.Press="press",t.Release="release",t.Hold="hold",t.PointerDragStart="pointerdragstart",t.PointerDragEnd="pointerdragend",t.PointerDragEnter="pointerdragenter",t.PointerDragLeave="pointerdragleave",t.PointerDragMove="pointerdragmove"}(At||(At={}));class St{constructor(){this._bubbles=!0}get bubbles(){return this._bubbles}set bubbles(t){this._bubbles=t}stopPropagation(){this.bubbles=!1}}class Pt extends St{constructor(t){super(),this.target=t}}class Et extends St{constructor(t){super(),this.target=t}}class Tt extends St{constructor(t){super(),this.target=t}}class Rt extends St{constructor(t){super(),this.target=t}}class Bt extends St{constructor(t){super(),this.target=t}}class Mt extends St{constructor(t,e,i){super(),this.ctx=t,this.delta=e,this.target=i}}class Dt extends St{constructor(t,e,i){super(),this.ctx=t,this.delta=e,this.target=i}}class Ft extends St{constructor(t,e){super(),this.ctx=t,this.target=e}}class kt extends St{constructor(t,e){super(),this.ctx=t,this.target=e}}class It extends St{constructor(t,e,i){super(),this.engine=t,this.delta=e,this.target=i}}class Lt extends St{constructor(t,e,i){super(),this.engine=t,this.delta=e,this.target=i}}class zt extends St{constructor(t,e){super(),this.engine=t,this.prevStats=e,this.target=t}}class Ot extends St{constructor(t,e){super(),this.engine=t,this.stats=e,this.target=t}}class Ut extends St{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class Ht extends St{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class Nt extends St{constructor(t,e,i){super(),this.button=t,this.value=e,this.target=i}}class Wt extends St{constructor(t,e,i){super(),this.axis=t,this.value=e,this.target=i}}class Vt extends St{constructor(t,e){super(),this.topic=t,this.handler=e}}class Gt extends St{constructor(t,e){super(),this.topic=t,this.handler=e}}class Xt extends St{constructor(t){super(),this.target=t}}class jt extends St{constructor(t){super(),this.target=t}}class qt extends St{constructor(t,e,i,s){super(),this.other=e,this.side=i,this.intersection=s,this.target=t}}class Kt extends St{constructor(t,e,i,s){super(),this.other=e,this.side=i,this.intersection=s,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class Zt{constructor(t,e,i){this.target=t,this.other=e,this.contact=i}}class Yt{constructor(t,e){this.target=t,this.other=e}}class Qt{constructor(t,e,i,s,n){this.target=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class $t{constructor(t,e,i,s,n){this.target=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class Jt extends St{constructor(t,e,i){super(),this.other=e,this.contact=i,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class te extends St{constructor(t,e){super(),this.other=e,this.target=t}get actor(){return this.target}set actor(t){this.target=t}}class ee extends St{constructor(t,e){super(),this.engine=t,this.target=e}}class ie extends St{constructor(t,e){super(),this.oldScene=t,this.target=e}}class se extends St{constructor(t,e){super(),this.newScene=t,this.target=e}}class ne extends St{constructor(t){super(),this.target=t}}class re extends St{constructor(t){super(),this.target=t}}class oe extends St{constructor(t,e){super(),this.target=t,this.actor=e}}class ae extends St{constructor(t,e){super(),this.target=t,this.actor=e}}class he{constructor(){this._handlers={},this._wiredEventDispatchers=[]}clear(){this._handlers={},this._wiredEventDispatchers=[]}emit(t,e){if(!t)return;let i,s;if(t=t.toLowerCase(),e||(e=new St),this._handlers[t])for(i=0,s=this._handlers[t].length;i<s;i++)this._handlers[t][i](e);for(i=0,s=this._wiredEventDispatchers.length;i<s;i++)this._wiredEventDispatchers[i].emit(t,e)}on(t,e){t=t.toLowerCase(),this._handlers[t]||(this._handlers[t]=[]),this._handlers[t].push(e),"unsubscribe"!==t&&"subscribe"!==t&&this.emit("subscribe",new Vt(t,e))}off(t,e){t=t.toLowerCase();const i=this._handlers[t];if(i)if(e){const s=i.indexOf(e);this._handlers[t].splice(s,1)}else this._handlers[t].length=0;"unsubscribe"!==t&&"subscribe"!==t&&this.emit("unsubscribe",new Gt(t,e))}once(t,e){this.on(t,(i=>{const s=i||new St;this.off(t,e),e(s)}))}wire(t){t._wiredEventDispatchers.push(this)}unwire(t){const e=t._wiredEventDispatchers.indexOf(this);e>-1&&t._wiredEventDispatchers.splice(e,1)}}class le{constructor(t,e,i=!0){this.path=t,this.responseType=e,this.bustCache=i,this.data=null,this.logger=_.getInstance(),this.events=new he}isLoaded(){return null!==this.data}_cacheBust(t){return/\?\w*=\w*/.test(t)?t+="&__="+Date.now():t+="?__="+Date.now(),t}load(){return new Promise(((t,e)=>{if(null!==this.data)return this.logger.debug("Already have data for resource",this.path),this.events.emit("complete",this.data),void t(this.data);const i=new XMLHttpRequest;i.open("GET",this.bustCache?this._cacheBust(this.path):this.path,!0),i.responseType=this.responseType,i.addEventListener("loadstart",(t=>this.events.emit("loadstart",t))),i.addEventListener("progress",(t=>this.events.emit("progress",t))),i.addEventListener("error",(t=>this.events.emit("error",t))),i.addEventListener("load",(t=>this.events.emit("load",t))),i.addEventListener("load",(()=>{if(0!==i.status&&200!==i.status)return this.logger.error("Failed to load resource ",this.path," server responded with error code",i.status),this.events.emit("error",i.response),void e(new Error(i.statusText));this.data=i.response,this.events.emit("complete",this.data),this.logger.debug("Completed loading resource",this.path),t(this.data)})),i.send()}))}}var ce=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};let de=class{updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=(n[s+0]+n[s+1]+n[s+2])/3;n[s+0]=r,n[s+1]=r,n[s+2]=r}};de=ce([b({message:"Grayscale will be removed in v0.26.0"})],de);let ue=class{updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data;n[s+0]=255-n[s+0],n[s+1]=255-n[s+1],n[s+2]=255-n[s+2]}};ue=ce([b({message:"Invert will be removed in v0.26.0"})],ue);let pe=class{constructor(t){this.opacity=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data;0!==n[s+3]&&(n[s+3]=Math.round(this.opacity*n[s+3]))}};pe=ce([b({message:"Opacity will be removed in v0.26.0"})],pe);let ge=class{constructor(t){this.color=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data;0!==n[s+3]&&(n[s+0]=(n[s+0]+this.color.r)/2,n[s+1]=(n[s+1]+this.color.g)/2,n[s+2]=(n[s+2]+this.color.b)/2)}};ge=ce([b({message:"Colorize will be removed in v0.26.0"})],ge);let _e=class{constructor(t=.1){this.factor=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=T.fromRGB(n[s+0],n[s+1],n[s+2],n[s+3]).lighten(this.factor);n[s+0]=r.r,n[s+1]=r.g,n[s+2]=r.b,n[s+3]=r.a}};_e=ce([b({message:"Lighten will be removed in v0.26.0"})],_e);let me=class{constructor(t=.1){this.factor=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=T.fromRGB(n[s+0],n[s+1],n[s+2],n[s+3]).darken(this.factor);n[s+0]=r.r,n[s+1]=r.g,n[s+2]=r.b,n[s+3]=r.a}};me=ce([b({message:"Darken will be removed v0.26.0"})],me);let fe=class{constructor(t=.1){this.factor=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=T.fromRGB(n[s+0],n[s+1],n[s+2],n[s+3]).saturate(this.factor);n[s+0]=r.r,n[s+1]=r.g,n[s+2]=r.b,n[s+3]=r.a}};fe=ce([b({message:"Saturate will be removed in v0.26.0"})],fe);let we=class{constructor(t=.1){this.factor=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data,r=T.fromRGB(n[s+0],n[s+1],n[s+2],n[s+3]).desaturate(this.factor);n[s+0]=r.r,n[s+1]=r.g,n[s+2]=r.b,n[s+3]=r.a}};we=ce([b({message:"Desaturate will be removed in v0.26.0"})],we);let ye=class{constructor(t){this.color=t}updatePixel(t,e,i){const s=4*(t+e*i.width),n=i.data;0!==n[s+3]&&(n[s+0]=this.color.r,n[s+1]=this.color.g,n[s+2]=this.color.b)}};ye=ce([b({message:"Fill will be removed in v0.26.0"})],ye);class ve{constructor(t,e=!0){this.path=t,this.bustCache=e,this._sprite=null,this.loaded=new Promise((t=>{this._loadedResolve=t})),this._resource=new le(t,"blob",e),this._sprite=new Ae(this,0,0,0,0)}get image(){return this.data}isLoaded(){return!!this.data}async load(){try{let t;if(this.path.includes("data:image/"))t=this.path;else{const e=await this._resource.load();t=URL.createObjectURL(e)}const e=new Image;e.src=t,await e.decode(),this.data=e,this.width=this._sprite.width=e.naturalWidth,this.height=this._sprite.height=e.naturalHeight,this._sprite=new Ae(this,0,0,this.width,this.height)}catch(t){await Promise.reject("Error loading texture")}return this._loadedResolve(this.data),this.data}asSprite(){return this._sprite}}function xe(t){return class extends t{assign(t){for(const e in t)"function"!=typeof this[e]&&(this[e]=t[e])}constructor(...t){super(...t);1!==t.filter((function(t){return void 0!==t})).length||!t[0]||"object"!=typeof t[0]||t[0]instanceof Array||this.assign(t[0])}}}var be=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Ce{constructor(t,e,i,s,n){this.x=0,this.y=0,this.rotation=0,this.anchor=A.Half,this.offset=A.Zero,this.scale=A.One,this.drawAroundAnchor=!1,this.logger=_.getInstance(),this.flipVertical=!1,this.flipHorizontal=!1,this.effects=[],this.width=0,this.height=0,this._spriteCanvas=null,this._spriteCtx=null,this._pixelData=null,this._pixelsLoaded=!1,this._dirtyEffect=!0,this._opacity=1;let r=t;if(t&&!(t instanceof ve)&&(e=0|t.x,i=0|t.y,s=0|t.width,n=0|t.height,r=t.image,!r)){throw new Error("An image texture is required to construct a sprite")}this.x=e||0,this.y=i||0,this.texture=r,this._spriteCanvas=document.createElement("canvas"),this._spriteCanvas.width=s,this._spriteCanvas.height=n,this._spriteCtx=this._spriteCanvas.getContext("2d"),this._initPixelsFromTexture(),this.width=s,this.height=n}get drawWidth(){return Math.abs(this.width*this.scale.x)}get drawHeight(){return Math.abs(this.height*this.scale.y)}async _initPixelsFromTexture(){try{const t=await this.texture.loaded;this.width=this.width||t.naturalWidth,this.height=this.height||t.naturalHeight,this._spriteCanvas.width=this._spriteCanvas.width||t.naturalWidth,this._spriteCanvas.height=this._spriteCanvas.height||t.naturalHeight,this._loadPixels(),this._dirtyEffect=!0}catch(t){this.logger.error("Error loading texture ",this.texture.path,t)}}_loadPixels(){if(this.texture.isLoaded()&&!this._pixelsLoaded){const t=this.texture.image.naturalWidth||0,e=this.texture.image.naturalHeight||0;if(this.width>t&&this.logger.warn(`The sprite width ${this.width} exceeds the width \n ${t} of the backing texture ${this.texture.path}`),this.width<=0||t<=0)throw new Error(`The width of a sprite cannot be 0 or negative, sprite width: ${this.width}, original width: ${t}`);if(this.height>e&&this.logger.warn(`The sprite height ${this.height} exceeds the height \n ${e} of the backing texture ${this.texture.path}`),this.height<=0||e<=0)throw new Error(`The height of a sprite cannot be 0 or negative, sprite height: ${this.height}, original height: ${e}`);this._flushTexture(),this._pixelsLoaded=!0}}_flushTexture(){const t=this.texture.image.naturalWidth||0,e=this.texture.image.naturalHeight||0;this._spriteCtx.clearRect(0,0,this.width,this.height),this._spriteCtx.drawImage(this.texture.image,L(this.x,0,t),L(this.y,0,e),L(this.width,0,t),L(this.height,0,e),0,0,this.width,this.height)}opacity(t){this._opacity=t}grayscale(){this.addEffect(new de)}invert(){this.addEffect(new ue)}fill(t){this.addEffect(new ye(t))}colorize(t){this.addEffect(new ge(t))}lighten(t=.1){this.addEffect(new _e(t))}darken(t=.1){this.addEffect(new me(t))}saturate(t=.1){this.addEffect(new fe(t))}desaturate(t=.1){this.addEffect(new we(t))}addEffect(t){this.effects.push(t),this.texture.isLoaded()&&this._pixelsLoaded?this._applyEffects():this._dirtyEffect=!0}removeEffect(t){let e=-1;e="number"==typeof t?t:this.effects.indexOf(t),e<0||e>=this.effects.length||(this.effects.splice(e,1),this.texture.isLoaded()&&this._pixelsLoaded?this._applyEffects():this._dirtyEffect=!0)}_applyEffects(){if(this._flushTexture(),this.effects.length>0){this._pixelData=this._spriteCtx.getImageData(0,0,this.width,this.height);const t=this.effects.length;for(let e=0;e<t;e++)for(let t=0;t<this.height;t++)for(let i=0;i<this.width;i++)this.effects[e].updatePixel(i,t,this._pixelData);this._spriteCtx.clearRect(0,0,this.width,this.height),this._spriteCtx.putImageData(this._pixelData,0,0)}this._dirtyEffect=!1}clearEffects(){this.effects.length=0,this._applyEffects()}reset(){}debugDraw(t,e,i){t.save(),t.translate(e,i),t.rotate(this.rotation);const s=this.drawWidth*this.anchor.x,n=this.drawHeight*this.anchor.y;t.strokeStyle=T.Black.toString(),t.strokeRect(-s,-n,this.drawWidth,this.drawHeight),t.restore()}draw(t,e,i){t instanceof CanvasRenderingContext2D?this._drawWithOptions({ctx:t,x:e,y:i}):this._drawWithOptions(t)}_drawWithOptions(t){var e,i,s,n,r,o,a,h,l;const{ctx:c,x:d,y:u,rotation:p,drawWidth:g,drawHeight:_,anchor:m,offset:f,opacity:w,flipHorizontal:y,flipVertical:v}={...t,rotation:null!==(e=t.rotation)&&void 0!==e?e:this.rotation,drawWidth:null!==(i=t.drawWidth)&&void 0!==i?i:this.width,drawHeight:null!==(s=t.drawHeight)&&void 0!==s?s:this.height,flipHorizontal:null!==(n=t.flipHorizontal)&&void 0!==n?n:this.flipHorizontal,flipVertical:null!==(r=t.flipVertical)&&void 0!==r?r:this.flipVertical,anchor:null!==(o=t.anchor)&&void 0!==o?o:this.anchor,offset:null!==(a=t.offset)&&void 0!==a?a:this.offset,opacity:(null!==(h=t.opacity)&&void 0!==h?h:1)*(null!==(l=this._opacity)&&void 0!==l?l:1)};this._dirtyEffect&&this._applyEffects();const x=g*m.x+f.x,b=_*m.y+f.y,C=this.scale.x>0?1:-1,A=this.scale.y>0?1:-1;c.save(),c.translate(d,u),c.scale(Math.abs(this.scale.x),Math.abs(this.scale.y)),this.drawAroundAnchor&&c.translate(-x,-b),c.translate(x,b),c.rotate(p),c.scale(C,A),c.translate(-x,-b),y&&(c.translate(g,0),c.scale(-1,1)),v&&(c.translate(0,_),c.scale(1,-1));const S=c.globalAlpha;c.globalAlpha=w,c.drawImage(this._spriteCanvas,0,0,this.width,this.height,0,0,this.width,this.height),c.globalAlpha=S,c.restore()}clone(){const t=new Ae(this.texture,this.x,this.y,this.width,this.height);t.anchor=this.anchor.clone(),t.scale=this.scale.clone(),t.rotation=this.rotation,t.flipHorizontal=this.flipHorizontal,t.flipVertical=this.flipVertical;const e=this.effects.length;for(let i=0;i<e;i++)t.addEffect(this.effects[i]);return t}}let Ae=class extends(xe(Ce)){constructor(t,e,i,s,n){super(t,e,i,s,n)}};Ae=be([b({message:"Label.clearTextShadow will be removed in v0.26.0",alternateMethod:"Use Label.font.shadow"})],Ae);class Se extends yt{constructor(t){var e,i;super(t),this.image=t.image;const{width:s,height:n}=t;this.sourceView=null!==(e=t.sourceView)&&void 0!==e?e:{x:0,y:0,width:null!=s?s:0,height:null!=n?n:0},this.destSize=null!==(i=t.destSize)&&void 0!==i?i:{width:null!=s?s:0,height:null!=n?n:0},this._updateSpriteDimensions(),this.image.ready.then((()=>{this._updateSpriteDimensions()}))}static from(t){return new Se({image:t})}get width(){return this.destSize.width}get height(){return this.destSize.height}set width(t){this.destSize.width=t,super.width=Math.ceil(this.destSize.width)}set height(t){this.destSize.height=t,super.height=Math.ceil(this.destSize.height)}_updateSpriteDimensions(){var t,e,i,s,n,r;const{width:o,height:a}=this.image;this.sourceView.width=(null===(t=this.sourceView)||void 0===t?void 0:t.width)||o,this.sourceView.height=(null===(e=this.sourceView)||void 0===e?void 0:e.height)||a,this.destSize.width=(null===(i=this.destSize)||void 0===i?void 0:i.width)||(null===(s=this.sourceView)||void 0===s?void 0:s.width)||o,this.destSize.height=(null===(n=this.destSize)||void 0===n?void 0:n.height)||(null===(r=this.sourceView)||void 0===r?void 0:r.height)||a,this.width=Math.ceil(this.destSize.width),this.height=Math.ceil(this.destSize.height)}_preDraw(t,e,i){this.image.isLoaded()&&this._updateSpriteDimensions(),super._preDraw(t,e,i)}_drawImage(t,e,i){this.image.isLoaded()&&(this._updateSpriteDimensions(),t.drawImage(this.image.image,this.sourceView.x,this.sourceView.y,this.sourceView.width,this.sourceView.height,e,i,this.destSize.width,this.destSize.height))}static fromLegacySprite(t){const e=t.texture,i=Pe.fromLegacyTexture(e);return new Se({image:i,sourceView:{x:t.x,y:t.y,width:t.width,height:t.height}})}static toLegacySprite(t){const e=t.image,i=new ve(e.path);return i.data=e.image,new Ae(i,t.sourceView.x,t.sourceView.y,t.sourceView.width,t.sourceView.height)}clone(){return new Se({image:this.image,sourceView:{...this.sourceView},destSize:{...this.destSize},...this.cloneGraphicOptions()})}}class Pe{constructor(t,e=!1){this.path=t,this._logger=_.getInstance(),this.data=new Image,this._resource=new le(t,"blob",e),(t.endsWith(".svg")||t.endsWith(".gif"))&&this._logger.warn(`Image type is not fully supported, you may have mixed results ${t}. Fully supported: jpg, bmp, and png`),this.ready=new Promise((t=>{this._loadedResolve=t}))}get width(){return this.image.naturalWidth}get height(){return this.image.naturalHeight}isLoaded(){return!!this.data.src}get image(){return this.data}async load(){if(this.isLoaded())return this.data;try{let t;if(this.path.includes("data:image/"))t=this.path;else{const e=await this._resource.load();t=URL.createObjectURL(e)}const e=new Image;e.src=t,await e.decode(),this.data=e}catch(t){throw`Error loading ImageSource from path '${this.path}' with error [${t.message}]`}return this._loadedResolve(this.data),this.data}toSprite(){return Se.from(this)}static fromLegacyTexture(t){const e=new Pe(t.path);return t.isLoaded()?e.data=t.data:t.loaded.then((()=>{e.data=t.data})),e}unload(){this.data=new Image}}var Ee=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Te{constructor(t,e,i,s){this.sprites=[],this.currentFrame=0,this._timeLeftInFrame=0,this._idempotencyToken=-1,this.anchor=A.Zero,this.rotation=0,this.scale=A.One,this.loop=!0,this.freezeFrame=-1,this.flipVertical=!1,this.flipHorizontal=!1,this.drawWidth=0,this.drawHeight=0,this.width=0,this.height=0,this._opacity=1;let n=t;if(t&&!(t instanceof sr)){const r=t;n=r.engine,e=r.sprites,i=r.speed,s=r.loop}this.sprites=e,this.speed=i,this._engine=n,this._timeLeftInFrame=this.speed,null!=s&&(this.loop=s),e&&e[0]&&(this.drawHeight=e[0]?e[0].drawHeight:0,this.drawWidth=e[0]?e[0].drawWidth:0,this.width=e[0]?e[0].width:0,this.height=e[0]?e[0].height:0,this.freezeFrame=e.length-1)}opacity(t){this._opacity=t}grayscale(){this.addEffect(new de)}invert(){this.addEffect(new ue)}fill(t){this.addEffect(new ye(t))}colorize(t){this.addEffect(new ge(t))}lighten(t=.1){this.addEffect(new _e(t))}darken(t=.1){this.addEffect(new me(t))}saturate(t=.1){this.addEffect(new fe(t))}desaturate(t=.1){this.addEffect(new we(t))}addEffect(t){for(const e in this.sprites)this.sprites[e].addEffect(t)}removeEffect(t){for(const e in this.sprites)this.sprites[e].removeEffect(t)}clearEffects(){for(const t in this.sprites)this.sprites[t].clearEffects()}_setAnchor(t){for(const e in this.sprites)this.sprites[e].anchor.setTo(t.x,t.y)}_setRotation(t){for(const e in this.sprites)this.sprites[e].rotation=t}_setScale(t){for(const e in this.sprites)this.sprites[e].scale=t}reset(){this.currentFrame=0}isDone(){return!this.loop&&this.currentFrame>=this.sprites.length}tick(t,e){if(this._idempotencyToken===e)return;this._idempotencyToken=e,this._timeLeftInFrame-=t,this._timeLeftInFrame<=0&&(this.currentFrame=this.loop?(this.currentFrame+1)%this.sprites.length:this.currentFrame+1,this._timeLeftInFrame=this.speed),this._updateValues();const i=this.sprites[this.currentFrame];i&&(this.width=i.width,this.height=i.height,this.drawWidth=i.drawWidth,this.drawHeight=i.drawHeight)}_updateValues(){this._setAnchor(this.anchor),this._setRotation(this.rotation),this._setScale(this.scale)}skip(t){this.currentFrame=(this.currentFrame+t)%this.sprites.length}draw(t,e,i){t instanceof CanvasRenderingContext2D?this._drawWithOptions({ctx:t,x:e,y:i}):this._drawWithOptions(t)}_drawWithOptions(t){var e,i,s,n,r,o,a,h;const l={...t,rotation:null!==(e=t.rotation)&&void 0!==e?e:this.rotation,drawWidth:null!==(i=t.drawWidth)&&void 0!==i?i:this.drawWidth,drawHeight:null!==(s=t.drawHeight)&&void 0!==s?s:this.drawHeight,flipHorizontal:null!==(n=t.flipHorizontal)&&void 0!==n?n:this.flipHorizontal,flipVertical:null!==(r=t.flipVertical)&&void 0!==r?r:this.flipVertical,anchor:null!==(o=t.anchor)&&void 0!==o?o:this.anchor,opacity:(null!==(a=t.opacity)&&void 0!==a?a:1)*(null!==(h=this._opacity)&&void 0!==h?h:1)};let c;this._updateValues(),this.currentFrame<this.sprites.length&&(c=this.sprites[this.currentFrame],c.draw(l)),-1!==this.freezeFrame&&this.currentFrame>=this.sprites.length&&(c=this.sprites[L(this.freezeFrame,0,this.sprites.length-1)],c.draw(l)),c&&(this.drawWidth=c.drawWidth,this.drawHeight=c.drawHeight)}play(t,e){this.reset(),this._engine.playAnimation(this,t,e)}}let Re=class extends(xe(Te)){constructor(t,e,i,s){super(t,e,i,s)}};var Be,Me,De,Fe,ke;Re=Ee([b({message:"Animation will be removed in v0.26.0",alternateMethod:"Use Graphics.Animation"})],Re),function(t){t.Em="em",t.Rem="rem",t.Px="px",t.Pt="pt",t.Percent="%"}(Be||(Be={})),function(t){t.Left="left",t.Right="right",t.Center="center",t.Start="start",t.End="end"}(Me||(Me={})),function(t){t.Top="top",t.Hanging="hanging",t.Middle="middle",t.Alphabetic="alphabetic",t.Ideographic="ideographic",t.Bottom="bottom"}(De||(De={})),function(t){t.Normal="normal",t.Italic="italic",t.Oblique="oblique"}(Fe||(Fe={})),function(t){t.LeftToRight="ltr",t.RightToLeft="rtl"}(ke||(ke={}));var Ie=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Le{constructor(t,e,i,s,n,r){this._sprites=[],this._image=null,this._columns=0,this._rows=0,this._spWidth=0,this._spHeight=0,this._spacing=0;let o=!1;if(t instanceof Array?this._sprites=t:(!t||t instanceof ve?(this._image=t,this._columns=e,this._rows=i,this._spWidth=s,this._spHeight=n,this._spacing=r||0):(this._columns=t.columns,this._rows=t.rows,this._spWidth=t.spWidth,this._spHeight=t.spHeight,this._image=t.image,this._spacing=t.spacing||0),this._sprites=new Array(this._columns*this._rows),o=!0),this.image instanceof ve){let t=!1,e=!1;if(this.image.isLoaded()){if(t=this.spWidth*this.columns>this.image.image.naturalWidth,e=this.spHeight*this.rows>this.image.image.naturalHeight,t)throw new RangeError(`SpriteSheet specified is wider, ${this.columns} cols x ${this.spWidth} pixels > ${this.image.image.naturalWidth} pixels than image width`);if(e)throw new RangeError(`SpriteSheet specified is taller, ${this.rows} rows x ${this.spHeight} pixels > ${this.image.image.naturalHeight} pixels than image height`)}}if(o){const t=this.getSpacingDimensions();for(let e=0;e<this.rows;e++)for(let i=0;i<this.columns;i++)this._sprites[i+e*this.columns]=new Ae(this.image,i*this.spWidth+t.margin*i+t.left,e*this.spHeight+t.margin*e+t.top,this.spWidth,this.spHeight)}}get spacing(){return this._spacing}get sprites(){return[...this._sprites]}get image(){return this._image}get columns(){return this._columns}get rows(){return this._rows}get spWidth(){return this._spWidth}get spHeight(){return this._spHeight}getSpacingDimensions(){var t,e,i;return"number"==typeof this.spacing?{left:this.spacing,top:this.spacing,margin:this.spacing}:{left:null!==(t=this.spacing.left)&&void 0!==t?t:0,top:null!==(e=this.spacing.top)&&void 0!==e?e:0,margin:null!==(i=this.spacing.margin)&&void 0!==i?i:0}}getAnimationByIndices(t,e,i){let s=e.map((t=>this.sprites[t]));return s=s.map((function(t){return t.clone()})),new Re(t,s,i)}getAnimationBetween(t,e,i,s){let n=this.sprites.slice(e,i);return n=n.map((function(t){return t.clone()})),new Re(t,n,s)}getAnimationForAll(t,e){const i=this.sprites.map((function(t){return t.clone()}));return new Re(t,i,e)}getSprite(t){if(t>=0&&t<this.sprites.length)return this.sprites[t];throw new Error("Invalid index: "+t)}getAnimationByCoords(t,e,i){let s=0,n=0;const r=new Array(e.length);for(let t=0;t<e.length;t++){const i=e[t];i.image=i.image||this.image,s=Math.max(s,i.drawWidth),n=Math.max(n,i.drawHeight),r[t]=new Ae(i)}const o=new Re(t,r,i);return o.drawWidth=s,o.drawHeight=n,o}}let ze=class extends Le{constructor(t,e,i,s,n,r,o,a){super(t instanceof ve?{image:t,spWidth:r,spHeight:o,rows:n,columns:s,spacing:a||0}:t),this._currentColor=T.Black,this._currentOpacity=1,this._spriteRecord={},this._textShadowOn=!1,this._textShadowDirty=!0,this._textShadowColor=T.Black,this._textShadowSprites={},this._shadowOffsetX=5,this._shadowOffsetY=5,!t||t instanceof ve||(e=t.alphabet,i=t.caseInsensitive),this.alphabet=e,this.caseInsensitive=i,this._spriteRecord=this.getTextSprites()}getTextSprites(){const t={};for(let e=0;e<this.alphabet.length;e++){let i=this.alphabet[e];this.caseInsensitive&&(i=i.toLowerCase()),t[i]=this.sprites[e].clone()}return t}setTextShadow(t,e,i){this._textShadowOn=!0,this._shadowOffsetX=t,this._shadowOffsetY=e,this._textShadowColor=i.clone(),this._textShadowDirty=!0;for(const t in this._spriteRecord)this._textShadowSprites[t]=this._spriteRecord[t].clone()}useTextShadow(t){this._textShadowOn=t,t&&this.setTextShadow(5,5,this._textShadowColor)}draw(t,e,i,s,n){if(n=this._parseOptions(n),this._currentColor.toString()!==n.color.toString()||this._currentOpacity!==n.opacity){this._currentOpacity=n.opacity,this._currentColor=n.color;for(const t in this._spriteRecord)this._spriteRecord[t].clearEffects(),this._spriteRecord[t].fill(n.color),this._spriteRecord[t].opacity(n.opacity)}if(this._textShadowOn&&this._textShadowDirty&&this._textShadowColor){for(const t in this._textShadowSprites)this._textShadowSprites[t].clearEffects(),this._textShadowSprites[t].addEffect(new ye(this._textShadowColor.clone()));this._textShadowDirty=!1}const r=this.sprites[0],o=r.height,a=n.fontSize/o,h=e.length*r.width*a+e.length*n.letterSpacing;let l=i;n.textAlign===Me.Left||n.textAlign===Me.Start?l=i:n.textAlign===Me.Right||n.textAlign===Me.End?l=i-h:n.textAlign===Me.Center&&(l=i-h/2);let c=s-o*a;n.baseAlign===De.Top||n.baseAlign===De.Hanging?c=s:n.baseAlign===De.Ideographic||n.baseAlign===De.Bottom||n.baseAlign===De.Alphabetic?c=s-o*a:n.baseAlign===De.Middle&&(c=s-o*a/2);for(let i=0;i<e.length;i++){let s=e[i];this.caseInsensitive&&(s=s.toLowerCase());try{this._textShadowOn&&(this._textShadowSprites[s].drawAroundAnchor=!1,this._textShadowSprites[s].scale=S(a,a),this._textShadowSprites[s].draw(t,l+this._shadowOffsetX,c+this._shadowOffsetY));const e=this._spriteRecord[s];e.drawAroundAnchor=!1,e.scale=S(a,a),e.draw(t,l,c),l+=e.drawWidth+n.letterSpacing}catch(t){_.getInstance().error(`SpriteFont Error drawing char ${s}`)}}}_parseOptions(t){return{fontSize:t.fontSize||10,letterSpacing:t.letterSpacing||0,color:t.color||T.Black,textAlign:void 0===typeof t.textAlign?Me.Left:t.textAlign,baseAlign:void 0===typeof t.baseAlign?De.Bottom:t.baseAlign,maxWidth:t.maxWidth||-1,opacity:t.opacity||0}}};ze=Ie([b({message:"SpriteSheet will be removed in v0.26.0",alternateMethod:"Use Graphics.SpriteSheet"})],ze);class Oe{constructor(t){this._logger=_.getInstance(),this.sprites=[];const{sprites:e,rows:i,columns:s}=t;this.sprites=e,this.rows=null!=i?i:1,this.columns=null!=s?s:this.sprites.length}getSprite(t,e){if(t>=this.columns||t<0)return this._logger.warn(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1}`),null;if(e>=this.rows||e<0)return this._logger.warn(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1}`),null;const i=t+e*this.columns;return this.sprites[i]}static fromLegacySpriteSheet(t){const e=t.sprites.map((t=>Se.fromLegacySprite(t)));return new Oe({sprites:e})}static toLegacySpriteSheet(t){const e=t.sprites.map((t=>Se.toLegacySprite(t)));return new Le(e)}static fromImageSource(t){var e;const i=[];t.spacing=null!==(e=t.spacing)&&void 0!==e?e:{};const{image:s,grid:{rows:n,columns:r,spriteWidth:o,spriteHeight:a},spacing:{originOffset:h,margin:l}}=t,c={x:0,y:0,...h},d={x:0,y:0,...l};for(let t=0;t<r;t++)for(let e=0;e<n;e++)i[t+e*r]=new Se({image:s,sourceView:{x:t*o+d.x*t+c.x,y:e*a+d.y*e+c.y,width:o,height:a},destSize:{height:a,width:o}});return new Oe({sprites:i,rows:n,columns:r})}}class Ue extends yt{constructor(t){super(t),this._text="",this._dirty=!0,this.alphabet="",this.shadow=null,this.caseInsensitive=!1,this.spacing=0,this._logger=_.getInstance(),this._sprites=[];const{alphabet:e,spriteSheet:i,caseInsensitive:s,spacing:n,shadow:r}=t;this.alphabet=e,this.spriteSheet=i,this.caseInsensitive=null!=s?s:this.caseInsensitive,this.spacing=null!=n?n:this.spacing,this.shadow=null!=r?r:this.shadow,this.spriteSheet.sprites[0].image.ready.then((()=>{this._updateDimensions()}))}static fromLegacySpriteFont(t){const e=t.sprites.map(Se.fromLegacySprite);return new Ue({alphabet:t.alphabet,spacing:0,caseInsensitive:t.caseInsensitive,spriteSheet:new Oe({sprites:e})})}_getCharacterSprites(t){if(!this._dirty)return this._sprites;const e=[],i=this.caseInsensitive?t.toLocaleLowerCase():t,s=this.caseInsensitive?this.alphabet.toLocaleLowerCase():this.alphabet;for(let t=0;t<i.length;t++){const n=i[t];let r=s.indexOf(n);-1===r&&(r=0,this._logger.warn(`SpriteFont - Cannot find letter '${n}' in configured alphabet '${s}'`));const o=this.spriteSheet.sprites[r];o?e.push(o):this._logger.warn(`SpriteFont - Cannot find sprite for '${n}' at index '${r}' in configured SpriteSheet`)}return this._dirty=!1,this._sprites=e}_updateDimensions(){const t=this._getCharacterSprites(this._text);let e=0,i=0;for(const s of t)e+=s.width+this.spacing,i=Math.max(i,s.height);this.width=e,this.height=i}updateText(t){this._text!==t&&(this._dirty=!0,this._text=t,this._updateDimensions())}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,e,i)}_drawImage(t,e,i){let s=0;for(const n of this._getCharacterSprites(this._text))n.draw(t,e+s,i),s+=n.width+this.spacing}render(t,e,i,s){this._text!==e&&(this._dirty=!0,this._text=e),this.shadow&&(t.save(),t.translate(this.shadow.offset.x,this.shadow.offset.y),this.draw(t,i,s),t.restore()),this.draw(t,i,s)}clone(){return new Ue({alphabet:this.alphabet,spriteSheet:this.spriteSheet,spacing:this.spacing})}}class He{constructor(){this.fontSheet="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAAwCAYAAAD+f6R/AAAAAXNSR0IArs4c6QAABcJJREFUeJztnemu7CgMhGE07//KmT9NhrAFVzkQndQntXRP3/bCZkwCSQhCCCGEEEIIIYQQQog/TRz953Ecx/nDGIe/vdNhlc9tIz605Fk/ZmWfsO1hn9Gxuv1KHbvb3iL/VN+d1WORbyr7yR/5b9M4vjNeqko6jPJHq5wGHU151o9J2Udse9hndCxuv0rH7rY3yD/Wdyf13MrnQeDfkZIUSGKM4ff3cWN82pEZuTyQGX2IxeyR63va//8VNCYCq+1yEkLtWyagXv1P1r1H+110gP3PzT4gT8uW/mdQ8mUG8E9DqOz4MS9ICKGbXpS2BpnIrRzYeS96cll08INlCMl2/glzdcfazuuPqQO03lmqrBHsf272Q6NODXj6zzZIJd/LAHYTg3Mays5gBi7ZR27fOgs0yj8rm36DLMFiPgkAdXHKOwUQeMCQ/adSh/qBQrT/tPxbAwA9+DOZEILPAATSuHMgTv7+Auk/df2lHPCZLvMSLJe34LkEQ9PwXF1SRTllMYgvIaflqyVAjLGbsiCDcOK76jflxZ+sINPyROc5071yKWK5CJTV3dMp6+tBlyCtNlhAq/+XbWoBDcRNXYBMzD4VvQygSuPYC2jGGaSSOxXfy3dTUEsanIvNeepm38N/hssSALTPZnAXfwIYRJn2b7UBcw0FKX+nDdAMpm2j9WVnxrUa7TXaVAca/B+TgaAVh6R/rH0P/5m01dt/RLYViJn+w/bhVX2P7f/duqom5qb02pRLCLGIMgBU1wCEEN9BAUCID6MAIMSHUQAQ4sMoAAjxYRQAhPgwd1uB0fuZ7H3cnn2P+9mr/Pe4B8/eB/fwP4eRtci/0f6OfTCPt/9oHwC6G6y19RHZDumxmwzR4eE/s/2Tte/q/+XLdc9DeJ19diesQc/j7Z8fCe4tAS4CxZ7sp7eiJi7HiZmjmOTGJs+93CbS3nP0XIPH3vW8/qz6QPnX2QdsV/1uw/iZYvg8ACeHd28rpPzfNfhL+7vkw/4Ou9s+Onhbv91elpKZ48Dl6bzpwwibHigRArf+Ptk9+L3Y1Q5OB4LgCeSBw1iuB3GeJh1/HrX/zF0A9Mk+u45zMkc3r4rWPomma5+p/514LB+Zo93MErJ1JHxXPzByGa/licRYVKbpeQCoQ6Q8yxuCwJF9IPsoDkHAo/3Tx26cvA4EtJ/n04w8QOq/mrR7ddfLAC5BYFNlVI/0CnOVUflOpvJUQMx9AIMIW/nWDM67/qw0+95v9goBqD9j+72u/KD9U89IbnQbMIR2Zbneh5zUY7Hdk7XIP3UffVb+r+wDYAZLq+1n1+C7y3/ny2r7p5yeByDEh9HzAIQQJwoAQnwYBQAhPowCgBBjoNu3hNxSFACE6INuKvPajPZ4EFEAEKINcybGYzOd247WEd3TgA2jlmjEyrd+j9hvfVbD2PWQ3ZmGlu2HyO8og8eBuNUvNYWoDgMVpwHTJoLWdz1Y+ZYOy5uF7t6PPruZxANrud1lQXkP0jsGz/Yz+vGGMuygFyhSPcJnc1pMnQZElc+cRnoAlxdTvoDuK7puqF7uCQy+3fyFMiA02/vJQHh7DQDogMPTSGFNA56HTzbZ9yAfBOb1Zyo3qGM3MfMZ3f76huXf6xlmAHknMlLNXsBBBvbljIz9Uyz5Y5TzIBLR/qy/rNyrZ8+L/0BZ0m+tgXD0OK5XZxC/9P7I/g4hVFvzXf1/6i5A7+3AlijMPBLMZfCvuAp7A9rY56ApHitmLQc7c8bOv6ftAxlM9Xp35nkEK7nJetBsaMhtAAAuOLQGXwhh2dXQnn1rZ/a42BI3dL7L+jkFAbQddwdA9Ah35yMKhgEgVT46EFh5D4jz+OgavNKxeBCd1wDSJ/97oR8eoJkLi9t9/BDgDHTJ5NE7Dnzechh914OVv9M1K9PCqsfqb88XVg9qN9lm6nG176UPu+zn17GOxuO0vOWEEC/j+LFKTgghlvEfYJaLS+SA2O0AAAAASUVORK5CYII=",this.size=16,this.load()}load(){return this._imageSource=new Pe(this.fontSheet),this._imageSource.load().then((()=>{this._spriteSheet=Oe.fromImageSource({image:this._imageSource,grid:{rows:3,columns:16,spriteWidth:16,spriteHeight:16}}),this._spriteFont=new Ue({alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ,!'&.\"?-()+ ",caseInsensitive:!0,spriteSheet:this._spriteSheet,spacing:-6})}))}write(t,e,i){this._imageSource.isLoaded()&&this._spriteFont.render(t,e,i.x,i.y)}}class Ne{constructor(t){this._webglCtx=t,this._debugText=new He}drawRect(t,e,i,s,n={color:T.Black}){this.drawLine(S(t,e),S(t+i,e),{...n}),this.drawLine(S(t+i,e),S(t+i,e+s),{...n}),this.drawLine(S(t+i,e+s),S(t,e+s),{...n}),this.drawLine(S(t,e+s),S(t,e),{...n})}drawLine(t,e,i={color:T.Black}){this._webglCtx.__lineRenderer.addLine(t,e,i.color)}drawPoint(t,e={color:T.Black,size:5}){this._webglCtx.__pointRenderer.addPoint(t,e.color,e.size)}drawText(t,e){this._debugText.write(this._webglCtx,t,e)}}class We{constructor(t){this._transform=new et,this._state=new it,this.snapToPixel=!0,this.smoothing=!1,this.backgroundColor=T.ExcaliburBlue,this.debug=new Ne(this);const{canvasElement:e,enableTransparency:i,smoothing:s,snapToPixel:n,backgroundColor:r}=t;this.__gl=e.getContext("webgl",{antialias:null!=s?s:this.smoothing,premultipliedAlpha:!1,alpha:null==i||i,depth:!0,powerPreference:"high-performance"}),this.snapToPixel=null!=n?n:this.snapToPixel,this.smoothing=null!=s?s:this.smoothing,this.backgroundColor=null!=r?r:this.backgroundColor,this._init()}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get width(){return this.__gl.canvas.width}get height(){return this.__gl.canvas.height}checkIfResolutionSupported(t){const e=this.__gl,i=e.getParameter(e.MAX_TEXTURE_SIZE)/4;let s=!0;return(t.width>i||t.height>i)&&(s=!1),s}_init(){const t=this.__gl;this._ortho=tt.ortho(0,t.canvas.width,t.canvas.height,0,400,-400),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.__pointRenderer=new wt(t,{matrix:this._ortho,transform:this._transform,state:this._state}),this.__lineRenderer=new lt(t,{matrix:this._ortho,transform:this._transform,state:this._state}),this.__imageRenderer=new mt(t,{matrix:this._ortho,transform:this._transform,state:this._state}),this._canvas=new Ct({width:t.canvas.width,height:t.canvas.height}),this.__ctx=this._canvas.ctx}resetTransform(){this._transform.current=tt.identity()}updateViewport(){const t=this.__gl;this._ortho=this._ortho=tt.ortho(0,t.canvas.width,t.canvas.height,0,400,-400),this.__pointRenderer.shader.addUniformMatrix("u_matrix",this._ortho.data),this.__lineRenderer.shader.addUniformMatrix("u_matrix",this._ortho.data),this.__imageRenderer.shader.addUniformMatrix("u_matrix",this._ortho.data),this._canvas.width=t.canvas.width,this._canvas.height=t.canvas.height}drawImage(t,e,i,s,n,r,o,a,h){if(0!==s&&0!==n&&0!==a&&0!==h&&0!==t.width&&0!==t.height)return t?void this.__imageRenderer.addImage(t,e,i,s,n,r,o,a,h):(_.getInstance().warn("Cannot draw a null or undefined image"),void(console.trace&&console.trace()))}drawLine(t,e,i,s=1){this.__imageRenderer.addLine(i,t,e,s)}drawRectangle(t,e,i,s){this.__imageRenderer.addRectangle(s,t,e,i)}drawCircle(t,e,i){this.__imageRenderer.addCircle(t,e,i)}save(){this._transform.save(),this._state.save()}restore(){this._transform.restore(),this._state.restore()}translate(t,e){this._transform.translate(this.snapToPixel?~~t:t,this.snapToPixel?~~e:e)}rotate(t){this._transform.rotate(t)}scale(t,e){this._transform.scale(t,e)}transform(t){this._transform.current=t}clear(){const t=this.__gl;t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT),rt.clear()}flush(){const t=this.__gl;t.viewport(0,0,t.canvas.width,t.canvas.height),this.__imageRenderer.render(),this.__lineRenderer.render(),this.__pointRenderer.render()}}var Ve;!function(t){t.Fixed="Fixed",t.FitScreen="FitScreen",t.FillScreen="FillScreen",t.FitContainer="FitContainer",t.FillContainer="FillContainer",t.Position="Position"}(Ve||(Ve={}));class Ge{static get SVGA(){return{width:800,height:600}}static get Standard(){return{width:1920,height:1080}}static get Atari2600(){return{width:160,height:192}}static get GameBoy(){return{width:160,height:144}}static get GameBoyAdvance(){return{width:240,height:160}}static get NintendoDS(){return{width:256,height:192}}static get NES(){return{width:256,height:224}}static get SNES(){return{width:256,height:244}}}class Xe{constructor(t){var e,i,s;this._antialiasing=!0,this._resolutionStack=[],this._viewportStack=[],this._pixelRatioOverride=null,this._isFullScreen=!1,this._isDisposed=!1,this._logger=_.getInstance(),this._fullscreenChangeHandler=()=>{this._isFullScreen=!this._isFullScreen,this._logger.debug("Fullscreen Change",this._isFullScreen)},this._pixelRatioChangeHandler=()=>{this._logger.debug("Pixel Ratio Change",window.devicePixelRatio),this._devicePixelRatio=this._calculateDevicePixelRatio(),this.applyResolutionAndViewport()},this._resizeHandler=()=>{const t=this.parent;this._logger.debug("View port resized"),this._setResolutionAndViewportByDisplayMode(t),this.applyResolutionAndViewport()},this._devicePixelRatio=this._calculateDevicePixelRatio(),this._alreadyWarned=!1,this.viewport=t.viewport,this.resolution=null!==(e=t.resolution)&&void 0!==e?e:{...this.viewport},this._displayMode=null!==(i=t.displayMode)&&void 0!==i?i:Ve.Fixed,this._canvas=t.canvas,this._ctx=t.context,this._antialiasing=null!==(s=t.antialiasing)&&void 0!==s?s:this._antialiasing,this._browser=t.browser,this._position=t.position,this._pixelRatioOverride=t.pixelRatio,this._applyDisplayMode(),this._mediaQueryList=this._browser.window.nativeComponent.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._mediaQueryList.addEventListener?this._mediaQueryList.addEventListener("change",this._pixelRatioChangeHandler):this._mediaQueryList.addListener(this._pixelRatioChangeHandler),this._canvas.addEventListener("fullscreenchange",this._fullscreenChangeHandler),this.applyResolutionAndViewport()}dispose(){this._isDisposed||(this._isDisposed=!0,this._browser.window.off("resize",this._resizeHandler),this._resizeObserver&&this._resizeObserver.disconnect(),this.parent.removeEventListener("resize",this._resizeHandler),this._mediaQueryList.removeEventListener?this._mediaQueryList.removeEventListener("change",this._pixelRatioChangeHandler):this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._canvas.removeEventListener("fullscreenchange",this._fullscreenChangeHandler))}_calculateDevicePixelRatio(){if(window.devicePixelRatio<1)return 1;return window.devicePixelRatio||1}get pixelRatio(){return this._pixelRatioOverride?this._pixelRatioOverride:this._devicePixelRatio}get isHiDpi(){return 1!==this.pixelRatio}get displayMode(){return this._displayMode}get canvas(){return this._canvas}get parent(){return this.displayMode===Ve.FillContainer||this.displayMode===Ve.FitContainer?this.canvas.parentElement||document.body:window}get resolution(){return this._resolution}set resolution(t){this._resolution=t}get viewport(){return this._viewport?this._viewport:this._resolution}set viewport(t){this._viewport=t}get aspectRatio(){return this._resolution.width/this._resolution.height}get scaledWidth(){return this._resolution.width*this.pixelRatio}get scaledHeight(){return this._resolution.height*this.pixelRatio}setCurrentCamera(t){this._camera=t}pushResolutionAndViewport(){this._resolutionStack.push(this.resolution),this._viewportStack.push(this.viewport),this.resolution={...this.resolution},this.viewport={...this.viewport}}peekViewport(){return this._viewportStack[this._viewportStack.length-1]}peekResolution(){return this._resolutionStack[this._resolutionStack.length-1]}popResolutionAndViewport(){this.resolution=this._resolutionStack.pop(),this.viewport=this._viewportStack.pop()}applyResolutionAndViewport(){if(this._canvas.width=this.scaledWidth,this._canvas.height=this.scaledHeight,this._ctx instanceof We){this._ctx.checkIfResolutionSupported({width:this.scaledWidth,height:this.scaledHeight})||this._alreadyWarned||(this._alreadyWarned=!0,this._logger.warn(`The currently configured resolution (${this.resolution.width}x${this.resolution.height}) is too large for the platform WebGL implementation, this may work but cause WebGL rendering to behave oddly. Try reducing the resolution or disabling Hi DPI scaling to avoid this (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`))}this._antialiasing?this._canvas.style.imageRendering="auto":(this._canvas.style.imageRendering="pixelated",""===this._canvas.style.imageRendering&&(this._canvas.style.imageRendering="crisp-edges")),this._canvas.style.width=this.viewport.width+"px",this._canvas.style.height=this.viewport.height+"px",this._ctx.updateViewport(),this._ctx.resetTransform(),this._ctx.scale(this.pixelRatio,this.pixelRatio),this._ctx.smoothing=this._antialiasing}get antialiasing(){return this._antialiasing}set antialiasing(t){this._antialiasing=t,this._ctx.smoothing=this._antialiasing}get isFullScreen(){return this._isFullScreen}goFullScreen(){return this._canvas.requestFullscreen()}exitFullScreen(){return document.exitFullscreen()}pageToScreenCoordinates(t){let e=t.x,i=t.y;if(this._isFullScreen||(e-=W(this._canvas).x,i-=W(this._canvas).y),this._isFullScreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const t=window.innerWidth/this.aspectRatio;i=(i-(window.innerHeight-t)/2)/t*this.viewport.height,e=e/window.innerWidth*this.viewport.width}else{const t=window.innerHeight*this.aspectRatio;e=(e-(window.innerWidth-t)/2)/t*this.viewport.width,i=i/window.innerHeight*this.viewport.height}return e=e/this.viewport.width*this.resolution.width,i=i/this.viewport.height*this.resolution.height,new A(e,i)}screenToPageCoordinates(t){let e=t.x,i=t.y;if(e=e/this.resolution.width*this.viewport.width,i=i/this.resolution.height*this.viewport.height,this._isFullScreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const t=window.innerWidth/this.aspectRatio,s=(window.innerHeight-t)/2;i=i/this.viewport.height*t+s,e=e/this.viewport.width*window.innerWidth}else{const t=window.innerHeight*this.aspectRatio,s=(window.innerWidth-t)/2;e=e/this.viewport.width*t+s,i=i/this.viewport.height*window.innerHeight}return this._isFullScreen||(e+=W(this._canvas).x,i+=W(this._canvas).y),new A(e,i)}screenToWorldCoordinates(t){var e,i,s,n;let r=t.x,o=t.y;return r=r/this.resolution.width*this.drawWidth,o=o/this.resolution.height*this.drawHeight,r-=this.halfDrawWidth,o-=this.halfDrawHeight,r+=null!==(i=null===(e=this._camera)||void 0===e?void 0:e.x)&&void 0!==i?i:0,o+=null!==(n=null===(s=this._camera)||void 0===s?void 0:s.y)&&void 0!==n?n:0,new A(r,o)}worldToScreenCoordinates(t){var e,i,s,n;let r=t.x,o=t.y;return r-=null!==(i=null===(e=this._camera)||void 0===e?void 0:e.x)&&void 0!==i?i:0,o-=null!==(n=null===(s=this._camera)||void 0===s?void 0:s.y)&&void 0!==n?n:0,r+=this.halfDrawWidth,o+=this.halfDrawHeight,r=r/this.drawWidth*this.resolution.width,o=o/this.drawHeight*this.resolution.height,new A(r,o)}pageToWorldCoordinates(t){const e=this.pageToScreenCoordinates(t);return this.screenToWorldCoordinates(e)}worldToPageCoordinates(t){const e=this.worldToScreenCoordinates(t);return this.screenToPageCoordinates(e)}getWorldBounds(){const t=this.screenToWorldCoordinates(A.Zero).x,e=this.screenToWorldCoordinates(A.Zero).y,i=t+this.drawWidth,s=e+this.drawHeight;return new B(t,e,i,s)}get canvasWidth(){return this.canvas.width}get halfCanvasWidth(){return this.canvas.width/2}get canvasHeight(){return this.canvas.height}get halfCanvasHeight(){return this.canvas.height/2}get drawWidth(){return this._camera?this.resolution.width/this._camera.zoom:this.resolution.width}get halfDrawWidth(){return this.drawWidth/2}get drawHeight(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get halfDrawHeight(){return this.drawHeight/2}get center(){return S(this.halfDrawWidth,this.halfDrawHeight)}_computeFit(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=this.aspectRatio;let e=0,i=0;window.innerWidth/t<window.innerHeight?(e=window.innerWidth,i=window.innerWidth/t):(e=window.innerHeight*t,i=window.innerHeight),this.viewport={width:e,height:i}}_computeFitContainer(){const t=this.aspectRatio;let e=0,i=0;const s=this.canvas.parentElement;s.clientWidth/t<s.clientHeight?(e=s.clientWidth,i=s.clientWidth/t):(e=s.clientHeight*t,i=s.clientHeight),this.viewport={width:e,height:i}}_applyDisplayMode(){this.displayMode===Ve.Position?this._initializeDisplayModePosition(this._position):(this._setResolutionAndViewportByDisplayMode(this.parent),this.parent instanceof Window?this._browser.window.on("resize",this._resizeHandler):(this._resizeObserver=new ResizeObserver((()=>{this._resizeHandler()})),this._resizeObserver.observe(this.parent)),this.parent.addEventListener("resize",this._resizeHandler))}_setResolutionAndViewportByDisplayMode(t){this.displayMode===Ve.FillContainer&&(this.resolution={width:t.clientWidth,height:t.clientHeight},this.viewport=this.resolution),this.displayMode===Ve.FillScreen&&(document.body.style.margin="0px",document.body.style.overflow="hidden",this.resolution={width:t.innerWidth,height:t.innerHeight},this.viewport=this.resolution),this.displayMode===Ve.FitScreen&&this._computeFit(),this.displayMode===Ve.FitContainer&&this._computeFitContainer()}_initializeDisplayModePosition(t){if(!t)throw new Error("DisplayMode of Position was selected but no position option was given");if(this.canvas.style.display="block",this.canvas.style.position="absolute","string"==typeof t){const e=t.split(" ");switch(e[0]){case"top":this.canvas.style.top="0px";break;case"bottom":this.canvas.style.bottom="0px";break;case"middle":this.canvas.style.top="50%";const t=-this.halfDrawHeight;this.canvas.style.marginTop=t.toString();break;default:throw new Error("Invalid Position Given")}if(e[1])switch(e[1]){case"left":this.canvas.style.left="0px";break;case"right":this.canvas.style.right="0px";break;case"center":this.canvas.style.left="50%";const t=-this.halfDrawWidth;this.canvas.style.marginLeft=t.toString();break;default:throw new Error("Invalid Position Given")}}else t.top&&("number"==typeof t.top?this.canvas.style.top=t.top.toString()+"px":this.canvas.style.top=t.top),t.right&&("number"==typeof t.right?this.canvas.style.right=t.right.toString()+"px":this.canvas.style.right=t.right),t.bottom&&("number"==typeof t.bottom?this.canvas.style.bottom=t.bottom.toString()+"px":this.canvas.style.bottom=t.bottom),t.left&&("number"==typeof t.left?this.canvas.style.left=t.left.toString()+"px":this.canvas.style.left=t.left)}}class je{static create(){return this._INSTANCE||(window.AudioContext||window.webkitAudioContext)&&(this._INSTANCE=new AudioContext),this._INSTANCE}}je._INSTANCE=null;class qe{static unlock(){return new Promise(((t,e)=>{if(qe._UNLOCKED||!je.create())return t(!0);const i=setTimeout((()=>{_.getInstance().warn("Excalibur was unable to unlock the audio context, audio probably will not play in this browser."),t(!1)}),200),s=je.create();s.resume().then((()=>{const e=s.createBuffer(1,1,22050),n=s.createBufferSource();let r=!1;n.buffer=e,n.connect(s.destination),n.onended=()=>r=!0,n.start(0),setTimeout((()=>{!function(t){return!!t.playbackState}(n)?(s.currentTime>0||r)&&(qe._UNLOCKED=!0):n.playbackState!==n.PLAYING_STATE&&n.playbackState!==n.FINISHED_STATE||(qe._UNLOCKED=!0)}),0),clearTimeout(i),t(!0)}),(()=>{e()}))}))}static isUnlocked(){return this._UNLOCKED}}qe._UNLOCKED=!1;class Ke{constructor(){this.eventDispatcher=new he}on(t,e){this.eventDispatcher.on(t,e)}off(t,e){this.eventDispatcher.off(t,e)}emit(t,e){this.eventDispatcher.emit(t,e)}once(t,e){this.eventDispatcher.once(t,e)}}function Ze(t,e=T.Red,i,s,n,r,o=1,a="butt"){t.beginPath(),t.lineWidth=o,t.lineCap=a,t.strokeStyle=e.toString(),t.moveTo(i,s),t.lineTo(n,r),t.closePath(),t.stroke()}function Ye(t,e=T.Red,i){t.beginPath(),t.strokeStyle=e.toString(),t.arc(i.x,i.y,5,0,2*Math.PI),t.closePath(),t.stroke()}function Qe(t,e,i,s,n=1){const r=e?e.toString():"blue",o=s.scale(n);t.beginPath(),t.strokeStyle=r,t.moveTo(i.x,i.y),t.lineTo(i.x+o.x,i.y+o.y),t.closePath(),t.stroke()}function $e(t,e,i,s,n,r=5,o=T.White,a=null){let h;if("number"==typeof r)h={tl:r,tr:r,br:r,bl:r};else{const t={tl:0,tr:0,br:0,bl:0};for(const e in t)if(t.hasOwnProperty(e)){const i=e;h[i]=r[i]||t[i]}}t.beginPath(),t.moveTo(e+h.tl,i),t.lineTo(e+s-h.tr,i),t.quadraticCurveTo(e+s,i,e+s,i+h.tr),t.lineTo(e+s,i+n-h.br),t.quadraticCurveTo(e+s,i+n,e+s-h.br,i+n),t.lineTo(e+h.bl,i+n),t.quadraticCurveTo(e,i+n,e,i+n-h.bl),t.lineTo(e,i+h.tl),t.quadraticCurveTo(e,i,e+h.tl,i),t.closePath(),a&&(t.fillStyle=a.toString(),t.fill()),o&&(t.strokeStyle=o.toString(),t.stroke())}function Je(t,e,i,s,n=T.White,r=null){t.beginPath(),t.arc(e,i,s,0,2*Math.PI),t.closePath(),r&&(t.fillStyle=r.toString(),t.fill()),n&&(t.strokeStyle=n.toString(),t.stroke())}var ti=i(1388);class ei extends Ke{constructor(t){super(),this.canvas=new Ct({smoothing:!0,draw:this.draw.bind(this)}),this._resourceList=[],this._index=0,this._playButtonShown=!1,this._resourceCount=0,this._numLoaded=0,this._progressCounts={},this._totalCounts={},this.logo="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdQAAAB2CAYAAABxhGI9AAAACXBIWXMAAAsSAAALEgHS3X78AAAKnUlEQVR42u3dP2wjSx0H8N8hJIonIRmJjsq0SBR+BQ1dcqKhe0lD77SvSwpKkJKGPulpktfRIMUdEqKIqV57rpAokM4dbSiyq7ONPTP7x39ifz7SFbnEnp3xer47O7uzH15fXwMA6OYHmgAABCoACFQAEKgAgEAFAIEKAAIVAAQqACBQAUCgAoBABQCBCgAIVAAQqAAgUAFAoAIAAhUABCoACFQAEKgAgECFLbmOiNeFf2PbAyz68Pr6qhUgbRwR92v+/zwiJrYHMEKFMmcN///UtgcQqFBk1PD/97U9Qx8VCFSgu4EmAIEKAAIVAAQqACBQ4Z25jojP8eX+0WtNAgIVaOY+Im5j+eKh24h41jQgUIEyZ7F5NaPU7wCBCiwYd/w9cOB+qAlgJ3KLLow0EV198803RWvJfvfddx+0lhEqHKu5JgAjVCBvlhmFzjQRXUekHz9+TP79y8uLRjNChXfvoePvAYEKxNtj1e42/O5JoIJABcrdRMRVLM+X3kTEpaaB988cKuzWg9EobTWdMx0Oly8uN4dqhAoARqgnaN3arHfqu7OyH8ItKLVB/P+CEfMTHyGPY3npx1m8zWGDEeoBfUk/xdti57dr/r1Wv2+6EPow3tZ5rRdS72s1neuF97xvWd+XTH0/V+UMttDWqbI/r2nrxfp+jv2uSjSO7S+OXy/A/3lN+9xX5T5HxEUPZZ0tfB71+w57eJ/HFu+z+jkv1u92YX9fbI/HhX3JA9rp5MPr66tWaG9UfUGbrHIzi7cLUyYFf/tpTady03EEeL8mUJ6i7MKYNvWNqr4Pe2jradXO60LrvPAz2PQ5RPX684ah8dxD+2zantnCgVipSVV+m/tgB9W2DDq2Sx/vM95wcHhZhWVJm8yrv58cSgfTdc70+++/X/r522+/tUKSEepBqo+om4ZLPerMjUwuNnQCtx1GWJtee1FwdD5uWd86xLs8UaVt2aNEO1/saZ/Z5rYMW4zq6v34rGV9Bg3q2eZ9SkeNm9qwyUh30OPIHYFKx5FG03C7znSOqYBq+qW/zpQ3anH037TNHluG6f0WPsPhHvab4QFty7ogOeuxDYcNy2/zu2214WNYWxmBurNO8bGn97pNBOO8xy/9uCorZZ4I2r4C7aJgO7ZV9iE49Dm6NvOWx+pWE9CUq3zbdTp9doz38TbXtzqH9RT5CyWe422OaZoZGeZCabrhPQY9HjwsjpTvCg4YtlE2+Ta/j2bzn8fqrDqgm+6yUHOmAvWUjAtGhbNYvsBknDnqH1Qhc7VmxHgeb/NbudA5j/UXlYwif2p6luhAc9teu1npiHKnDs8if6tCm7JLX3NKpgttXe9ruc9mHMd7a83iwdxF5vt8tutARaCeklRnNK9C8WnNF7geJQ4T4XG3JhSnVdilQrG+yOnrlVHfsEGYzhNBn7Lu6tS7+HJafJQ4EMiNlNqWXZ9WPvVgnVYHG5M1ByDXkT6leX2EgTqJtyt45yv7S2qO3sEZjZhDLXeR+YKdJ0Zdk8QocvH9N732KrNtq+FZ/zzIHABcJrYpd+Xv14lOd5ap76SgrduW/VTQ1qcQpqnbgu4ifZvUMNpd9XuoZmvCtPaQ2Y/BCHVLgbrJTeRPDdVf6pfMKDU2fOkHmVFFfXr3MsouLsnNvV5kRoe5+s431PeuoKPqWnaurY/ZPBEeqwceN4l96iwO6H7Mjq4y7VGPVNe10VaZMzVCPVWpI/Z6FZbcv5fMqGCU+dLfFGzj58jP8+bCdJCo7yzKTwdOF0bu9Ug7V4c+yz7FJfYeGoysUss0HssIdVZwYLDujMqlESoCdTtGsZtbHnJBeNdDSJSs0jTKdMJN1HNX54Wv7bvsU9NkVJVa13dX+/wuArV0X/l5RHyo/lnfF4G6p6DrS0kHdtXhy35TGErDPYZUn2WfWqDOo/lVqdMD2O/hKJhD7S/odukymq9s02QN4EEPR/zbaOumZc+r15zK1Zqznl9jsfiemTM1QmV3HUuTkedlg9HIQzRbUD93dfC+2tpj2fIHEH2+RqCCQH13gZq7hWXTNpVu19OB1fc9nQ0AKOKUb5lU0P1kDyOneoWk0lOZ9cIP0x7qu8+2BhCoR2wYu1+e7DmaXzBSsu5vaX1ne2zrpmUPTmxf7PM1Dm4y/vC7ny7Nif7+z/9ZmtM0Z3panPLtPmra9f16bcK0Dpbnwk43Vd/RHtu6zfNQTy1QBy3aqG2g9nVmxml+BOoJyT3NpWmn9xhfFnu4bvDa+44BXhqqfdf3uUF9+yz77AT31Yue2mjecYQ62NLfgkA9ghHqLNEhNem4H1c6vdyDxhf/bpz5m4coW/c39wi6VH2bPtHlcaV9cvXts+zxCe6rTeqc2ndL7uGd93QwM9bFcAzMoZZ7SgTBbWx+asui61h/iq1+RmjqdbnQXQ3T1DNQ63V/U9ucqm/pMzPb1rePsk/1iTOjgvatR4W3Lc8ULB78pELyrnAfeTcj1NU509/86mfJ33/8+Mf00a05UyPUEw7UVCeWG/WNEiExyHRMt5ltW30izUPk18ytt7lNfc8i//DvtvXto+ySA5BjljsLUF8lPkqMPEtW1JomDsiGBZ9Byb4NAvUITSN9GuwsIj6t6UTOqk7jJREkmzqli8xIs96udSO20sX0H1vW92IL9e1a9rgqVyf91gbPsTy9UD9n9lOkT8k+RfkFR5PMNqxOcdSf32PBvg3vilO+zdxE+okx9Wm0ph36XYsRZCpMF993GOk5qvqB3Dct6jvssb67KvuUNJ3frw92bhr8/STSF0JdRPMLpUCgnsgo9S76PZ246ZFk1wWvK5m3vVoYvW1Sz7nN91jfXbQ1ZQc7TW6HeaoOalypG/8/p/rP1aNAc6ZHzSnfdqPUPhdy2PQw6Nz9gSVhuhiqueUHR3uu7y7K3rdDX4u46ZrPbUa0IFBZ0seKQ3XQTRt2vm3W/a2DbNKys++rvm3ep6+y1x2UdP3bWU9lzra47U1GmlctX/sQ23t+aOlByLTh/4NAPaCRxtcdO5HLSJ/6vNtCwGx67VPmPbvWd1q9frKHtp4kAqRJ2HR9j762JfX3bZ//elPtj13PPDx1+D5tqk/Xi6NO8SHz7MmH19dXrdBNfVFP6T2PT1UHNit87/t4m5+aRH+nQBdvqyhZDKJLfZs8h7XPsqdV2ZOV+tanKB8aln0dyxdAXbV4j4gvt4oMOrbP6vbU73NW7TMlbdTnPrWpfqXfh9HKZ9vke7KuTeZRNtXRSe6+1FV//ce/ln5eXfsXgcqXzr6+9261M3moOoa7E6nvTZTfy7iNsmfb7kjfgXGsvxe0vihsEts9HTquPpt1q1vtahu2TqAiUAEEKj0zhwoARqgAu/OnX/442WH+9xc/Wvr58re/Tr7f41/+ZsRqhAoACFQAEKgAcHjMoQJskJsz/eqrr5Z+vvr7v5fmQFevAl5lztQIFQAQqAAgUAHgIJlDBdhgdQ41N2eKESoAIFABQKACwFEwhwoARqgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAEKgAgUAFAoAKAQAUAgQoACFQAEKgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAQqAAgUAFAoAKAQAUAlvwPcFDns1DsH4sAAAAASUVORK5CYII=",this.logoWidth=468,this.logoHeight=118,this.loadingBarColor=T.White,this.backgroundColor="#176BAA",this.suppressPlayButton=!1,this._playButtonStyles=ti.Z.toString(),this.playButtonText="Play game",this.startButtonFactory=()=>{let t=document.getElementById("excalibur-play");return t||(t=document.createElement("button")),t.id="excalibur-play",t.textContent=this.playButtonText,t.style.display="none",t},this._isLoadedPromise=new Promise((t=>{this._isLoadedResolve=t})),t&&this.addResources(t)}get _image(){return this._imageElement||(this._imageElement=new Image,this._imageElement.src=this.logo),this._imageElement}get playButtonRootElement(){return this._playButtonRootElement}get playButtonElement(){return this._playButtonElement}get _playButton(){const t=document.getElementById("excalibur-play-root");return t&&(this._playButtonRootElement=t),this._playButtonRootElement||(this._playButtonRootElement=document.createElement("div"),this._playButtonRootElement.id="excalibur-play-root",this._playButtonRootElement.style.position="absolute",document.body.appendChild(this._playButtonRootElement)),this._styleBlock||(this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._playButtonStyles,document.head.appendChild(this._styleBlock)),this._playButtonElement||(this._playButtonElement=this.startButtonFactory(),this._playButtonRootElement.appendChild(this._playButtonElement)),this._playButtonElement}wireEngine(t){this._engine=t,this.canvas.width=this._engine.canvas.width,this.canvas.height=this._engine.canvas.height}addResource(t){const e=this._index++;this._resourceList.push(t),this._progressCounts[e]=0,this._totalCounts[e]=1,this._resourceCount++}addResources(t){let e=0;const i=t.length;for(;e<i;e++)this.addResource(t[e])}isLoaded(){return this._numLoaded===this._resourceCount}async showPlayButton(){var t,e;if(!this.suppressPlayButton){const t=()=>{this._positionPlayButton()};(null===(e=this._engine)||void 0===e?void 0:e.browser)&&this._engine.browser.window.on("resize",t),this._playButtonShown=!0,this._playButton.style.display="block",document.body.addEventListener("keyup",(t=>{"Enter"===t.key&&this._playButton.click()})),this._positionPlayButton();const i=new Promise((e=>{const i=i=>{var s;i.stopPropagation(),this.hidePlayButton(),(null===(s=this._engine)||void 0===s?void 0:s.browser)&&this._engine.browser.window.off("resize",t),e()};this._playButton.addEventListener("click",i),this._playButton.addEventListener("touchend",i),this._playButton.addEventListener("pointerup",i)}));return await i}this.hidePlayButton(),await Q(500,null===(t=this._engine)||void 0===t?void 0:t.clock)}hidePlayButton(){this._playButtonShown=!1,this._playButton.style.display="none"}dispose(){this._playButtonRootElement.parentElement&&(this._playButtonRootElement.removeChild(this._playButtonElement),document.body.removeChild(this._playButtonRootElement),document.head.removeChild(this._styleBlock),this._playButtonRootElement=null,this._playButtonElement=null,this._styleBlock=null)}update(t,e){}areResourcesLoaded(){return this._isLoadedPromise}async load(){var t,e;return await(null===(t=this._image)||void 0===t?void 0:t.decode()),await Promise.all(this._resourceList.map((t=>t.load().finally((()=>{this._numLoaded++}))))),this._isLoadedResolve(),await Q(200,null===(e=this._engine)||void 0===e?void 0:e.clock),await this.showPlayButton(),await qe.unlock(),this.data=this._resourceList}markResourceComplete(){this._numLoaded++}get progress(){return this._resourceCount>0?L(this._numLoaded,0,this._resourceCount)/this._resourceCount:1}_positionPlayButton(){if(this._engine){const t=this._engine.screen.viewport.height,e=this._engine.screen.viewport.width;if(this._playButtonRootElement){const i=this._engine.canvas.offsetLeft,s=this._engine.canvas.offsetTop,n=this._playButton.clientWidth,r=this._playButton.clientHeight;this.playButtonPosition?(this._playButtonRootElement.style.left=`${this.playButtonPosition.x}px`,this._playButtonRootElement.style.top=`${this.playButtonPosition.y}px`):(this._playButtonRootElement.style.left=i+e/2-n/2+"px",this._playButtonRootElement.style.top=s+t/2-r/2+100+"px")}}}draw(t){const e=this._engine.canvasHeight/this._engine.pixelRatio,i=this._engine.canvasWidth/this._engine.pixelRatio;this._positionPlayButton(),t.fillStyle=this.backgroundColor,t.fillRect(0,0,i,e);let s=e/2;const n=Math.min(this.logoWidth,.75*i);let r=i/2-n/2;this.logoPosition&&(r=this.logoPosition.x,s=this.logoPosition.y);const o=Math.floor(n*(this.logoHeight/this.logoWidth)),a=this._engine.getAntialiasing();if(this._engine.setAntialiasing(!0),this.logoPosition?t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,r,s,n,o):t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,r,s-o-20,n,o),!this.suppressPlayButton&&this._playButtonShown)return void this._engine.setAntialiasing(a);let h=r,l=s;this.loadingBarPosition&&(h=this.loadingBarPosition.x,l=this.loadingBarPosition.y),t.lineWidth=2,$e(t,h,l,n,20,10,this.loadingBarColor);const c=n*this.progress-10;$e(t,h+5,l+5,c>10?c:10,10,5,null,this.loadingBarColor),this._engine.setAntialiasing(a)}}const ii={webgl:"WebGL",webaudio:"WebAudio",gamepadapi:"Gamepad API"};class si{constructor(){this._features=null,this.failedTests=[],this._criticalTests={canvasSupport:function(){const t=document.createElement("canvas");return!(!t.getContext||!t.getContext("2d"))},arrayBufferSupport:function(){const t=new XMLHttpRequest;t.open("GET","/");try{t.responseType="arraybuffer"}catch(t){return!1}return"arraybuffer"===t.responseType},dataUrlSupport:function(){return 0===document.createElement("canvas").toDataURL("image/png").indexOf("data:image/png")},objectUrlSupport:function(){return"URL"in window&&"revokeObjectURL"in URL&&"createObjectURL"in URL},rgbaSupport:function(){const t=document.createElement("a").style;return t.cssText="background-color:rgba(150,255,150,.5)",(""+t.backgroundColor).indexOf("rgba")>-1}},this._warningTest={webAudioSupport:function(){return!!(window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext)},webglSupport:function(){const t=document.createElement("canvas");return!(!t.getContext||!t.getContext("webgl"))}},this._features=this._loadBrowserFeatures()}getBrowserFeatures(){return null===this._features&&(this._features=this._loadBrowserFeatures()),this._features}logBrowserFeatures(){let t="%cSUPPORTED BROWSER FEATURES\n==========================%c\n";const e=["font-weight: bold; color: navy","font-weight: normal; color: inherit"],i=this.getBrowserFeatures();for(const s of Object.keys(ii))i[s]?(t+="(%c✓%c)",e.push("font-weight: bold; color: green"),e.push("font-weight: normal; color: inherit")):(t+="(%c✗%c)",e.push("font-weight: bold; color: red"),e.push("font-weight: normal; color: inherit")),t+=" "+ii[s]+"\n";e.unshift(t),console.log.apply(console,e)}_loadBrowserFeatures(){return{canvas:(()=>this._criticalTests.canvasSupport())(),arraybuffer:(()=>this._criticalTests.arrayBufferSupport())(),dataurl:(()=>this._criticalTests.dataUrlSupport())(),objecturl:(()=>this._criticalTests.objectUrlSupport())(),rgba:(()=>this._criticalTests.rgbaSupport())(),webaudio:(()=>this._warningTest.webAudioSupport())(),webgl:(()=>this._warningTest.webglSupport())(),gamepadapi:!!navigator.getGamepads}}test(){let t=!1;for(const e in this._criticalTests)this._criticalTests[e].call(this)||(this.failedTests.push(e),_.getInstance().error("Critical browser feature missing, Excalibur requires:",e),t=!0);if(t)return!1;for(const t in this._warningTest)this._warningTest[t]()||_.getInstance().warn("Warning browser feature missing, Excalibur will have reduced performance:",t);return!0}}var ni;!function(t){t.PreventCollision="PreventCollision",t.Passive="Passive",t.Active="Active",t.Fixed="Fixed"}(ni||(ni={}));var ri,oi,ai,hi=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};!function(t){t.Arcade="arcade",t.Realistic="realistic"}(ri||(ri={})),function(t){t[t.DynamicAABBTree=0]="DynamicAABBTree"}(oi||(oi={})),function(t){t[t.Euler=0]="Euler"}(ai||(ai={}));class li{static get gravity(){return li.acc}static set gravity(t){li.acc=t}static useArcadePhysics(){li.collisionResolutionStrategy=ri.Arcade}static useRealisticPhysics(){li.collisionResolutionStrategy=ri.Realistic}static get dynamicTreeVelocityMultiplyer(){return li.dynamicTreeVelocityMultiplier}static set dynamicTreeVelocityMultiplyer(t){li.dynamicTreeVelocityMultiplier=t}}li.acc=new A(0,0),li.enabled=!0,li.broadphaseStrategy=oi.DynamicAABBTree,li.collisionResolutionStrategy=ri.Arcade,li.defaultMass=10,li.integrator=ai.Euler,li.dynamicTreeVelocityMultiplier=2,li.boundsPadding=5,li.positionIterations=3,li.velocityIterations=8,li.slop=1,li.steeringFactor=.2,li.warmStart=!0,li.bodiesCanSleepByDefault=!1,li.surfaceEpsilon=.1,li.sleepEpsilon=.07,li.wakeThreshold=3*li.sleepEpsilon,li.sleepBias=.9,li.checkForFastBodies=!0,li.disableMinimumSpeedForFastBody=!1,hi([b({message:"Alias for incorrect spelling used in older versions, will be removed in v0.25.0",alternateMethod:"dynamicTreeVelocityMultiplier"})],li,"dynamicTreeVelocityMultiplyer",null);class ci extends A{constructor(t){super(0,0),this._getX=t.getX,this._getY=t.getY,this._setX=t.setX,this._setY=t.setY}get x(){return this._x=this._getX()}set x(t){this._setX(t),this._x=t}get y(){return this._y=this._getY()}set y(t){this._setY(t),this._y=t}}class di{constructor(){this.owner=null}clone(){const t=new this.constructor;for(const i in this)if(this.hasOwnProperty(i)){const s=this[i];(null==(e=s)?void 0:e.clone)&&"owner"!==i&&"clone"!==i?t[i]=s.clone():t[i]=s}var e;return t}}class ui extends di{constructor(t,e){super(),this.type=t,this.value=e}}var pi;!function(t){t.World="world",t.Screen="screen"}(pi||(pi={}));class gi extends di{constructor(){super(...arguments),this.type="ex.transform",this._dirty=!1,this.matrix=tt.identity().translate(0,0).rotate(0).scale(1,1),this._position=(t=>{const e=t;return new ci({setX:t=>{e.data[$.X]=t},setY:t=>{e.data[$.Y]=t},getX:()=>e.data[$.X],getY:()=>e.data[$.Y]})})(this.matrix),this._rotation=0,this._scale=(t=>{const e=t;return new ci({setX:t=>{e.setScaleX(t)},setY:t=>{e.setScaleY(t)},getX:()=>e.getScaleX(),getY:()=>e.getScaleY()})})(this.matrix),this.coordPlane=pi.World,this.z=0}_recalculate(){this._rotation=this.matrix.getRotation(),this._dirty=!1}getGlobalMatrix(){return this.parent?this.parent.getGlobalMatrix().multm(this.matrix):this.matrix}getGlobalTransform(){return{pos:this.globalPos,scale:this.globalScale,rotation:this.globalRotation,z:this.z,coordPlane:this.coordPlane}}get parent(){var t,e;return null===(e=null===(t=null==this?void 0:this.owner)||void 0===t?void 0:t.parent)||void 0===e?void 0:e.get(gi)}get pos(){return this._dirty&&this._recalculate(),this._position}set pos(t){this.matrix.setPosition(t.x,t.y),this._dirty=!0}get dirty(){var t;if(null===(t=null==this?void 0:this.owner)||void 0===t?void 0:t.parent){return this.parent.dirty||this._dirty}return this._dirty}get globalPos(){const t=this.getGlobalMatrix();return new ci({getX:()=>t.data[$.X],getY:()=>t.data[$.Y],setX:e=>{var i;if(this.parent){const[s]=null===(i=this.parent)||void 0===i?void 0:i.getGlobalMatrix().getAffineInverse().multv([e,t.data[$.Y]]);this.matrix.data[$.X]=s}else this.matrix.data[$.X]=e},setY:e=>{var i;if(this.parent){const[,s]=null===(i=this.parent)||void 0===i?void 0:i.getGlobalMatrix().getAffineInverse().multv([t.data[$.X],e]);this.matrix.data[$.Y]=s}else this.matrix.data[$.Y]=e}})}set globalPos(t){const e=this.parent;this.pos=e?e.getGlobalMatrix().getAffineInverse().multv(t):t}get rotation(){return this._dirty&&this._recalculate(),this._rotation}set rotation(t){this.matrix.setRotation(t),this._dirty=!0}get globalRotation(){return this.getGlobalMatrix().getRotation()}set globalRotation(t){const e=this.parent;this.rotation=e?t-e.globalRotation:t}get scale(){return this._dirty&&this._recalculate(),this._scale}set scale(t){this.matrix.setScale(t),this._dirty=!0}get globalScale(){const t=this.getGlobalMatrix();return new ci({getX:()=>t.getScaleX(),getY:()=>t.getScaleY(),setX:t=>{if(this.parent){const e=this.parent.globalScale.x;this.matrix.setScaleX(t/e)}else this.matrix.setScaleX(t)},setY:t=>{if(this.parent){const e=this.parent.globalScale.y;this.matrix.setScaleY(t/e)}else this.matrix.setScaleY(t)}})}set globalScale(t){const e=this.parent;this.scale=e?S(t.x/e.globalScale.x,t.y/e.globalScale.y):t}apply(t){return this.matrix.multv(t)}applyInverse(t){return this.matrix.getAffineInverse().multv(t)}}class _i extends di{constructor(){super(...arguments),this.type="ex.motion",this.vel=A.Zero,this.acc=A.Zero,this.scaleFactor=A.Zero,this.angularVelocity=0,this.torque=0,this.inertia=1}}class mi{constructor(t,e,i){this._name=t,this._category=e,this._mask=i}get name(){return this._name}get category(){return this._category}get mask(){return this._mask}canCollide(t){return 0!=(this.category&t.mask)&&0!=(t.category&this.mask)}invert(){return new mi("~("+this.name+")",~this.category,~this.mask)}static combine(t){const e=t.map((t=>t.name)).join("+"),i=t.reduce(((t,e)=>e.category|t),0);return new mi(e,i,~i)}static collidesWith(t){return mi.combine(t).invert()}}mi.All=new mi("Collide with all groups",-1,-1);class fi{constructor(){this.observers=[],this.subscriptions=[]}register(t){this.observers.push(t)}subscribe(t){this.subscriptions.push(t)}unregister(t){const e=this.observers.indexOf(t);-1!==e&&this.observers.splice(e,1)}unsubscribe(t){const e=this.subscriptions.indexOf(t);-1!==e&&this.subscriptions.splice(e,1)}notifyAll(t){this.observers.forEach((e=>e.notify(t))),this.subscriptions.forEach((e=>e(t)))}clear(){this.observers.length=0,this.subscriptions.length=0}}class wi{constructor(t,e){this.colliderA=t,this.colliderB=e,this.id=null,this.id=wi.calculatePairHash(t.id,e.id)}static canCollide(t,e){var i,s;const n=null===(i=null==t?void 0:t.owner)||void 0===i?void 0:i.get(Oi),r=null===(s=null==e?void 0:e.owner)||void 0===s?void 0:s.get(Oi);return t.id!==e.id&&((!t.owner||!e.owner||t.owner.id!==e.owner.id)&&(!t.localBounds.hasZeroDimensions()&&!e.localBounds.hasZeroDimensions()&&(!(!n||!r)&&(!!n.group.canCollide(r.group)&&((n.collisionType!==ni.Fixed||r.collisionType!==ni.Fixed)&&(r.collisionType!==ni.PreventCollision&&n.collisionType!==ni.PreventCollision&&!(!n.active||!r.active)))))))}get canCollide(){const t=this.colliderA,e=this.colliderB;return wi.canCollide(t,e)}collide(){return this.colliderA.collide(this.colliderB)}hasCollider(t){return t===this.colliderA||t===this.colliderB}static calculatePairHash(t,e){return t.value<e.value?`#${t.value}+${e.value}`:`#${e.value}+${t.value}`}}class yi{constructor(t,e){this.min=t,this.max=e}overlaps(t){return this.max>t.min&&t.max>this.min}getOverlap(t){return this.overlaps(t)?this.max>t.max?t.max-this.min:this.max-t.min:0}}class vi{constructor(t){this.parent=t,this.parent=t||null,this.data=null,this.bounds=new B,this.left=null,this.right=null,this.height=0}isLeaf(){return!this.left&&!this.right}}class xi{constructor(t=new B(-Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)){this.worldBounds=t,this.root=null,this.nodes={}}_insert(t){if(null===this.root)return this.root=t,void(this.root.parent=null);const e=t.bounds;let i=this.root;for(;!i.isLeaf();){const t=i.left,s=i.right,n=i.bounds.getPerimeter(),r=i.bounds.combine(e).getPerimeter(),o=2*r,a=2*(r-n);let h=0;const l=e.combine(t.bounds);let c,d;t.isLeaf()?h=l.getPerimeter()+a:(d=t.bounds.getPerimeter(),c=l.getPerimeter(),h=c-d+a);let u=0;const p=e.combine(s.bounds);if(s.isLeaf()?u=p.getPerimeter()+a:(d=s.bounds.getPerimeter(),c=p.getPerimeter(),u=c-d+a),o<h&&o<u)break;i=h<u?t:s}const s=i.parent,n=new vi(s);n.bounds=e.combine(i.bounds),n.height=i.height+1,null!==s?(s.left===i?s.left=n:s.right=n,n.left=i,n.right=t,i.parent=n,t.parent=n):(n.left=i,n.right=t,i.parent=n,t.parent=n,this.root=n);let r=t.parent;for(;r;){if(r=this._balance(r),!r.left)throw new Error("Parent of current leaf cannot have a null left child"+r);if(!r.right)throw new Error("Parent of current leaf cannot have a null right child"+r);r.height=1+Math.max(r.left.height,r.right.height),r.bounds=r.left.bounds.combine(r.right.bounds),r=r.parent}}_remove(t){if(t===this.root)return void(this.root=null);const e=t.parent,i=e.parent;let s;if(s=e.left===t?e.right:e.left,i){i.left===e?i.left=s:i.right=s,s.parent=i;let t=i;for(;t;)t=this._balance(t),t.bounds=t.left.bounds.combine(t.right.bounds),t.height=1+Math.max(t.left.height,t.right.height),t=t.parent}else this.root=s,s.parent=null}trackCollider(t){const e=new vi;e.data=t,e.bounds=t.bounds,e.bounds.left-=2,e.bounds.top-=2,e.bounds.right+=2,e.bounds.bottom+=2,this.nodes[t.id.value]=e,this._insert(e)}updateCollider(t){var e;const i=this.nodes[t.id.value];if(!i)return!1;const s=t.bounds;if(!this.worldBounds.contains(s))return _.getInstance().warn("Collider with id "+t.id.value+" is outside the world bounds and will no longer be tracked for physics"),this.untrackCollider(t),!1;if(i.bounds.contains(s))return!1;if(this._remove(i),s.left-=li.boundsPadding,s.top-=li.boundsPadding,s.right+=li.boundsPadding,s.bottom+=li.boundsPadding,t.owner){const i=null===(e=t.owner)||void 0===e?void 0:e.get(Oi);if(i){const t=32*i.vel.x/1e3*li.dynamicTreeVelocityMultiplier,e=32*i.vel.y/1e3*li.dynamicTreeVelocityMultiplier;t<0?s.left+=t:s.right+=t,e<0?s.top+=e:s.bottom+=e}}return i.bounds=s,this._insert(i),!0}untrackCollider(t){const e=this.nodes[t.id.value];e&&(this._remove(e),this.nodes[t.id.value]=null,delete this.nodes[t.id.value])}_balance(t){if(null===t)throw new Error("Cannot balance at null node");if(t.isLeaf()||t.height<2)return t;const e=t.left,i=t.right,s=t,n=e,r=i,o=e.left,a=e.right,h=i.left,l=i.right,c=r.height-n.height;if(c>1)return r.left=s,r.parent=s.parent,s.parent=r,r.parent?r.parent.left===s?r.parent.left=r:r.parent.right=r:this.root=r,h.height>l.height?(r.right=h,s.right=l,l.parent=s,s.bounds=n.bounds.combine(l.bounds),r.bounds=s.bounds.combine(h.bounds),s.height=1+Math.max(n.height,l.height),r.height=1+Math.max(s.height,h.height)):(r.right=l,s.right=h,h.parent=s,s.bounds=n.bounds.combine(h.bounds),r.bounds=s.bounds.combine(l.bounds),s.height=1+Math.max(n.height,h.height),r.height=1+Math.max(s.height,l.height)),r;if(c<-1){if(n.left=s,n.parent=s.parent,s.parent=n,n.parent)if(n.parent.left===s)n.parent.left=n;else{if(n.parent.right!==s)throw"Error rotating Dynamic Tree";n.parent.right=n}else this.root=n;return o.height>a.height?(n.right=o,s.left=a,a.parent=s,s.bounds=r.bounds.combine(a.bounds),n.bounds=s.bounds.combine(o.bounds),s.height=1+Math.max(r.height,a.height),n.height=1+Math.max(s.height,o.height)):(n.right=a,s.left=o,o.parent=s,s.bounds=r.bounds.combine(o.bounds),n.bounds=s.bounds.combine(a.bounds),s.height=1+Math.max(r.height,o.height),n.height=1+Math.max(s.height,a.height)),n}return t}getHeight(){return null===this.root?0:this.root.height}query(t,e){const i=t.bounds,s=n=>{if(n&&n.bounds.intersect(i)){if(!n.isLeaf()||n.data===t)return s(n.left)||s(n.right);if(e.call(t,n.data))return!0}return!1};s(this.root)}rayCastQuery(t,e=1/0,i){const s=n=>{if(n&&n.bounds.rayCast(t,e)){if(!n.isLeaf())return s(n.left)||s(n.right);if(i.call(t,n.data))return!0}return!1};s(this.root)}getNodes(){const t=e=>e?[e].concat(t(e.left),t(e.right)):[];return t(this.root)}debug(t){const e=i=>{i&&(i.isLeaf()?i.bounds.draw(t,T.Green):i.bounds.draw(t,T.White),i.left&&e(i.left),i.right&&e(i.right))};e(this.root)}}class bi{constructor(t,e){this.pos=t,this.dir=e.normalize()}intersect(t){const e=t.begin.sub(this.pos);if(0===this.dir.cross(t.getSlope())&&0!==e.cross(this.dir))return-1;const i=this.dir.cross(t.getSlope());if(0===i)return-1;const s=e.cross(t.getSlope())/i;if(s>=0){const n=e.cross(this.dir)/i/t.getLength();if(n>=0&&n<=1)return s}return-1}intersectPoint(t){const e=this.intersect(t);return e<0?null:this.getPoint(e)}getPoint(t){return this.pos.add(this.dir.scale(t))}}class Ci{constructor(){this._dynamicCollisionTree=new xi,this._pairs=new Set,this._collisionPairCache=[],this._colliders=[]}getColliders(){return this._colliders}track(t){if(t)if(t instanceof Si){const e=t.getColliders();for(const i of e)i.owner=t.owner,this._colliders.push(i),this._dynamicCollisionTree.trackCollider(i)}else this._colliders.push(t),this._dynamicCollisionTree.trackCollider(t);else _.getInstance().warn("Cannot track null collider")}untrack(t){if(t)if(t instanceof Si){const e=t.getColliders();for(const t of e){const e=this._colliders.indexOf(t);-1!==e&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}}else{const e=this._colliders.indexOf(t);-1!==e&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}else _.getInstance().warn("Cannot untrack a null collider")}_pairExists(t,e){const i=wi.calculatePairHash(t.id,e.id);return this._pairs.has(i)}broadphase(t,e,i){const s=e/1e3,n=t.filter((t=>{var e,i;const s=null===(e=t.owner)||void 0===e?void 0:e.get(Oi);return(null===(i=t.owner)||void 0===i?void 0:i.active)&&s.collisionType!==ni.PreventCollision}));let r;this._collisionPairCache=[],this._pairs.clear();for(let t=0,e=n.length;t<e;t++)r=n[t],this._dynamicCollisionTree.query(r,(t=>{if(!this._pairExists(r,t)&&wi.canCollide(r,t)){const e=new wi(r,t);this._pairs.add(e.id),this._collisionPairCache.push(e)}return!1}));if(i&&(i.physics.pairs=this._collisionPairCache.length),li.checkForFastBodies)for(const t of n){const e=t.owner.get(Oi);if(e.collisionType!==ni.Active)continue;const n=e.vel.size*s+.5*e.acc.size*s*s,r=Math.min(t.bounds.height,t.bounds.width);if(li.disableMinimumSpeedForFastBody||n>r/2){i&&i.physics.fastBodies++;const s=e.pos.sub(e.oldPos),r=t.center,o=t.getFurthestPoint(e.vel),a=o.sub(s),h=new bi(a,e.vel);let l;h.pos=h.pos.add(h.dir.scale(-2*li.surfaceEpsilon));let c=new A(1/0,1/0);if(this._dynamicCollisionTree.rayCastQuery(h,n+2*li.surfaceEpsilon,(e=>{if(!this._pairExists(t,e)&&wi.canCollide(t,e)){const t=e.rayCast(h,n+10*li.surfaceEpsilon);if(t){const i=t.sub(a);i.size<c.size&&(c=i,l=e)}}return!1})),l&&A.isValid(c)){const s=new wi(t,l);this._pairs.has(s.id)||(this._pairs.add(s.id),this._collisionPairCache.push(s));const n=r.sub(o);e.pos=a.add(n).add(c).add(h.dir.scale(10*li.surfaceEpsilon)),t.update(e.transform),i&&i.physics.fastBodyCollisions++}}}return this._collisionPairCache}narrowphase(t,e){let i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();if(i=i.concat(n),e&&n.length>0)for(const t of n)e.physics.contacts.set(t.id,t)}return e&&(e.physics.collisions+=i.length),i}update(t){let e=0;const i=t.length;for(let s=0;s<i;s++)this._dynamicCollisionTree.updateCollider(t[s])&&e++;return e}debug(t){this._dynamicCollisionTree.debug(t)}}class Ai{constructor(){this.id=g("collider",Ai._ID++),this.events=new he}touching(t){return!!this.collide(t)}}Ai._ID=0;class Si extends Ai{constructor(t){super(),this._collisionProcessor=new Ci,this._dynamicAABBTree=new xi,this._colliders=[];for(const e of t)this.addCollider(e)}clearColliders(){this._colliders=[]}addCollider(t){this.events.wire(t.events),this._colliders.push(t),this._collisionProcessor.track(t),this._dynamicAABBTree.trackCollider(t)}removeCollider(t){this.events.unwire(t.events),G(t,this._colliders),this._collisionProcessor.untrack(t),this._dynamicAABBTree.untrackCollider(t)}getColliders(){return this._colliders}get worldPos(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:A.Zero}get center(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:A.Zero}get bounds(){var t,e;const i=this.getColliders();return i.reduce(((t,e)=>t.combine(e.bounds)),null!==(e=null===(t=i[0])||void 0===t?void 0:t.bounds)&&void 0!==e?e:(new B).translate(this.worldPos))}get localBounds(){var t,e;const i=this.getColliders();return i.reduce(((t,e)=>t.combine(e.localBounds)),null!==(e=null===(t=i[0])||void 0===t?void 0:t.localBounds)&&void 0!==e?e:new B)}get axes(){const t=this.getColliders();let e=[];for(const i of t)e=e.concat(i.axes);return e}getFurthestPoint(t){const e=this.getColliders(),i=[];for(const s of e)i.push(s.getFurthestPoint(t));let s=i[0],n=-Number.MAX_VALUE;for(const e of i){const i=e.dot(t);i>n&&(s=e,n=i)}return s}getInertia(t){const e=this.getColliders();let i=0;for(const s of e)i+=s.getInertia(t);return i}collide(t){let e=[t];t instanceof Si&&(e=t.getColliders());const i=[];for(const t of e)this._dynamicAABBTree.query(t,(e=>(i.push(new wi(t,e)),!1)));let s=[];for(const t of i)s=s.concat(t.collide());return s}getClosestLineBetween(t){const e=this.getColliders(),i=[];if(t instanceof Si){const s=t.getColliders();for(const t of e)for(const e of s){const s=t.getClosestLineBetween(e);s&&i.push(s)}}else for(const s of e){const e=t.getClosestLineBetween(s);e&&i.push(e)}if(i.length){let t=i[0].getLength(),e=i[0];for(const s of i){const i=s.getLength();i<t&&(t=i,e=s)}return e}return null}contains(t){const e=this.getColliders();for(const i of e)if(i.contains(t))return!0;return!1}rayCast(t,e){const i=this.getColliders(),s=[];for(const n of i){const i=n.rayCast(t,e);i&&s.push(i)}if(s.length){let e=s[0],i=e.dot(t.dir);for(const n of s){const s=t.dir.dot(n);s<i&&(e=n,i=s)}return e}return null}project(t){const e=this.getColliders(),i=[];for(const s of e){const e=s.project(t);e&&i.push(e)}if(i.length){const t=new yi(i[0].min,i[0].max);for(const e of i)t.min=Math.min(e.min,t.min),t.max=Math.max(e.max,t.max);return t}return null}update(t){if(t){const e=this.getColliders();for(const i of e)i.owner=this.owner,i.update(t)}}draw(t,e,i){const s=this.getColliders();for(const n of s)n.draw(t,e,i)}debug(t,e){const i=this.getColliders();for(const s of i)s.debug(t,e)}debugDraw(t,e){const i=this.getColliders();for(const s of i)s.draw(t,e)}clone(){return new Si(this._colliders.map((t=>t.clone())))}}class Pi{constructor(t,e){this.begin=t,this.end=e}get slope(){return(this.end.y-this.begin.y)/(this.end.x-this.begin.x)}get intercept(){return this.begin.y-this.slope*this.begin.x}normal(){return this.end.sub(this.begin).normal()}dir(){return this.end.sub(this.begin)}getPoints(){return[this.begin,this.end]}getSlope(){const t=this.begin,e=this.end,i=t.distance(e);return e.sub(t).scale(1/i)}getEdge(){const t=this.begin;return this.end.sub(t)}getLength(){const t=this.begin,e=this.end;return t.distance(e)}get midpoint(){return this.begin.add(this.end).scale(.5)}flip(){return new Pi(this.end,this.begin)}below(t){return(this.end.x-this.begin.x)*(t.y-this.begin.y)-(this.end.y-this.begin.y)*(t.x-this.begin.x)>=0}clip(t,e){let i=t;i=i.normalize();const s=i.dot(this.begin)-e,n=i.dot(this.end)-e,r=[];if(s<=0&&r.push(this.begin),n<=0&&r.push(this.end),s*n<0){const t=s/(s-n);r.push(this.begin.add(this.end.sub(this.begin).scale(t)))}return 2!==r.length?null:new Pi(r[0],r[1])}distanceToPoint(t,e=!1){const i=t.x,s=t.y,n=this.getLength(),r=((this.end.y-this.begin.y)*i-(this.end.x-this.begin.x)*s+this.end.x*this.begin.y-this.end.y*this.begin.x)/n;return e?r:Math.abs(r)}findVectorToPoint(t){const e=this.begin.sub(t),i=this.getSlope();return e.sub(i.scale(e.dot(i)))}findPoint(t=null,e=null){const i=this.slope,s=this.intercept;if(null!==t)return new A(t,i*t+s);if(null!==e)return new A((e-s)/i,e);throw new Error("You must provide an X or a Y value")}hasPoint(){let t,e=0;if("number"==typeof arguments[0]&&"number"==typeof arguments[1])t=new A(arguments[0],arguments[1]),e=arguments[2]||0;else{if(!(arguments[0]instanceof A))throw"Could not determine the arguments for Vector.hasPoint";t=arguments[0],e=arguments[1]||0}const i=t.x-this.begin.x,s=t.y-this.begin.y,n=this.end.x-this.begin.x,r=this.end.y-this.begin.y,o=i*r-s*n;return!(Math.abs(o)>e)&&(Math.abs(n)>=Math.abs(r)?n>0?this.begin.x<=t.x&&t.x<=this.end.x:this.end.x<=t.x&&t.x<=this.begin.x:r>0?this.begin.y<=t.y&&t.y<=this.end.y:this.end.y<=t.y&&t.y<=this.begin.y)}}function Ei(t,e,i,s){const n=t.sub(i),r=e.dot(e),o=e.dot(s),a=s.dot(s),h=e.dot(n),l=s.dot(n),c=r*a-o*o;let d=c,u=c;if(0===c||c<=.01){const e=h/o;return new Pi(t,i.add(s.scale(e)))}let p=o*l-a*h,g=r*l-o*h;return p<0?(p=0,g=l,u=a):p>d&&(p=d,g=l+o,u=a),g<0?(g=0,-h<0?p=0:-h>r?p=d:(p=-h,d=r)):g>u&&(g=u,-h+o<0?p=0:-h+o>r?p=d:(p=-h+o,d=r)),p=Math.abs(p)<.001?0:p/d,g=Math.abs(g)<.001?0:g/u,new Pi(t.add(e.scale(p)),i.add(s.scale(g)))}const Ti={PolygonPolygonClosestLine(t,e){const i=e.worldPos,s=i.sub(t.worldPos),n=s.negate(),r=new bi(t.worldPos,s),o=new bi(i,n),a=t.rayCast(r).add(r.dir.scale(.1)),h=e.rayCast(o).add(o.dir.scale(.1)),l=t.getClosestFace(a),c=e.getClosestFace(h);return Ei(l.face.begin,l.face.getEdge(),c.face.begin,c.face.getEdge())},PolygonEdgeClosestLine(t,e){const i=e.worldPos.sub(t.worldPos),s=new bi(t.worldPos,i),n=t.rayCast(s).add(s.dir.scale(.1)),r=t.getClosestFace(n),o=r.face.begin,a=r.face.getEdge(),h=e.asLine();return Ei(o,a,h.begin,h.getEdge())},PolygonCircleClosestLine(t,e){const i=e.worldPos,s=i.sub(t.worldPos),n=new bi(t.worldPos,s.normalize()),r=t.rayCast(n).add(n.dir.scale(.1)),o=t.getClosestFace(r),a=o.face.begin,h=o.face.getEdge();let l=(h.x*(i.x-a.x)+h.y*(i.y-a.y))/(h.x*h.x+h.y*h.y);l>1?l=1:l<0&&(l=0);const c=Math.sqrt(Math.pow(a.x+h.x*l-i.x,2)+Math.pow(a.y+h.y*l-i.y,2))-e.radius,d=(a.x+h.x*l-i.x)*e.radius/(e.radius+c),u=(a.y+h.y*l-i.y)*e.radius/(e.radius+c);return new Pi(h.scale(l).add(a),new A(i.x+d,i.y+u))},CircleCircleClosestLine(t,e){const i=e.worldPos.sub(t.worldPos),s=t.worldPos.sub(e.worldPos),n=new bi(t.worldPos,i),r=new bi(e.worldPos,s),o=t.rayCast(n),a=e.rayCast(r);return new Pi(o,a)},CircleEdgeClosestLine(t,e){const i=t.worldPos,s=e.asLine(),n=s.begin,r=s.getEdge();let o=(r.x*(i.x-n.x)+r.y*(i.y-n.y))/(r.x*r.x+r.y*r.y);o>1?o=1:o<0&&(o=0);const a=Math.sqrt(Math.pow(n.x+r.x*o-i.x,2)+Math.pow(n.y+r.y*o-i.y,2))-t.radius,h=(n.x+r.x*o-i.x)*t.radius/(t.radius+a),l=(n.y+r.y*o-i.y)*t.radius/(t.radius+a);return new Pi(r.scale(o).add(n),new A(i.x+h,i.y+l))},EdgeEdgeClosestLine(t,e){const i=t.asLine(),s=i.begin,n=i.getEdge(),r=e.asLine();return Ei(s,n,r.begin,r.getEdge())}};class Ri extends Ai{constructor(t){super(),this.offset=A.Zero,this.offset=t.offset||A.Zero,this.radius=t.radius||0}get worldPos(){var t,e;return this.offset.add(null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:A.Zero)}clone(){return new Ri({offset:this.offset.clone(),radius:this.radius})}get center(){var t,e;return this.offset.add(null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos)&&void 0!==e?e:A.Zero)}contains(t){var e,i;return(null!==(i=null===(e=this._transform)||void 0===e?void 0:e.pos)&&void 0!==i?i:this.offset).distance(t)<=this.radius}rayCast(t,e=1/0){const i=this.center,s=t.dir,n=t.pos,r=Math.sqrt(Math.pow(s.dot(n.sub(i)),2)-Math.pow(n.sub(i).distance(),2)+Math.pow(this.radius,2));if(r<0)return null;{let o=0;if(0===r)return o=-s.dot(n.sub(i)),o>0&&o<e?t.getPoint(o):null;{const o=-s.dot(n.sub(i))+r,a=-s.dot(n.sub(i))-r,h=[];o>=0&&h.push(o),a>=0&&h.push(a);const l=Math.min(...h);return l<=e?t.getPoint(l):null}}}getClosestLineBetween(t){if(t instanceof Ri)return Ti.CircleCircleClosestLine(this,t);if(t instanceof ki)return Ti.PolygonCircleClosestLine(t,this).flip();if(t instanceof Fi)return Ti.CircleEdgeClosestLine(this,t).flip();throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ri)return Di.CollideCircleCircle(this,t);if(t instanceof ki)return Di.CollideCirclePolygon(this,t);if(t instanceof Fi)return Di.CollideCircleEdge(this,t);throw new Error("Circle could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){return this.center.add(t.normalize().scale(this.radius))}getFurthestLocalPoint(t){return t.normalize().scale(this.radius)}get bounds(){var t;const e=this._transform,i=null!==(t=null==e?void 0:e.globalPos)&&void 0!==t?t:A.Zero;return new B(this.offset.x+i.x-this.radius,this.offset.y+i.y-this.radius,this.offset.x+i.x+this.radius,this.offset.y+i.y+this.radius)}get localBounds(){return new B(this.offset.x-this.radius,this.offset.y-this.radius,this.offset.x+this.radius,this.offset.y+this.radius)}get axes(){return[]}getInertia(t){return t*this.radius*this.radius/2}update(t){this._transform=t}project(t){const e=[],i=this.center.dot(t);return e.push(i),e.push(i+this.radius),e.push(i-this.radius),new yi(Math.min.apply(Math,e),Math.max.apply(Math,e))}draw(t,e=T.Green,i=A.Zero){const s=i.add(this.offset);t.beginPath(),t.fillStyle=e.toString(),t.arc(s.x,s.y,this.radius,0,2*Math.PI),t.closePath(),t.fill()}debug(t,e){const i=this._transform,s=(null==i?void 0:i.globalPos)?null==i?void 0:i.globalPos.add(this.offset):this.offset;t.drawCircle(s,this.radius,e)}debugDraw(t,e=T.Green){const i=this._transform,s=i?i.pos.add(this.offset):this.offset,n=i?i.rotation:0;t.beginPath(),t.strokeStyle=e.toString(),t.arc(s.x,s.y,this.radius,0,2*Math.PI),t.closePath(),t.stroke(),t.beginPath(),t.moveTo(s.x,s.y),t.lineTo(Math.cos(n)*this.radius+s.x,Math.sin(n)*this.radius+s.y),t.closePath(),t.stroke()}}class Bi{constructor(t,e,i,s,n,r,o,a){this._canceled=!1,this.colliderA=t,this.colliderB=e,this.mtv=i,this.normal=s,this.tangent=n,this.points=r,this.localPoints=o,this.info=a,this.id=wi.calculatePairHash(t.id,e.id)}matchAwake(){const t=this.colliderA.owner.get(Oi),e=this.colliderB.owner.get(Oi);t&&e&&t.sleeping!==e.sleeping&&(t.sleeping&&t.collisionType!==ni.Fixed&&e.sleepMotion>=li.wakeThreshold&&t.setSleeping(!1),e.sleeping&&e.collisionType!==ni.Fixed&&t.sleepMotion>=li.wakeThreshold&&e.setSleeping(!1))}isCanceled(){return this._canceled}cancel(){this._canceled=!0}}class Mi{static findPolygonPolygonSeparation(t,e){let i=-Number.MAX_VALUE,s=null,n=null,r=-1,o=null;const a=t.getSides(),h=t.getLocalSides();for(let t=0;t<a.length;t++){const h=a[t],l=h.normal(),c=e.getFurthestPoint(l.negate()),d=h.distanceToPoint(c,!0);d>i&&(i=d,s=h,n=l,r=t,o=c)}return{collider:t,separation:n?i:99,axis:n,side:s,localSide:h[r],sideId:r,point:o,localPoint:n?e.getFurthestLocalPoint(n.negate()):null}}static findCirclePolygonSeparation(t,e){const i=e.axes,s=e.center.sub(t.worldPos),n=e.getFurthestPoint(s.negate());i.push(n.sub(t.worldPos).normalize());let r=Number.MAX_VALUE,o=null,a=-1;for(let s=0;s<i.length;s++){const n=e.project(i[s]),h=t.project(i[s]),l=n.getOverlap(h);if(l<=0)return null;l<r&&(r=l,o=i[s],a=s)}return a<0?null:o.normalize().scale(r)}}const Di={CollideCircleCircle(t,e){const i=t.worldPos,s=e.worldPos,n=t.radius+e.radius,r=i.distance(s);if(r>n)return[];const o=n-r,a=s.sub(i).normalize(),h=a.perpendicular(),l=a.scale(o),c=t.getFurthestPoint(a),d=t.getFurthestLocalPoint(a);return[new Bi(t,e,l,a,h,[c],[d],{collider:t,separation:o,axis:a,point:c})]},CollideCirclePolygon(t,e){var i,s;let n=Mi.findCirclePolygonSeparation(t,e);if(!n)return[];const r=n.dot(e.center.sub(t.center));n=r<0?n.negate():n;const o=t.getFurthestPoint(n),a=(null!==(s=null===(i=t.owner)||void 0===i?void 0:i.get(gi))&&void 0!==s?s:new gi).applyInverse(o),h=n.normalize(),l={collider:t,separation:-n.size,axis:h,point:o,localPoint:a,side:e.findSide(h.negate()),localSide:e.findLocalSide(h.negate())};return[new Bi(t,e,n,h,h.perpendicular(),[o],[a],l)]},CollideCircleEdge(t,e){const i=t.center,s=e.asLine(),n=s.end.sub(s.begin),r=n.dot(s.end.sub(i)),o=n.dot(i.sub(s.begin)),a=e.asLine(),h=e.asLocalLine();if(o<=0){const n=s.begin.sub(i),r=n.dot(n);if(r>t.radius*t.radius)return[];const o=n.normalize(),l=t.radius-Math.sqrt(r),c={collider:t,separation:l,axis:o,point:a.begin,side:a,localSide:h};return[new Bi(t,e,o.scale(l),o,o.perpendicular(),[a.begin],[h.begin],c)]}if(r<=0){const n=s.end.sub(i),r=n.dot(n);if(r>t.radius*t.radius)return[];const o=n.normalize(),l=t.radius-Math.sqrt(r),c={collider:t,separation:l,axis:o,point:a.end,side:a,localSide:h};return[new Bi(t,e,o.scale(l),o,o.perpendicular(),[a.end],[h.end],c)]}const l=n.dot(n),c=s.begin.scale(r).add(s.end.scale(o)).scale(1/l),d=i.sub(c),u=d.dot(d);if(u>t.radius*t.radius)return[];let p=n.perpendicular();p.dot(i.sub(s.begin))<0&&(p.x=-p.x,p.y=-p.y),p=p.normalize();const g=t.radius-Math.sqrt(u),_=p.scale(g),m={collider:t,separation:g,axis:p,point:c,side:a,localSide:h};return[new Bi(t,e,_,p.negate(),p.negate().perpendicular(),[c],[c.sub(e.worldPos)],m)]},CollideEdgeEdge:()=>[],CollidePolygonEdge(t,e){var i;const s=t.center,n=e.center.sub(s).normalize(),r=new ki({points:[e.begin,e.end,e.end.add(n.scale(100)),e.begin.add(n.scale(100))],offset:e.offset});r.owner=e.owner;(null===(i=e.owner)||void 0===i?void 0:i.get(gi))&&r.update(e.owner.get(gi));const o=this.CollidePolygonPolygon(t,r);return o.length&&(o[0].colliderB=e,o[0].id=wi.calculatePairHash(t.id,e.id)),o},CollidePolygonPolygon(t,e){var i,s,n,r;const o=Mi.findPolygonPolygonSeparation(t,e);if(o.separation>0)return[];const a=Mi.findPolygonPolygonSeparation(e,t);if(a.separation>0)return[];const h=o.separation>a.separation?o:a,l=(h.collider===t?e:t).findSide(h.axis.negate()),c=h.side,d=c.dir().normalize(),u=l.clip(d.negate(),-d.dot(c.begin));let p=null;if(u&&(p=u.clip(d,d.dot(c.end))),p){const o=p.getPoints().filter((t=>c.below(t)));let a=h.axis,l=a.perpendicular();e.worldPos.sub(t.worldPos).dot(a)<0&&(a=a.negate(),l=a.perpendicular());let d=[];if(h.collider===t){const t=null!==(s=null===(i=e.owner)||void 0===i?void 0:i.get(gi))&&void 0!==s?s:new gi;d=o.map((e=>t.applyInverse(e)))}else{const e=null!==(r=null===(n=t.owner)||void 0===n?void 0:n.get(gi))&&void 0!==r?r:new gi;d=o.map((t=>e.applyInverse(t)))}return[new Bi(t,e,a.scale(-h.separation),a,l,o,d,h)]}return[]},FindContactSeparation(t,e){var i,s,n,r;const o=t.colliderA,a=null!==(s=null===(i=t.colliderA.owner)||void 0===i?void 0:i.get(gi))&&void 0!==s?s:new gi,h=t.colliderB,l=null!==(r=null===(n=t.colliderB.owner)||void 0===n?void 0:n.get(gi))&&void 0!==r?r:new gi;if(o instanceof Ri&&h instanceof Ri){return-(o.radius+h.radius-a.pos.distance(l.pos))}if(o instanceof ki&&h instanceof ki&&t.info.localSide){let i,s;return t.info.collider===o?(i=new Pi(a.apply(t.info.localSide.begin),a.apply(t.info.localSide.end)),s=l.apply(e)):(i=new Pi(l.apply(t.info.localSide.begin),l.apply(t.info.localSide.end)),s=a.apply(e)),i.distanceToPoint(s,!0)}if(o instanceof ki&&h instanceof Ri||h instanceof ki&&o instanceof Ri){const i=a.apply(e);if(t.info.side)return t.info.side.distanceToPoint(i,!0)}if(o instanceof Fi&&h instanceof ki||h instanceof Fi&&o instanceof ki){let i;if(i=t.info.collider===o?l.apply(e):a.apply(e),t.info.side)return t.info.side.distanceToPoint(i,!0)}if(o instanceof Ri&&h instanceof Fi||h instanceof Ri&&o instanceof Fi){const i=l.apply(e);let s;o instanceof Ri&&(s=o.getFurthestPoint(t.normal));const n=i.distance(s);if(t.info.side)return n>0?-n:0}return 0}};class Fi extends Ai{constructor(t){var e;super(),this.begin=t.begin||A.Zero,this.end=t.end||A.Zero,this.offset=null!==(e=t.offset)&&void 0!==e?e:A.Zero}clone(){return new Fi({begin:this.begin.clone(),end:this.end.clone()})}get worldPos(){var t;const e=this._transform;return null!==(t=null==e?void 0:e.globalPos.add(this.offset))&&void 0!==t?t:this.offset}get center(){return this.begin.average(this.end).add(this._getBodyPos())}_getBodyPos(){var t;const e=this._transform;return null!==(t=null==e?void 0:e.globalPos)&&void 0!==t?t:A.Zero}_getTransformedBegin(){const t=this._transform,e=t?t.globalRotation:0;return this.begin.rotate(e).add(this._getBodyPos())}_getTransformedEnd(){const t=this._transform,e=t?t.globalRotation:0;return this.end.rotate(e).add(this._getBodyPos())}getSlope(){const t=this._getTransformedBegin(),e=this._getTransformedEnd(),i=t.distance(e);return e.sub(t).scale(1/i)}getLength(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.distance(e)}contains(){return!1}rayCast(t,e=1/0){const i=this._getTransformedBegin().sub(t.pos);if(0===t.dir.cross(this.getSlope())&&0!==i.cross(t.dir))return null;const s=t.dir.cross(this.getSlope());if(0===s)return null;const n=i.cross(this.getSlope())/s;if(n>=0&&n<=e){const e=i.cross(t.dir)/s/this.getLength();if(e>=0&&e<=1)return t.getPoint(n)}return null}getClosestLineBetween(t){if(t instanceof Ri)return Ti.CircleEdgeClosestLine(t,this);if(t instanceof ki)return Ti.PolygonEdgeClosestLine(t,this).flip();if(t instanceof Fi)return Ti.EdgeEdgeClosestLine(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ri)return Di.CollideCircleEdge(t,this);if(t instanceof ki)return Di.CollidePolygonEdge(t,this);if(t instanceof Fi)return Di.CollideEdgeEdge();throw new Error("Edge could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){const e=this._getTransformedBegin(),i=this._getTransformedEnd();return t.dot(e)>0?e:i}_boundsFromBeginEnd(t,e,i=10){return new B(Math.min(t.x,e.x)-i,Math.min(t.y,e.y)-i,Math.max(t.x,e.x)+i,Math.max(t.y,e.y)+i)}get bounds(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return this._boundsFromBeginEnd(t,e)}get localBounds(){return this._boundsFromBeginEnd(this.begin,this.end)}asLine(){return new Pi(this._getTransformedBegin(),this._getTransformedEnd())}asLocalLine(){return new Pi(this.begin,this.end)}get axes(){const t=this._getTransformedEnd().sub(this._getTransformedBegin()).normal(),e=[];return e.push(t),e.push(t.negate()),e.push(t.normal()),e.push(t.normal().negate()),e}getInertia(t){const e=this.end.sub(this.begin).distance()/2;return t*e*e}update(t){this._transform=t}project(t){const e=[],i=[this._getTransformedBegin(),this._getTransformedEnd()],s=i.length;for(let n=0;n<s;n++)e.push(i[n].dot(t));return new yi(Math.min.apply(Math,e),Math.max.apply(Math,e))}draw(t,e=T.Green,i=A.Zero){const s=this.begin.add(i),n=this.end.add(i);t.strokeStyle=e.toString(),t.beginPath(),t.moveTo(s.x,s.y),t.lineTo(n.x,n.y),t.closePath(),t.stroke()}debug(t,e){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.drawLine(i,s,e,2),t.drawCircle(i,2,e),t.drawCircle(s,2,e)}debugDraw(t,e=T.Red){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.strokeStyle=e.toString(),t.beginPath(),t.moveTo(i.x,i.y),t.lineTo(s.x,s.y),t.closePath(),t.stroke()}}class ki extends Ai{constructor(t){var e;super(),this._transformedPoints=[],this._axes=[],this._sides=[],this._localSides=[],this.offset=null!==(e=t.offset)&&void 0!==e?e:A.Zero;const i=!!t.clockwiseWinding;this.points=(i?t.points.reverse():t.points)||[],this._calculateTransformation()}clone(){return new ki({offset:this.offset.clone(),points:this.points.map((t=>t.clone()))})}get worldPos(){return this._transform?this._transform.pos.add(this.offset):this.offset}get center(){return this.bounds.center}_calculateTransformation(){const t=this._transform,e=t?t.globalPos.add(this.offset):this.offset,i=t?t.globalRotation:0,s=t?t.globalScale:A.One,n=this.points.length;this._transformedPoints.length=0;for(let t=0;t<n;t++)this._transformedPoints[t]=this.points[t].scale(s).rotate(i).add(e)}getTransformedPoints(){return this._calculateTransformation(),this._transformedPoints}getSides(){if(this._sides.length)return this._sides;const t=[],e=this.getTransformedPoints(),i=e.length;for(let s=0;s<i;s++)t.push(new Pi(e[s],e[(s+1)%i]));return this._sides=t,this._sides}getLocalSides(){if(this._localSides.length)return this._localSides;const t=[],e=this.points,i=e.length;for(let s=0;s<i;s++)t.push(new Pi(e[s],e[(s+1)%i]));return this._localSides=t,this._localSides}findSide(t){const e=this.getSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=e[n],o=r.normal().dot(t);o>s&&(i=r,s=o)}return i}findLocalSide(t){const e=this.getLocalSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=e[n],o=r.normal().dot(t);o>s&&(i=r,s=o)}return i}get axes(){if(this._axes.length)return this._axes;const t=this.getSides().map((t=>t.normal()));return this._axes=t,this._axes}update(t){this._transform=t,this._sides.length=0,this._localSides.length=0,this._axes.length=0,this._transformedPoints.length=0,this.getTransformedPoints(),this.getSides(),this.getLocalSides()}contains(t){const e=new bi(t,new A(1,0));return this.getSides().reduce((function(t,i){return e.intersect(i)>=0?t+1:t}),0)%2!=0}getClosestLineBetween(t){if(t instanceof Ri)return Ti.PolygonCircleClosestLine(this,t);if(t instanceof ki)return Ti.PolygonPolygonClosestLine(this,t);if(t instanceof Fi)return Ti.PolygonEdgeClosestLine(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}collide(t){if(t instanceof Ri)return Di.CollideCirclePolygon(t,this);if(t instanceof ki)return Di.CollidePolygonPolygon(this,t);if(t instanceof Fi)return Di.CollidePolygonEdge(this,t);throw new Error("Polygon could not collide with unknown CollisionShape "+typeof t)}getFurthestPoint(t){const e=this.getTransformedPoints();let i=null,s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=t.dot(e[n]);r>s&&(s=r,i=e[n])}return i}getFurthestLocalPoint(t){const e=this.points;let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const r=t.dot(e[n]);r>s&&(s=r,i=e[n])}return i}getClosestFace(t){const e=this.getSides();let i=Number.POSITIVE_INFINITY,s=-1,n=-1;for(let r=0;r<e.length;r++){const o=e[r].distanceToPoint(t);o<i&&(i=o,s=r,n=o)}return-1!==s?{distance:e[s].normal().scale(n),face:e[s]}:null}get bounds(){var t,e,i;const s=this._transform,n=null!==(t=null==s?void 0:s.globalScale)&&void 0!==t?t:A.One,r=null!==(e=null==s?void 0:s.globalRotation)&&void 0!==e?e:0,o=(null!==(i=null==s?void 0:s.globalPos)&&void 0!==i?i:A.Zero).add(this.offset);return this.localBounds.scale(n).rotate(r).translate(o)}get localBounds(){return B.fromPoints(this.points)}getInertia(t){let e=0,i=0;for(let t=0;t<this.points.length;t++){const s=(t+1)%this.points.length,n=this.points[s].cross(this.points[t]);e+=n*(this.points[t].dot(this.points[t])+this.points[t].dot(this.points[s])+this.points[s].dot(this.points[s])),i+=n}return t/6*(e/i)}rayCast(t,e=1/0){const i=this.getSides(),s=i.length;let n=Number.MAX_VALUE,r=-1;for(let o=0;o<s;o++){const s=t.intersect(i[o]);s>=0&&s<n&&s<=e&&(n=s,r=o)}return r>=0?t.getPoint(n):null}project(t){const e=this.getTransformedPoints(),i=e.length;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let r=0;r<i;r++){const i=e[r].dot(t);s=Math.min(s,i),n=Math.max(n,i)}return new yi(s,n)}draw(t,e=T.Green,i=A.Zero){const s=i.add(this.offset);t.beginPath(),t.fillStyle=e.toString();const n=this.points[0].add(s);t.moveTo(n.x,n.y),this.points.map((t=>t.add(s))).forEach((function(e){t.lineTo(e.x,e.y)})),t.lineTo(n.x,n.y),t.closePath(),t.fill()}debug(t,e){const i=this.getTransformedPoints()[0],s=[i,...this.getTransformedPoints(),i];for(let i=0;i<s.length-1;i++)t.drawLine(s[i],s[i+1],e,2),t.drawCircle(s[i],2,e),t.drawCircle(s[i+1],2,e)}debugDraw(t,e=T.Red){t.beginPath(),t.strokeStyle=e.toString();const i=this.getTransformedPoints()[0];t.moveTo(i.x,i.y),this.getTransformedPoints().forEach((function(e){t.lineTo(e.x,e.y)})),t.lineTo(i.x,i.y),t.closePath(),t.stroke()}}class Ii{static Box(t,e,i=A.Half,s=A.Zero){return new ki({points:new B(-t*i.x,-e*i.y,t-t*i.x,e-e*i.y).getPoints(),offset:s})}static Polygon(t,e=!1,i=A.Zero){return new ki({points:t,offset:i,clockwiseWinding:e})}static Circle(t,e=A.Zero){return new Ri({radius:t,offset:e})}static Edge(t,e){return new Fi({begin:t,end:e})}static Capsule(t,e,i=A.Zero){const s=_.getInstance();t===e&&s.warn("A capsule collider with equal width and height is a circle, consider using a ex.Shape.Circle or ex.CircleCollider");if(e>=t){return new Si([Ii.Circle(t/2,S(0,-e/2+t/2).add(i)),Ii.Box(t,e-t,A.Half,i),Ii.Circle(t/2,S(0,e/2-t/2).add(i))])}return new Si([Ii.Circle(e/2,S(-t/2+e/2,0).add(i)),Ii.Box(t-e,e,A.Half,i),Ii.Circle(e/2,S(t/2-e/2,0).add(i))])}}class Li extends di{constructor(t){super(),this.type="ex.collider",this.events=new he,this.$colliderAdded=new fi,this.$colliderRemoved=new fi,this.set(t)}get(){return this._collider}set(t){return this.clear(),t&&(this._collider=t,this._collider.owner=this.owner,this.events.wire(t.events),this.$colliderAdded.notifyAll(t),this.update()),t}clear(){this._collider&&(this.events.unwire(this._collider.events),this.$colliderRemoved.notifyAll(this._collider),this._collider.owner=null,this._collider=null)}get bounds(){var t,e;return null!==(e=null===(t=this._collider)||void 0===t?void 0:t.bounds)&&void 0!==e?e:new B}get localBounds(){var t,e;return null!==(e=null===(t=this._collider)||void 0===t?void 0:t.localBounds)&&void 0!==e?e:new B}update(){var t;const e=null===(t=this.owner)||void 0===t?void 0:t.get(gi);this._collider&&(this._collider.owner=this.owner,e&&this._collider.update(e))}collide(t){let e=this._collider,i=t._collider;if(!e||!i)return[];let s=!1;if(i instanceof Si&&(e=i,i=this._collider,s=!0),this._collider){const n=e.collide(i);return n?(s&&n.forEach((e=>{e.mtv=e.mtv.negate(),e.normal=e.normal.negate(),e.tangent=e.normal.perpendicular(),e.colliderA=this._collider,e.colliderB=t._collider})),n):[]}return[]}onAdd(t){this._collider&&this.update(),this.events.on("precollision",(e=>{const i=e;t.events.emit("precollision",new qt(i.target.owner,i.other.owner,i.side,i.intersection))})),this.events.on("postcollision",(e=>{const i=e;t.events.emit("postcollision",new Kt(i.target.owner,i.other.owner,i.side,i.intersection))})),this.events.on("collisionstart",(e=>{const i=e;t.events.emit("collisionstart",new Jt(i.target.owner,i.other.owner,i.contact))})),this.events.on("collisionend",(e=>{const i=e;t.events.emit("collisionend",new te(i.target.owner,i.other.owner))}))}onRemove(){this.events.clear(),this.$colliderRemoved.notifyAll(this._collider)}useBoxCollider(t,e,i=A.Half,s=A.Zero){const n=Ii.Box(t,e,i,s);return this.set(n)}usePolygonCollider(t,e=A.Zero){const i=Ii.Polygon(t,!1,e);return this.set(i)}useCircleCollider(t,e=A.Zero){const i=Ii.Circle(t,e);return this.set(i)}useEdgeCollider(t,e){const i=Ii.Edge(t,e);return this.set(i)}useCompositeCollider(t){return this.set(new Si(t))}}var zi;!function(t){t.Rotation="rotation",t.X="x",t.Y="y"}(zi||(zi={}));class Oi extends di{constructor(t){var e,i,s;super(),this.type="ex.body",this.dependencies=[gi,_i],this.id=g("body",Oi._ID++),this.events=new he,this.collisionType=ni.PreventCollision,this.group=mi.All,this.mass=li.defaultMass,this.sleepMotion=5*li.sleepEpsilon,this.canSleep=li.bodiesCanSleepByDefault,this._sleeping=!1,this.bounciness=.2,this.friction=.99,this.useGravity=!0,this.limitDegreeOfFreedom=[],this.oldPos=new A(0,0),this.oldVel=new A(0,0),this.oldAcc=A.Zero,this.oldRotation=0,this.oldScale=A.One,t&&(this.collisionType=null!==(e=t.type)&&void 0!==e?e:this.collisionType,this.group=null!==(i=t.group)&&void 0!==i?i:this.group,this.useGravity=null!==(s=t.useGravity)&&void 0!==s?s:this.useGravity)}get inverseMass(){return this.collisionType===ni.Fixed?0:1/this.mass}get sleeping(){return this._sleeping}setSleeping(t){this._sleeping=t,t?(this.vel=A.Zero,this.acc=A.Zero,this.angularVelocity=0,this.sleepMotion=0):this.sleepMotion=5*li.sleepEpsilon}updateMotion(){this._sleeping&&this.setSleeping(!0);const t=this.vel.size*this.vel.size+Math.abs(this.angularVelocity*this.angularVelocity),e=li.sleepBias;this.sleepMotion=e*this.sleepMotion+(1-e)*t,this.sleepMotion=L(this.sleepMotion,0,10*li.sleepEpsilon),this.canSleep&&this.sleepMotion<li.sleepEpsilon&&this.setSleeping(!0)}get inertia(){const t=this.owner.get(Li);return(null==t?void 0:t.get())?t.get().getInertia(this.mass):0}get inverseInertia(){return this.collisionType===ni.Fixed?0:1/this.inertia}get active(){var t;return!!(null===(t=this.owner)||void 0===t?void 0:t.active)}get center(){return this.pos}get transform(){var t;return null===(t=this.owner)||void 0===t?void 0:t.get(gi)}get motion(){var t;return null===(t=this.owner)||void 0===t?void 0:t.get(_i)}get pos(){return this.transform.globalPos}set pos(t){this.transform.globalPos=t}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t}get torque(){return this.motion.torque}set torque(t){this.motion.torque=t}get rotation(){return this.transform.globalRotation}set rotation(t){this.transform.globalRotation=t}get scale(){return this.transform.globalScale}set scale(t){this.transform.globalScale=t}get sx(){return this.motion.scaleFactor.x}set sx(t){this.motion.scaleFactor.x=t}get sy(){return this.motion.scaleFactor.y}set sy(t){this.motion.scaleFactor.y=t}get rx(){return this.motion.angularVelocity}set rx(t){this.motion.angularVelocity=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}applyImpulse(t,e){if(this.collisionType!==ni.Active)return;const i=e.scale(this.inverseMass);if(this.limitDegreeOfFreedom.includes(zi.X)&&(i.x=0),this.limitDegreeOfFreedom.includes(zi.Y)&&(i.y=0),this.vel.addEqual(i),!this.limitDegreeOfFreedom.includes(zi.Rotation)){const i=t.sub(this.pos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}applyLinearImpulse(t){if(this.collisionType!==ni.Active)return;const e=t.scale(this.inverseMass);this.limitDegreeOfFreedom.includes(zi.X)&&(e.x=0),this.limitDegreeOfFreedom.includes(zi.Y)&&(e.y=0),this.vel=this.vel.add(e)}applyAngularImpulse(t,e){if(this.collisionType===ni.Active&&!this.limitDegreeOfFreedom.includes(zi.Rotation)){const i=t.sub(this.pos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}captureOldTransform(){this.oldVel.setTo(this.vel.x,this.vel.y),this.oldPos.setTo(this.pos.x,this.pos.y),this.oldAcc.setTo(this.acc.x,this.acc.y),this.oldScale.setTo(this.scale.x,this.scale.y),this.oldRotation=this.rotation}debugDraw(t){}}Oi._ID=0;class Ui{constructor(){this._topLeft=new A(0,0),this._topRight=new A(0,0),this._bottomLeft=new A(0,0),this._bottomRight=new A(0,0)}isSpriteOffScreen(t,e){const i=t.currentDrawing.drawWidth,s=t.currentDrawing.drawHeight,n=t.rotation,r=t.center,o=t.getGlobalPos();this._topLeft=S(o.x-i/2,o.y-s/2),this._topLeft=this._topLeft.rotate(n,r),this._topRight=S(o.x+i/2,o.y-s/2),this._topRight=this._topRight.rotate(n,r),this._bottomLeft=S(o.x-i/2,o.y+s/2),this._bottomLeft=this._bottomLeft.rotate(n,r),this._bottomRight=S(o.x+i/2,o.y+s/2),this._bottomRight=this._bottomRight.rotate(n,r);const a=e.worldToScreenCoordinates(this._topLeft),h=e.worldToScreenCoordinates(this._topRight),l=e.worldToScreenCoordinates(this._bottomLeft),c=e.worldToScreenCoordinates(this._bottomRight);this._xCoords=[],this._yCoords=[],this._xCoords.push(a.x,h.x,l.x,c.x),this._yCoords.push(a.y,h.y,l.y,c.y),this._xMin=Math.min.apply(null,this._xCoords),this._yMin=Math.min.apply(null,this._yCoords),this._xMax=Math.max.apply(null,this._xCoords),this._yMax=Math.max.apply(null,this._yCoords);const d=e.screenToWorldCoordinates(new A(this._xMin,this._yMin)),u=e.screenToWorldCoordinates(new A(this._xMax,this._yMax));this._xMinWorld=d.x,this._yMinWorld=d.y,this._xMaxWorld=u.x,this._yMaxWorld=u.y;const p=[new A(this._xMin,this._yMin),new A(this._xMax,this._yMin),new A(this._xMin,this._yMax),new A(this._xMax,this._yMax)];if(p[0].x<0&&p[1].x>e.canvas.clientWidth&&(p[0].y>0||p[2].y<e.canvas.clientHeight))return!1;if(p[0].y<0&&p[2].y>e.canvas.clientHeight&&(p[1].x>0||p[0].x<e.canvas.clientWidth))return!1;for(let t=0;t<p.length;t++)if(p[t].x>0&&p[t].y>0&&p[t].x<e.canvas.clientWidth&&p[t].y<e.canvas.clientHeight)return!1;return!0}debugDraw(t){t.beginPath(),t.strokeStyle=T.White.toString(),t.rect(this._xMinWorld,this._yMinWorld,this._xMaxWorld-this._xMinWorld,this._yMaxWorld-this._yMinWorld),t.stroke(),t.fillStyle=T.Red.toString(),t.beginPath(),t.arc(this._topLeft.x,this._topLeft.y,5,0,2*Math.PI),t.closePath(),t.fill(),t.fillStyle=T.Green.toString(),t.beginPath(),t.arc(this._topRight.x,this._topRight.y,5,0,2*Math.PI),t.closePath(),t.fill(),t.fillStyle=T.Blue.toString(),t.beginPath(),t.arc(this._bottomLeft.x,this._bottomLeft.y,5,0,2*Math.PI),t.closePath(),t.fill(),t.fillStyle=T.Magenta.toString(),t.beginPath(),t.arc(this._bottomRight.x,this._bottomRight.y,5,0,2*Math.PI),t.closePath(),t.fill()}}class Hi{constructor(){this.cullingBox=new Ui}update(t,e){const i=t.eventDispatcher;let s=!0;null!=t.currentDrawing&&(s=this.cullingBox.isSpriteOffScreen(t,e));let n=!1;e&&e.currentScene&&e.currentScene.camera&&e.currentScene.camera.viewport&&!t.parent&&(n=!e.currentScene.camera.viewport.intersect(t.collider.bounds)),t.isOffScreen?n&&s||(i.emit("enterviewport",new re(t)),t.removeComponent("offscreen")):n&&s&&(i.emit("exitviewport",new ne(t)),t.addComponent(new ui("offscreen")))}}class Ni{constructor(t){this.data=t,this.type="Component Added"}}function Wi(t){return!!t&&"Component Added"===t.type}class Vi{constructor(t){this.data=t,this.type="Component Removed"}}function Gi(t){return!!t&&"Component Removed"===t.type}class Xi extends Ke{constructor(t,e){if(super(),this.id=Xi._ID++,this._name="anonymous",this.active=!0,this._componentsToRemove=[],this._componentTypeToInstance=new Map,this._componentStringToInstance=new Map,this._tagsMemo=[],this._typesMemo=[],this.componentAdded$=new fi,this.componentRemoved$=new fi,this._parent=null,this.childrenAdded$=new fi,this.childrenRemoved$=new fi,this._children=[],this._isInitialized=!1,this._setName(e),t)for(const e of t)this.addComponent(e)}_setName(t){t&&(this._name=t)}get name(){return this._name}get events(){return this.eventDispatcher}kill(){this.active=!1}isKilled(){return!this.active}get tags(){return this._tagsMemo}hasTag(t){return this.tags.includes(t)}addTag(t){return this.addComponent(new ui(t))}removeTag(t,e=!1){return this.removeComponent(t,e)}get types(){return this._typesMemo}_rebuildMemos(){this._tagsMemo=Array.from(this._componentStringToInstance.values()).filter((t=>t instanceof ui)).map((t=>t.type)),this._typesMemo=Array.from(this._componentStringToInstance.keys())}getComponents(){return Array.from(this._componentStringToInstance.values())}_notifyAddComponent(t){this._rebuildMemos();const e=new Ni({component:t,entity:this});this.componentAdded$.notifyAll(e)}_notifyRemoveComponent(t){const e=new Vi({component:t,entity:this});this.componentRemoved$.notifyAll(e),this._rebuildMemos()}get parent(){return this._parent}get children(){return this._children}unparent(){this._parent&&(this._parent.removeChild(this),this._parent=null)}addChild(t){if(null!==t.parent)throw new Error("Entity already has a parent, cannot add without unparenting");if(this.getAncestors().includes(t))throw new Error("Cycle detected, cannot add entity");return this._children.push(t),t._parent=this,this.childrenAdded$.notifyAll(t),this}removeChild(t){return t.parent===this&&(G(t,this._children),t._parent=null,this.childrenRemoved$.notifyAll(t)),this}removeAllChildren(){return this.children.forEach((t=>{this.removeChild(t)})),this}getAncestors(){const t=[this];let e=this.parent;for(;e;)t.push(e),e=e.parent;return t.reverse()}getDescendants(){let t=[this],e=[this];for(;e.length>0;){const i=e.pop();e=e.concat(i.children),t=t.concat(i.children)}return t}clone(){const t=new Xi;for(const e of this.types)t.addComponent(this.get(e).clone());for(const e of this.children)t.addChild(e.clone());return t}addTemplate(t,e=!1){for(const i of t.getComponents())this.addComponent(i.clone(),e);for(const e of t.children)this.addChild(e.clone().addTemplate(e));return this}addComponent(t,e=!1){if(this.has(t.type)){if(!e)return this;this.removeComponent(t)}if(t.dependencies&&t.dependencies.length)for(const e of t.dependencies)this.addComponent(new e);t.owner=this;const i=t.constructor;return this._componentTypeToInstance.set(i,t),this._componentStringToInstance.set(t.type,t),t.onAdd&&t.onAdd(this),this._notifyAddComponent(t),this}removeComponent(t,e=!1){return e?"string"==typeof t?this._removeComponentByType(t):t instanceof di&&this._removeComponentByType(t.type):this._componentsToRemove.push(t),this}_removeComponentByType(t){if(this.has(t)){const e=this.get(t);e.owner=null,e.onRemove&&e.onRemove(this);const i=e.constructor;this._componentTypeToInstance.delete(i),this._componentStringToInstance.delete(e.type),this._notifyRemoveComponent(e)}}processComponentRemoval(){for(const t of this._componentsToRemove){const e="string"==typeof t?t:t.type;this._removeComponentByType(e)}this._componentsToRemove.length=0}has(t){return"string"==typeof t?this._componentStringToInstance.has(t):this._componentTypeToInstance.has(t)}get(t){return"string"==typeof t?this._componentStringToInstance.get(t):this._componentTypeToInstance.get(t)}get isInitialized(){return this._isInitialized}_initialize(t){this.isInitialized||(this.onInitialize(t),super.emit("initialize",new ee(t,this)),this._isInitialized=!0)}_preupdate(t,e){this.emit("preupdate",new It(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new Lt(t,e,this)),this.onPostUpdate(t,e)}onInitialize(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this._initialize(t),this._preupdate(t,e);for(const i of this.children)i.update(t,e);this._postupdate(t,e)}}Xi._ID=0;class ji extends di{constructor(t){var e;super(),this.draw=t,this.type="ex.canvas",this.draw=null!==(e=this.draw)&&void 0!==e?e:()=>{}}}function qi(t){return!!t.tick}class Ki{constructor(t,e){this._options=t,this._graphics=e,this.graphics=[]}get name(){return this._options.name}hide(t){if(t){let e=null;e=t instanceof yt?t:this._graphics.getGraphic(t),this.graphics=this.graphics.filter((t=>t.graphic!==e))}else this.graphics.length=0}show(t,e){let i;return e={...e},t instanceof yt?i=this._graphics.copyGraphics?t.clone():t:(i=this._graphics.getGraphic(t),i||_.getInstance().error(`No such graphic added to component named ${t}. These named graphics are available: `,this._graphics.getNames())),i?(this.graphics.push({graphic:i,options:e}),i):null}use(t,e){return e={...e},this.hide(),this.show(t,e)}get order(){return this._options.order}set order(t){this._options.order=t}get offset(){var t;return null!==(t=this._options.offset)&&void 0!==t?t:A.Zero}set offset(t){this._options.offset=t}get currentKeys(){var t;return null!==(t=this.name)&&void 0!==t?t:"anonymous"}}class Zi{constructor(t){this._component=t,this._layers=[],this._layerMap={},this.default=new Ki({name:"default",order:0},t),this._maybeAddLayer(this.default)}create(t){const e=new Ki(t,this._component);return this._maybeAddLayer(e)}get(t){return t?this._getLayer(t):this._layers}currentKeys(){const t=[];for(const e of this._layers)t.push(e.currentKeys);return t}has(t){return t in this._layerMap}_maybeAddLayer(t){return this._layerMap[t.name]?this._layerMap[t.name]:(this._layerMap[t.name]=t,this._layers.push(t),this._layers.sort(((t,e)=>t.order-e.order)),t)}_getLayer(t){return this._layerMap[t]}}class Yi extends di{constructor(t){super(),this.type="ex.graphics",this._graphics={},this.visible=!0,this.opacity=1,this.offset=A.Zero,this.anchor=A.Half,this.copyGraphics=!1,this._bounds=null,t={visible:this.visible,...t};const{current:e,anchor:i,opacity:s,visible:n,graphics:r,offset:o,copyGraphics:a,onPreDraw:h,onPostDraw:l}=t;this._graphics=r||{},this.offset=null!=o?o:this.offset,this.opacity=null!=s?s:this.opacity,this.anchor=null!=i?i:this.anchor,this.copyGraphics=null!=a?a:this.copyGraphics,this.onPreDraw=null!=h?h:this.onPreDraw,this.onPostDraw=null!=l?l:this.onPostDraw,this.visible=!!n,this.layers=new Zi(this),e&&this._graphics[e]&&this.show(this._graphics[e])}getGraphic(t){return this._graphics[t]}getNames(){return Object.keys(this._graphics)}get current(){return this.layers.default.graphics}get graphics(){return this._graphics}add(t,e){let i="default",s=null;return"string"==typeof t?(i=t,s=e):s=t,this._graphics[i]=this.copyGraphics?s.clone():s,"default"===i&&this.show("default"),s}show(t,e){return this.layers.default.show(t,e)}use(t,e){return this.layers.default.use(t,e)}hide(t){this.layers.default.hide(t)}set localBounds(t){this._bounds=t}get localBounds(){if(this._bounds)return this._bounds;let t=new B;for(const e of this.layers.get())for(const{graphic:i,options:s}of e.graphics){let n=this.anchor,r=this.offset;(null==s?void 0:s.anchor)&&(n=s.anchor),(null==s?void 0:s.offset)&&(r=s.offset);const o=i.localBounds,a=-o.width*i.scale.x*n.x+r.x,h=-o.height*i.scale.y*n.y+r.y;t=null==i?void 0:i.localBounds.translate(S(a+e.offset.x,h+e.offset.y)).combine(t)}return t}update(t,e=0){for(const i of this.layers.get())for(const{graphic:s}of i.graphics)qi(s)&&(null==s||s.tick(t,e))}}class Qi extends bt{constructor(t){super(t),this.width=t.width,this.height=t.height,this.rasterize()}clone(){return new Qi({width:this.width,height:this.height,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.color&&t.fillRect(0,0,this.width,this.height),this.strokeColor&&t.strokeRect(0,0,this.width,this.height)}}class $i extends bt{constructor(t){var e;super(t),this._radius=0,this.padding=null!==(e=t.padding)&&void 0!==e?e:2,this.radius=t.radius,this.rasterize()}get radius(){return this._radius}set radius(t){this._radius=t,this.width=2*this._radius,this.height=2*this._radius,this.flagDirty()}clone(){return new $i({radius:this.radius,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.radius>0&&(t.beginPath(),t.arc(this.radius,this.radius,this.radius,0,2*Math.PI),this.color&&t.fill(),this.strokeColor&&t.stroke())}}class Ji extends di{constructor(){super(...arguments),this.type="ex.pointer",this.useColliderShape=!0,this.useGraphicsBounds=!1}}var ts,es=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class is{static CreateReversibleEasingFunction(t){return(e,i,s,n)=>s<i?i-(t(e,s,i,n)-s):t(e,i,s,n)}static CreateReversableEasingFunction(t){return is.CreateReversibleEasingFunction(t)}static CreateVectorEasingFunction(t){return(e,i,s,n)=>new A(t(e,i.x,s.x,n),t(e,i.y,s.y,n))}}is.Linear=is.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*t/s+e)),is.EaseInQuad=is.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*(t/=s)*t+e)),is.EaseOutQuad=is.CreateReversibleEasingFunction(((t,e,i,s)=>-(i-=e)*(t/=s)*(t-2)+e)),is.EaseInOutQuad=is.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e,(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e))),is.EaseInCubic=is.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e)*(t/=s)*t*t+e)),is.EaseOutCubic=is.CreateReversibleEasingFunction(((t,e,i,s)=>(t/=s,(i-=e)*(--t*t*t+1)+e))),is.EaseInOutCubic=is.CreateReversibleEasingFunction(((t,e,i,s)=>(i-=e,(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e))),es([b({message:"Alias for incorrect spelling used in older versions, will be removed in v0.25.0",alternateMethod:"CreateReversibleEasingFunction"})],is,"CreateReversableEasingFunction",null);class ss{constructor(t){this._actions=[],this._completedActions=[],this._entity=t}add(t){this._actions.push(t)}remove(t){const e=this._actions.indexOf(t);this._actions.splice(e,1)}clearActions(){this._actions.length=0,this._completedActions.length=0,this._currentAction&&this._currentAction.stop()}getActions(){return this._actions.concat(this._completedActions)}hasNext(){return this._actions.length>0}isComplete(){return 0===this._actions.length}reset(){this._actions=this.getActions();const t=this._actions.length;for(let e=0;e<t;e++)this._actions[e].reset();this._completedActions=[]}update(t){this._actions.length>0&&(this._currentAction=this._actions[0],this._currentAction.update(t),this._currentAction.isComplete(this._entity)&&this._completedActions.push(this._actions.shift()))}}class ns{constructor(t,e,i){this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new vs(t),this._actionQueue=this._repeatContext.getQueue(),this._repeat=i,this._originalRepeat=i,this._repeatBuilder(this._repeatContext),this._repeat--}update(t){this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext),this._repeat--),this._actionQueue.update(t)}isComplete(){return this._stopped||this._repeat<=0&&this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._repeat=this._originalRepeat}}class rs{constructor(t,e){this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new vs(t),this._actionQueue=this._repeatContext.getQueue(),this._repeatBuilder(this._repeatContext)}update(t){this._stopped||(this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext)),this._actionQueue.update(t))}isComplete(){return this._stopped}stop(){this._stopped=!0,this._actionQueue.clearActions()}reset(){}}class os{constructor(t,e,i,s){if(this._started=!1,this._stopped=!1,this._entity=t,this._tx=t.get(gi),this._motion=t.get(_i),this._speed=s,this._offset=new A(e,i),s<=0)throw _.getInstance().error("Attempted to moveBy with speed less than or equal to zero : "+s),new Error("Speed must be greater than 0 pixels per second")}update(t){this._started||(this._started=!0,this._start=new A(this._tx.pos.x,this._tx.pos.y),this._end=this._start.add(this._offset),this._distance=this._offset.size,this._dir=this._end.sub(this._start).normalize()),this.isComplete(this._entity)?(this._tx.pos=S(this._end.x,this._end.y),this._motion.vel=S(0,0)):this._motion.vel=this._dir.scale(this._speed)}isComplete(t){const e=t.get(gi);return this._stopped||e.pos.distance(this._start)>=this._distance}stop(){this._motion.vel=S(0,0),this._stopped=!0}reset(){this._started=!1}}class as{constructor(t,e,i,s){this.entity=t,this._started=!1,this._stopped=!1,this._tx=t.get(gi),this._motion=t.get(_i),this._end=new A(e,i),this._speed=s}update(t){this._started||(this._started=!0,this._start=new A(this._tx.pos.x,this._tx.pos.y),this._distance=this._start.distance(this._end),this._dir=this._end.sub(this._start).normalize());const e=this._dir.scale(this._speed);this._motion.vel=S(e.x,e.y),this.isComplete(this.entity)&&(this._tx.pos=S(this._end.x,this._end.y),this._motion.vel=S(0,0))}isComplete(t){const e=t.get(gi);return this._stopped||new A(e.pos.x,e.pos.y).distance(this._start)>=this._distance}stop(){this._motion.vel=S(0,0),this._stopped=!0}reset(){this._started=!1}}!function(t){t[t.ShortestPath=0]="ShortestPath",t[t.LongestPath=1]="LongestPath",t[t.Clockwise=2]="Clockwise",t[t.CounterClockwise=3]="CounterClockwise"}(ts||(ts={}));class hs{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(gi),this._motion=t.get(_i),this._end=e,this._speed=i,this._rotationType=s||ts.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation;const t=Math.abs(this._end-this._start),e=F-t;switch(t>e?(this._shortDistance=e,this._longDistance=t):(this._shortDistance=t,this._longDistance=e),this._shortestPathIsPositive=(this._start-this._end+F)%F>=Math.PI,this._rotationType){case ts.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case ts.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case ts.Clockwise:this._direction=1,this._shortestPathIsPositive?this._distance=this._shortDistance:this._distance=this._longDistance;break;case ts.CounterClockwise:this._direction=-1,this._shortestPathIsPositive?this._distance=this._longDistance:this._distance=this._shortDistance}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1}}class ls{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(gi),this._motion=t.get(_i),this._speed=i,this._offset=e,this._rotationType=s||ts.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation,this._end=this._start+this._offset;const t=Math.abs(this._end-this._start),e=F-t;switch(t>e?(this._shortDistance=e,this._longDistance=t):(this._shortDistance=t,this._longDistance=e),this._shortestPathIsPositive=(this._start-this._end+F)%F>=Math.PI,this._rotationType){case ts.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case ts.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case ts.Clockwise:this._direction=1,this._shortDistance>=0?this._distance=this._shortDistance:this._distance=this._longDistance;break;case ts.CounterClockwise:this._direction=-1,this._shortDistance<=0?this._distance=this._shortDistance:this._distance=this._longDistance}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1}}class cs{constructor(t,e,i,s,n){this._started=!1,this._stopped=!1,this._tx=t.get(gi),this._motion=t.get(_i),this._endX=e,this._endY=i,this._speedX=s,this._speedY=n}update(t){if(this._started||(this._started=!0,this._startX=this._tx.scale.x,this._startY=this._tx.scale.y,this._distanceX=Math.abs(this._endX-this._startX),this._distanceY=Math.abs(this._endY-this._startY)),Math.abs(this._tx.scale.x-this._startX)>=this._distanceX)this._motion.scaleFactor.x=0;else{const t=this._endY<this._startY?-1:1;this._motion.scaleFactor.x=this._speedX*t}if(Math.abs(this._tx.scale.y-this._startY)>=this._distanceY)this._motion.scaleFactor.y=0;else{const t=this._endY<this._startY?-1:1;this._motion.scaleFactor.y=this._speedY*t}this.isComplete()&&(this._tx.scale=S(this._endX,this._endY),this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.y-this._startX)>=this._distanceX&&Math.abs(this._tx.scale.y-this._startY)>=this._distanceY}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1}}class ds{constructor(t,e,i,s){this._started=!1,this._stopped=!1,this._tx=t.get(gi),this._motion=t.get(_i),this._offset=new A(e,i),this._speedX=this._speedY=s}update(t){this._started||(this._started=!0,this._startScale=this._tx.scale.clone(),this._endScale=this._startScale.add(this._offset),this._distanceX=Math.abs(this._endScale.x-this._startScale.x),this._distanceY=Math.abs(this._endScale.y-this._startScale.y),this._directionX=this._endScale.x<this._startScale.x?-1:1,this._directionY=this._endScale.y<this._startScale.y?-1:1),this._motion.scaleFactor.x=this._speedX*this._directionX,this._motion.scaleFactor.y=this._speedY*this._directionY,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startScale.x)>=this._distanceX&&Math.abs(this._tx.scale.y-this._startScale.y)>=this._distanceY}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1}}class us{constructor(t){this._method=null,this._hasBeenCalled=!1,this._method=t}update(t){this._method(),this._hasBeenCalled=!0}isComplete(){return this._hasBeenCalled}reset(){this._hasBeenCalled=!1}stop(){this._hasBeenCalled=!0}}class ps{constructor(t,e,i,s,n){this.easingFcn=n,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=new A(0,0),this._lerpEnd=new A(0,0),this._initialized=!1,this._stopped=!1,this._distance=0,this._tx=t.get(gi),this._motion=t.get(_i),this._lerpDuration=s,this._lerpEnd=new A(e,i)}_initialize(){this._lerpStart=new A(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0,this._distance=this._lerpStart.distance(this._lerpEnd)}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;this._currentLerpTime<this._lerpDuration?(e=this._lerpEnd.x<this._lerpStart.x?this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),i=this._lerpEnd.y<this._lerpStart.y?this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration),this._motion.vel=S((e-this._tx.pos.x)/(t/1e3),(i-this._tx.pos.y)/(t/1e3))):(this._tx.pos=S(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=A.Zero)}isComplete(t){return this._stopped||new A(t.pos.x,t.pos.y).distance(this._lerpStart)>=this._distance}reset(){this._initialized=!1}stop(){this._motion.vel=S(0,0),this._stopped=!0}}class gs{constructor(t,e,i,s=1){this._timeVisible=0,this._timeNotVisible=0,this._elapsedTime=0,this._totalTime=0,this._stopped=!1,this._started=!1,this._graphics=t.get(Yi),this._timeVisible=e,this._timeNotVisible=i,this._duration=(e+i)*s}update(t){this._started||(this._started=!0),this._graphics&&(this._elapsedTime+=t,this._totalTime+=t,this._graphics.visible&&this._elapsedTime>=this._timeVisible&&(this._graphics.visible=!1,this._elapsedTime=0),!this._graphics.visible&&this._elapsedTime>=this._timeNotVisible&&(this._graphics.visible=!0,this._elapsedTime=0),this.isComplete()&&(this._graphics.visible=!0))}isComplete(){return this._stopped||this._totalTime>=this._duration}stop(){this._graphics&&(this._graphics.visible=!0),this._stopped=!0}reset(){this._started=!1,this._elapsedTime=0,this._totalTime=0}}class _s{constructor(t,e,i){this._multiplier=1,this._started=!1,this._stopped=!1,this._graphics=t.get(Yi),this._endOpacity=e,this._speed=i}update(t){this._graphics&&(this._started||(this._started=!0,this._endOpacity<this._graphics.opacity?this._multiplier=-1:this._multiplier=1),this._speed>0&&(this._graphics.opacity+=this._multiplier*(Math.abs(this._graphics.opacity-this._endOpacity)*t)/this._speed),this._speed-=t,this.isComplete()&&(this._graphics.opacity=this._endOpacity),_.getInstance().debug("[Action fade] Actor opacity:",this._graphics.opacity))}isComplete(){return this._stopped||Math.abs(this._graphics.opacity-this._endOpacity)<.05}stop(){this._stopped=!0}reset(){this._started=!1}}class ms{constructor(t){this._elapsedTime=0,this._started=!1,this._stopped=!1,this._delay=t}update(t){this._started||(this._started=!0),this._elapsedTime+=t}isComplete(){return this._stopped||this._elapsedTime>=this._delay}stop(){this._stopped=!0}reset(){this._elapsedTime=0,this._started=!1}}class fs{constructor(t){this._stopped=!1,this._entity=t}update(t){this._entity.get(xs).clearActions(),this._entity.kill(),this._stopped=!0}isComplete(){return this._stopped}stop(){}reset(){}}class ws{constructor(t,e,i){this._started=!1,this._stopped=!1,this._tx=t.get(gi),this._motion=t.get(_i),this._followTx=e.get(gi),this._followMotion=e.get(_i),this._current=new A(this._tx.pos.x,this._tx.pos.y),this._end=new A(this._followTx.pos.x,this._followTx.pos.y),this._maximumDistance=void 0!==i?i:this._current.distance(this._end),this._speed=0}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._followMotion.vel.x,2)+Math.pow(this._followMotion.vel.y,2));if(0!==e&&(this._speed=e),this._current=S(this._tx.pos.x,this._tx.pos.y),this._end=S(this._followTx.pos.x,this._followTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize(),this._distanceBetween>=this._maximumDistance){const t=this._dir.scale(this._speed);this._motion.vel=S(t.x,t.y)}else this._motion.vel=S(0,0);this.isComplete()&&(this._tx.pos=S(this._end.x,this._end.y),this._motion.vel=S(0,0))}stop(){this._motion.vel=S(0,0),this._stopped=!0}isComplete(){return this._stopped}reset(){this._started=!1}}class ys{constructor(t,e,i){this._started=!1,this._stopped=!1,this._speedWasSpecified=!1,this._tx=t.get(gi),this._motion=t.get(_i),this._meetTx=e.get(gi),this._meetMotion=e.get(_i),this._current=new A(this._tx.pos.x,this._tx.pos.y),this._end=new A(this._meetTx.pos.x,this._meetTx.pos.y),this._speed=i||0,void 0!==i&&(this._speedWasSpecified=!0)}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._meetMotion.vel.x,2)+Math.pow(this._meetMotion.vel.y,2));0===e||this._speedWasSpecified||(this._speed=e),this._current=S(this._tx.pos.x,this._tx.pos.y),this._end=S(this._meetTx.pos.x,this._meetTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize();const i=this._dir.scale(this._speed);this._motion.vel=S(i.x,i.y),this.isComplete()&&(this._tx.pos=S(this._end.x,this._end.y),this._motion.vel=S(0,0))}isComplete(){return this._stopped||this._distanceBetween<=1}stop(){this._motion.vel=S(0,0),this._stopped=!0}reset(){this._started=!1}}class vs{constructor(t){this._entity=t,this._queue=new ss(t)}getQueue(){return this._queue}update(t){this._queue.update(t)}clearActions(){this._queue.clearActions()}easeTo(...t){var e,i;let s=0,n=0,r=0,o=is.Linear;return t[0]instanceof A?(s=t[0].x,n=t[0].y,r=t[1],o=null!==(e=t[2])&&void 0!==e?e:o):(s=t[0],n=t[1],r=t[2],o=null!==(i=t[3])&&void 0!==i?i:o),this._queue.add(new ps(this._entity,s,n,r,o)),this}moveTo(t,e,i){let s=0,n=0,r=0;return t instanceof A?(s=t.x,n=t.y,r=e):(s=t,n=e,r=i),this._queue.add(new as(this._entity,s,n,r)),this}moveBy(t,e,i){let s=0,n=0,r=0;return t instanceof A?(s=t.x,n=t.y,r=e):(s=t,n=e,r=i),this._queue.add(new os(this._entity,s,n,r)),this}rotateTo(t,e,i){return this._queue.add(new hs(this._entity,t,e,i)),this}rotateBy(t,e,i){return this._queue.add(new ls(this._entity,t,e,i)),this}scaleTo(t,e,i,s){let n=1,r=1,o=0,a=0;return t instanceof A&&e instanceof A&&(n=t.x,r=t.y,o=e.x,a=e.y),"number"==typeof t&&"number"==typeof e&&(n=t,r=e,o=i,a=s),this._queue.add(new cs(this._entity,n,r,o,a)),this}scaleBy(t,e,i){let s=1,n=1;return t instanceof A&&(s=t.x,n=t.y,i=e),"number"==typeof t&&"number"==typeof e&&(s=t,n=e),this._queue.add(new ds(this._entity,s,n,i)),this}blink(t,e,i=1){return this._queue.add(new gs(this._entity,t,e,i)),this}fade(t,e){return this._queue.add(new _s(this._entity,t,e)),this}delay(t){return this._queue.add(new ms(t)),this}die(){return this._queue.add(new fs(this._entity)),this}callMethod(t){return this._queue.add(new us(t)),this}repeat(t,e){return e?(this._queue.add(new ns(this._entity,t,e)),this):(this.repeatForever(t),this)}repeatForever(t){return this._queue.add(new rs(this._entity,t)),this}follow(t,e){return void 0===e?this._queue.add(new ws(this._entity,t)):this._queue.add(new ws(this._entity,t,e)),this}meet(t,e){return void 0===e?this._queue.add(new ys(this._entity,t)):this._queue.add(new ys(this._entity,t,e)),this}asPromise(){return this.toPromise()}toPromise(){return new Promise((t=>{this._queue.add(new us((()=>{t()})))}))}}class xs extends di{constructor(){super(...arguments),this.type="ex.actions",this.dependencies=[gi,_i]}onAdd(t){this._ctx=new vs(t)}onRemove(){this._ctx=null}getQueue(){var t;return null===(t=this._ctx)||void 0===t?void 0:t.getQueue()}update(t){var e;return null===(e=this._ctx)||void 0===e?void 0:e.update(t)}clearActions(){var t;null===(t=this._ctx)||void 0===t||t.clearActions()}easeTo(...t){return this._ctx.easeTo.apply(this._ctx,t)}moveTo(t,e,i){return this._ctx.moveTo.apply(this._ctx,[t,e,i])}moveBy(t,e,i){return this._ctx.moveBy.apply(this._ctx,[t,e,i])}rotateTo(t,e,i){return this._ctx.rotateTo(t,e,i)}rotateBy(t,e,i){return this._ctx.rotateBy(t,e,i)}scaleTo(t,e,i,s){return this._ctx.scaleTo.apply(this._ctx,[t,e,i,s])}scaleBy(t,e,i){return this._ctx.scaleBy.apply(this._ctx,[t,e,i])}blink(t,e,i){return this._ctx.blink(t,e,i)}fade(t,e){return this._ctx.fade(t,e)}delay(t){return this._ctx.delay(t)}die(){return this._ctx.die()}callMethod(t){return this._ctx.callMethod(t)}repeat(t,e){return this._ctx.repeat(t,e)}repeatForever(t){return this._ctx.repeatForever(t)}follow(t,e){return this._ctx.follow(t,e)}meet(t,e){return this._ctx.meet(t,e)}asPromise(){return this.toPromise()}toPromise(){return this._ctx.toPromise()}}var bs=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Cs extends Xi{constructor(t){super(),this._anchor=vt(A.Half,(t=>this._handleAnchorChange(t))),this.logger=_.getInstance(),this.scene=null,this.frames={},this.currentDrawing=null,this._draggable=!1,this._dragging=!1,this._pointerDragStartHandler=()=>{this._dragging=!0},this._pointerDragEndHandler=()=>{this._dragging=!1},this._pointerDragMoveHandler=t=>{this._dragging&&(this.pos=t.worldPos)},this._pointerDragLeaveHandler=t=>{this._dragging&&(this.pos=t.worldPos)},this.traits=[];const{name:e,x:i,y:s,pos:n,scale:r,width:o,height:a,radius:h,collider:l,vel:d,acc:u,rotation:g,angularVelocity:m,z:f,color:w,visible:y,anchor:v,collisionType:x,collisionGroup:b}={...t};this._setName(e),this.anchor=null!=v?v:Cs.defaults.anchor.clone(),this.addComponent(new gi),this.pos=null!=n?n:S(null!=i?i:0,null!=s?s:0),this.rotation=null!=g?g:0,this.scale=null!=r?r:S(1,1),this.z=null!=f?f:0,this.addComponent(new Ji),this.addComponent(new Yi({anchor:this.anchor})),this.addComponent(new ji(((t,e)=>this.draw(t,e)))),this.addComponent(new _i),this.vel=null!=d?d:A.Zero,this.acc=null!=u?u:A.Zero,this.angularVelocity=null!=m?m:0,this.addComponent(new xs),this.addComponent(new Oi),this.body.collisionType=null!=x?x:ni.Passive,b&&(this.body.group=b),l?this.addComponent(new Li(l)):h?this.addComponent(new Li(Ii.Circle(h,this.anchor))):o>0&&a>0?this.addComponent(new Li(Ii.Box(o,a,this.anchor))):this.addComponent(new Li),this.graphics.visible=null==y||y,w&&(this.color=w,o&&a?this.graphics.add(new Qi({color:w,width:o,height:a})):h&&this.graphics.add(new $i({color:w,radius:h}))),p.isEnabled(c.LegacyDrawing)&&this.traits.push(new Hi)}get body(){return this.get(Oi)}get transform(){return this.get(gi)}get motion(){return this.get(_i)}get graphics(){return this.get(Yi)}get collider(){return this.get(Li)}get pointer(){return this.get(Ji)}get actions(){return this.get(xs)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t.clone()}get oldPos(){return this.body.oldPos}set oldPos(t){this.body.oldPos.setTo(t.x,t.y)}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t.clone()}get oldVel(){return this.body.oldVel}set oldVel(t){this.body.oldVel.setTo(t.x,t.y)}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t.clone()}set oldAcc(t){this.body.oldAcc.setTo(t.x,t.y)}get oldAcc(){return this.body.oldAcc}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}get scale(){return this.get(gi).scale}set scale(t){this.get(gi).scale=t}get anchor(){return this._anchor}set anchor(t){this._anchor=vt(t,(t=>this._handleAnchorChange(t))),this._handleAnchorChange(t)}_handleAnchorChange(t){this.graphics&&(this.graphics.anchor=t)}get isOffScreen(){return this.hasTag("offscreen")}get visible(){return this.graphics.visible}set visible(t){this.graphics.visible=t}get opacity(){return this.graphics.opacity}set opacity(t){this.graphics.opacity=t}get draggable(){return this._draggable}set draggable(t){t&&(t&&!this._draggable?(this.on("pointerdragstart",this._pointerDragStartHandler),this.on("pointerdragend",this._pointerDragEndHandler),this.on("pointerdragmove",this._pointerDragMoveHandler),this.on("pointerdragleave",this._pointerDragLeaveHandler)):!t&&this._draggable&&(this.off("pointerdragstart",this._pointerDragStartHandler),this.off("pointerdragend",this._pointerDragEndHandler),this.off("pointerdragmove",this._pointerDragMoveHandler),this.off("pointerdragleave",this._pointerDragLeaveHandler)),this._draggable=t)}get color(){return this._color}set color(t){this._color=t.clone()}onInitialize(t){}_initialize(t){super._initialize(t);for(const e of this.children)e._initialize(t)}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}_prekill(t){super.emit("prekill",new Et(this)),this.onPreKill(t)}onPreKill(t){}_postkill(t){super.emit("postkill",new Tt(this)),this.onPostKill(t)}onPostKill(t){}kill(){this.scene?(this._prekill(this.scene),this.emit("kill",new Pt(this)),super.kill(),this._postkill(this.scene)):this.logger.warn("Cannot kill actor, it was never added to the Scene")}unkill(){this.active=!0}isKilled(){return!this.active}setDrawing(t){t=t.toString(),this.currentDrawing!==this.frames[t]&&(null!=this.frames[t]?(this.frames[t].reset(),this.currentDrawing=this.frames[t]):_.getInstance().error(`the specified drawing key ${t} does not exist`)),this.currentDrawing&&this.currentDrawing instanceof Re&&this.currentDrawing.tick(0)}addDrawing(){2===arguments.length?(this.frames[arguments[0]]=arguments[1],this.currentDrawing||(this.currentDrawing=arguments[1])):(arguments[0]instanceof Ae&&this.addDrawing("default",arguments[0]),arguments[0]instanceof ve&&this.addDrawing("default",arguments[0].asSprite()))}get z(){return this.get(gi).z}getZIndex(){return this.get(gi).z}set z(t){this.get(gi).z=t}setZIndex(t){this.get(gi).z=t}get center(){return new A(this.pos.x+this.width/2-this.anchor.x*this.width,this.pos.y+this.height/2-this.anchor.y*this.height)}get width(){return this.collider.localBounds.width*this.getGlobalScale().x}get height(){return this.collider.localBounds.height*this.getGlobalScale().y}getGlobalRotation(){return this.get(gi).globalRotation}getGlobalPos(){return this.get(gi).globalPos}getGlobalScale(){return this.get(gi).globalScale}contains(t,e,i=!1){const s=S(t,e),n=this.get(Li);n.update();const r=n.get();if(!r)return!1;const o=r.contains(s);return i?o||this.children.some((i=>i.contains(t,e,!0))):o}within(t,e){const i=this.get(Li),s=t.get(Li),n=i.get(),r=s.get();return!(!n||!r)&&n.getClosestLineBetween(r).getLength()<=e}update(t,e){this._initialize(t),this._preupdate(t,e);const i=this.currentDrawing;i&&i instanceof Re&&i.tick(e,t.stats.currFrame.id);for(const i of this.traits)i.update(this,t,e);this._postupdate(t,e)}onPreUpdate(t,e){}onPostUpdate(t,e){}_preupdate(t,e){this.emit("preupdate",new It(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new It(t,e,this)),this.onPostUpdate(t,e)}draw(t,e){var i;if(t.save(),this.currentDrawing){t.translate(-this.width*this.anchor.x,-this.height*this.anchor.y),this._predraw(t,e);const i=this.currentDrawing,s=(this.width-i.width*i.scale.x)*this.anchor.x,n=(this.height-i.height*i.scale.y)*this.anchor.y;this.currentDrawing.draw({ctx:t,x:s,y:n,opacity:this.graphics.opacity})}else if(this._predraw(t,e),this.color&&this.collider){const e=this.get(Li);e.update(),e&&!e.bounds.hasZeroDimensions()&&(t.globalAlpha=this.graphics.opacity,null===(i=e.get())||void 0===i||i.draw(t,this.color,S(0,0)))}t.restore(),this._postdraw(t,e)}onPreDraw(t,e){}onPostDraw(t,e){}_predraw(t,e){this.emit("predraw",new Mt(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new Mt(t,e,this)),this.onPostDraw(t,e)}debugDraw(t){}}Cs.defaults={anchor:A.Half},bs([b({message:"Actor.visible will be removed in v0.26.0",alternateMethod:"Use Actor.graphics.visible"})],Cs.prototype,"visible",null),bs([b({message:"Actor.opacity will be removed in v0.26.0",alternateMethod:"Use Actor.graphics.opacity"})],Cs.prototype,"opacity",null),bs([b({message:"Actor.setDrawing will be removed in v0.26.0",alternateMethod:"Use Actor.graphics.show() or Actor.graphics.use()"})],Cs.prototype,"setDrawing",null),bs([b({message:"Actor.addDrawing will be removed in v0.26.0",alternateMethod:"Use Actor.graphics.add()"})],Cs.prototype,"addDrawing",null),bs([b({message:"Actor.getZIndex will be removed in v0.26.0",alternateMethod:"Use Actor.transform.z or Actor.z"})],Cs.prototype,"getZIndex",null),bs([b({message:"Actor.setZIndex will be removed in v0.26.0",alternateMethod:"Use Actor.transform.z or Actor.z"})],Cs.prototype,"setZIndex",null);class As extends Cs{constructor(t){super({...t}),this.get(gi).coordPlane=pi.Screen,this.anchor=S(0,0),this.body.collisionType=ni.PreventCollision,this.collider.useBoxCollider(this.width,this.height,this.anchor)}_initialize(t){this._engine=t,super._initialize(t)}contains(t,e,i=!0){if(i)return super.contains(t,e);const s=this._engine.worldToScreenCoordinates(new A(t,e));return super.contains(s.x,s.y)}}var Ss=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Ps{constructor(t,e,i,s){if(this._logger=_.getInstance(),this.id=0,this._elapsedTime=0,this._totalTimeAlive=0,this._running=!1,this._numberOfTicks=0,this.interval=10,this.repeats=!1,this.maxNumberOfRepeats=-1,this._complete=!1,this.scene=null,"function"!=typeof t){const n=t;t=n.fcn,e=n.interval,i=n.repeats,s=n.numberOfRepeats}if(s&&s>=0&&(this.maxNumberOfRepeats=s,!i))throw new Error("repeats must be set to true if numberOfRepeats is set");this.id=Ps._MAX_ID++,this.interval=e||this.interval,this.repeats=i||this.repeats,this._callbacks=[],t&&this.on(t)}get complete(){return this._complete}on(t){this._callbacks.push(t)}off(t){const e=this._callbacks.indexOf(t);this._callbacks.splice(e,1)}update(t){this._running&&(this._totalTimeAlive+=t,this._elapsedTime+=t,this.maxNumberOfRepeats>-1&&this._numberOfTicks>=this.maxNumberOfRepeats&&(this._complete=!0,this._running=!1,this._elapsedTime=0),!this.complete&&this._elapsedTime>=this.interval&&(this._callbacks.forEach((t=>{t.call(this)})),this._numberOfTicks++,this.repeats||(this._complete=!0,this._running=!1),this._elapsedTime=0))}reset(t,e){if(t&&t>=0&&(this.interval=t),this.maxNumberOfRepeats&&this.maxNumberOfRepeats>=0&&(this.maxNumberOfRepeats=e,!this.repeats))throw new Error("repeats must be set to true if numberOfRepeats is set");this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0}get timesRepeated(){return this._numberOfTicks}getTimeRunning(){return this._totalTimeAlive}get timeToNextAction(){return this.complete?0:this.interval-this._elapsedTime}get timeElapsedTowardNextAction(){return this._elapsedTime}get isRunning(){return this._running}pause(){return this._running=!1,this}unpause(){this._running=!0}resume(){return this._running=!0,this}start(){return this.scene||this._logger.warn("Cannot start a timer not part of a scene, timer wont start until added"),this._running=!0,this.complete&&(this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0),this}stop(){return this._running=!1,this._elapsedTime=0,this._numberOfTicks=0,this}cancel(){this.pause(),this.scene&&this.scene.cancelTimer(this)}}Ps._MAX_ID=0,Ss([b({message:"Will be removed in v0.26.0",alternateMethod:"Use Timer.resume()"})],Ps.prototype,"unpause",null);var Es,Ts=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Rs extends Xi{constructor(t,e,i,s,n,r){if(super(),this._token=0,this._onScreenXStart=0,this._onScreenXEnd=9999,this._onScreenYStart=0,this._onScreenYEnd=9999,this._spriteSheets={},this._legacySpriteMap=new Map,this.logger=_.getInstance(),this.data=[],this._rows=[],this._cols=[],this.visible=!0,this.isOffscreen=!1,this._dirty=!0,t&&"object"==typeof t){const o=t;t=o.x,e=o.y,i=o.cellWidth,s=o.cellHeight,n=o.rows,r=o.cols}this.addComponent(new gi),this.addComponent(new _i),this.addComponent(new Oi({type:ni.Fixed})),this.addComponent(new ji(((t,e)=>this.draw(t,e)))),this.addComponent(new Yi({onPostDraw:(t,e)=>this.draw(t,e)})),this.addComponent(new Li),this._transform=this.get(gi),this._motion=this.get(_i),this._collider=this.get(Li),this._composite=this._collider.useCompositeCollider([]),this.x=t,this.y=e,this.cellWidth=i,this.cellHeight=s,this.rows=n,this.cols=r,this.data=new Array(n*r),this._rows=new Array(n),this._cols=new Array(r);let o=[];for(let a=0;a<r;a++){for(let h=0;h<n;h++){const n=new Ds(a*i+t,h*s+e,i,s,a+h*r);n.map=this,this.data[a+h*r]=n,o.push(n),this._rows[h]||(this._rows[h]=[]),this._rows[h].push(n)}this._cols[a]=o,o=[]}this.get(Yi).localBounds=new B({left:0,top:0,right:this.cols*this.cellWidth,bottom:this.rows*this.cellHeight})}flagDirty(){this._dirty=!0}get x(){var t;return null!==(t=this._transform.pos.x)&&void 0!==t?t:0}set x(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.pos)&&(this.get(gi).pos=S(t,this.y))}get y(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.pos.y)&&void 0!==e?e:0}set y(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.pos)&&(this._transform.pos=S(this.x,t))}get z(){var t;return null!==(t=this._transform.z)&&void 0!==t?t:0}set z(t){this._transform&&(this._transform.z=t)}get rotation(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.rotation)&&void 0!==e?e:0}set rotation(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.rotation)&&(this._transform.rotation=t)}get scale(){var t,e;return null!==(e=null===(t=this._transform)||void 0===t?void 0:t.scale)&&void 0!==e?e:A.One}set scale(t){var e;(null===(e=this._transform)||void 0===e?void 0:e.scale)&&(this._transform.scale=t)}get pos(){return this._transform.pos}set pos(t){this._transform.pos=t}get vel(){return this._motion.vel}set vel(t){this._motion.vel=t}on(t,e){super.on(t,e)}_initialize(t){super._initialize(t)}registerSpriteSheet(t,e){this._spriteSheets[t]=e instanceof Oe?e:Oe.fromLegacySpriteSheet(e)}_updateColliders(){this._composite.clearColliders();const t=[];let e;for(let i=0;i<this.cols;i++){for(let s=0;s<this.rows;s++){0===s&&(e=null);const n=this.data[i+s*this.cols];n.solid?e=e?e.combine(n.bounds):n.bounds:(e&&t.push(e),e=null)}if(e){const i=t[t.length-1];i&&i.top===e.top&&i.bottom===e.bottom?t[t.length-1]=i.combine(e):t.push(e)}}this._composite=this._collider.useCompositeCollider([]);for(const e of t){const t=Ii.Box(e.width,e.height,A.Zero,S(e.left-this.pos.x,e.top-this.pos.y));t.owner=this,this._composite.addCollider(t)}this._collider.update()}getCellByIndex(t){return this.data[t]}getCell(t,e){return t<0||e<0||t>=this.cols||e>=this.rows?null:this.data[t+e*this.cols]}getCellByPoint(t,e){t=Math.floor((t-this.pos.x)/this.cellWidth),e=Math.floor((e-this.pos.y)/this.cellHeight);const i=this.getCell(t,e);return t>=0&&e>=0&&t<this.cols&&e<this.rows&&i?i:null}getRows(){return this._rows}getColumns(){return this._cols}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this.onPreUpdate(t,e),this.emit("preupdate",new It(t,e,this)),this._dirty&&(this._dirty=!1,this._updateColliders()),this._token++;const i=t.getWorldBounds(),s=S(i.left,i.top),n=S(i.right,i.bottom);this._onScreenXStart=Math.max(Math.floor((s.x-this.x)/this.cellWidth)-2,0),this._onScreenYStart=Math.max(Math.floor((s.y-this.y)/this.cellHeight)-2,0),this._onScreenXEnd=Math.max(Math.floor((n.x-this.x)/this.cellWidth)+2,0),this._onScreenYEnd=Math.max(Math.floor((n.y-this.y)/this.cellHeight)+2,0),this._transform.pos=S(this.x,this.y),this.onPostUpdate(t,e),this.emit("postupdate",new Lt(t,e,this))}draw(t,e){this.emit("predraw",new Mt(t,e,this));let i=this._onScreenXStart;const s=Math.min(this._onScreenXEnd,this.cols);let n=this._onScreenYStart;const r=Math.min(this._onScreenYEnd,this.rows);let o,a,h;for(;i<s;i++){for(;n<r;n++)for(o=this.getCell(i,n).graphics,a=0,h=o.length;a<h;a++){const s=o[a];s&&(t instanceof CanvasRenderingContext2D?s instanceof Se&&(this._legacySpriteMap.has(s)||this._legacySpriteMap.set(s,Se.toLegacySprite(s)),this._legacySpriteMap.get(s).draw(t,i*this.cellWidth,n*this.cellHeight)):(qi(s)&&(null==s||s.tick(e,this._token)),s.draw(t,i*this.cellWidth,n*this.cellHeight)))}n=this._onScreenYStart}this.emit("postdraw",new Dt(t,e,this))}}Ts([b({message:"No longer used, will be removed in v0.26.0"})],Rs.prototype,"registerSpriteSheet",null);class Bs extends(xe(Rs)){constructor(t,e,i,s,n,r){super(t,e,i,s,n,r)}}class Ms extends Xi{constructor(t,e,i,s,n,r=!1,o=[]){if(super(),this._solid=!1,this.graphics=[],this.data=new Map,t&&"object"==typeof t){const a=t;t=a.x,e=a.y,i=a.width,s=a.height,n=a.index,r=a.solid,o=a.sprites}this.x=t,this.y=e,this.width=i,this.height=s,this.index=n,this.solid=r,this.graphics=o,this._bounds=new B(this.x,this.y,this.x+this.width,this.y+this.height)}get solid(){return this._solid}set solid(t){var e;null===(e=this.map)||void 0===e||e.flagDirty(),this._solid=t}get bounds(){return this._bounds}get center(){return new A(this.x+this.width/2,this.y+this.height/2)}pushSprite(t){this.addGraphic(t)}addGraphic(t){t instanceof Ae?this.graphics.push(Se.fromLegacySprite(t)):this.graphics.push(t)}removeGraphic(t){G(t,this.graphics)}clearGraphics(){this.graphics.length=0}}Ts([b({message:"Will be removed in v0.26.0",alternateMethod:"addSprite"})],Ms.prototype,"pushSprite",null);class Ds extends(xe(Ms)){constructor(t,e,i,s,n,r,o){super(t,e,i,s,n,r,o)}}class Fs{constructor(t){this.camera=t}lockToActor(t){this.camera.addStrategy(new ks(t))}lockToActorAxis(t,e){this.camera.addStrategy(new Is(t,e))}elasticToActor(t,e,i){this.camera.addStrategy(new Ls(t,e,i))}radiusAroundActor(t,e){this.camera.addStrategy(new zs(t,e))}limitCameraBounds(t){this.camera.addStrategy(new Os(t))}}!function(t){t[t.X=0]="X",t[t.Y=1]="Y"}(Es||(Es={}));class ks{constructor(t){this.target=t,this.action=(t,e,i,s)=>t.center}}class Is{constructor(t,e){this.target=t,this.axis=e,this.action=(t,e,i,s)=>{const n=t.center,r=e.getFocus();return this.axis===Es.X?new A(n.x,r.y):new A(r.x,n.y)}}}class Ls{constructor(t,e,i){this.target=t,this.cameraElasticity=e,this.cameraFriction=i,this.action=(t,e,i,s)=>{const n=t.center;let r=e.getFocus(),o=e.vel.clone();const a=n.sub(r).scale(this.cameraElasticity);o=o.add(a);const h=o.scale(-1).scale(this.cameraFriction);return o=o.add(h),r=r.add(o),r}}}class zs{constructor(t,e){this.target=t,this.radius=e,this.action=(t,e,i,s)=>{const n=t.center,r=e.getFocus(),o=n.sub(r),a=o.size;if(a>=this.radius){const t=a-this.radius;return r.add(o.normalize().scale(t))}return r}}}class Os{constructor(t){this.target=t,this.boundSizeChecked=!1,this.action=(t,e,i,s)=>{const n=e.getFocus();this.boundSizeChecked||((t.bottom-t.top<i.drawHeight||t.right-t.left<i.drawWidth)&&_.getInstance().warn("Camera bounds should not be smaller than the engine viewport"),this.boundSizeChecked=!0);let r=n.x,o=n.y;return n.x<t.left+i.halfDrawWidth?r=t.left+i.halfDrawWidth:n.x>t.right-i.halfDrawWidth&&(r=t.right-i.halfDrawWidth),n.y<t.top+i.halfDrawHeight?o=t.top+i.halfDrawHeight:n.y>t.bottom-i.halfDrawHeight&&(o=t.bottom-i.halfDrawHeight),S(r,o)}}}class Us extends Ke{constructor(){super(...arguments),this._cameraStrategies=[],this.strategy=new Fs(this),this._z=1,this.dz=0,this.az=0,this.rotation=0,this.rx=0,this._posChanged=!1,this._pos=xt(A.Zero,(()=>this._posChanged=!0)),this.vel=A.Zero,this.acc=A.Zero,this._cameraMoving=!1,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=null,this._lerpEnd=null,this._isShaking=!1,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._elapsedShakeTime=0,this._xShake=0,this._yShake=0,this._isZooming=!1,this._zoomStart=1,this._zoomEnd=1,this._currentZoomTime=0,this._zoomDuration=0,this._zoomEasing=is.EaseInOutCubic,this._easing=is.EaseInOutCubic,this._halfWidth=0,this._halfHeight=0,this._viewport=null,this._isInitialized=!1}get zoom(){return this._z}set zoom(t){this._z=t,this._engine&&(this._halfWidth=this._engine.halfDrawWidth,this._halfHeight=this._engine.halfDrawHeight)}get angularVelocity(){return this.rx}set angularVelocity(t){this.rx=t}get pos(){return this._pos}set pos(t){this._pos=xt(t,(()=>this._posChanged=!0)),this._posChanged=!0}get x(){return this.pos.x}set x(t){this._follow||this._cameraMoving||(this.pos=S(t,this.pos.y))}get y(){return this.pos.y}set y(t){this._follow||this._cameraMoving||(this.pos=S(this.pos.x,t))}get dx(){return this.vel.x}set dx(t){this.vel=S(t,this.vel.y)}get dy(){return this.vel.y}set dy(t){this.vel=S(this.vel.x,t)}get ax(){return this.acc.x}set ax(t){this.acc=S(t,this.acc.y)}get ay(){return this.acc.y}set ay(t){this.acc=S(this.acc.x,t)}getFocus(){return this.pos}move(t,e,i=is.EaseInOutCubic){if("function"!=typeof i)throw"Please specify an EasingFunction";return this._follow?Promise.reject(t):(this._lerpPromise&&this._lerpResolve&&this._lerpResolve(t),this._lerpPromise=new Promise((t=>{this._lerpResolve=t})),this._lerpStart=this.getFocus().clone(),this._lerpDuration=e,this._lerpEnd=t,this._currentLerpTime=0,this._cameraMoving=!0,this._easing=i,this._lerpPromise)}shake(t,e,i){this._isShaking=!0,this._shakeMagnitudeX=t,this._shakeMagnitudeY=e,this._shakeDuration=i}zoomOverTime(t,e=0,i=is.EaseInOutCubic){return this._zoomPromise=new Promise((t=>{this._zoomResolve=t})),e?(this._isZooming=!0,this._zoomEasing=i,this._currentZoomTime=0,this._zoomDuration=e,this._zoomStart=this.zoom,this._zoomEnd=t,this._zoomPromise):(this._isZooming=!1,this.zoom=t,Promise.resolve(!0))}get viewport(){return this._viewport?this._viewport:new B(0,0,0,0)}addStrategy(t){this._cameraStrategies.push(t)}removeStrategy(t){G(t,this._cameraStrategies)}clearAllStrategies(){this._cameraStrategies.length=0}_preupdate(t,e){this.emit("preupdate",new It(t,e,this)),this.onPreUpdate(t,e)}onPreUpdate(t,e){}_postupdate(t,e){this.emit("postupdate",new Lt(t,e,this)),this.onPostUpdate(t,e)}onPostUpdate(t,e){}get isInitialized(){return this._isInitialized}_initialize(t){if(!this.isInitialized){this._engine=t;const e=this._engine.screen.resolution;let i=S(e.width/2,e.height/2);if(!this._engine.loadingComplete){const t=this._engine.screen.peekResolution();t&&(i=S(t.width/2,t.height/2))}this._halfWidth=i.x,this._halfHeight=i.x,this._posChanged||(this.pos=i),this.onInitialize(t),super.emit("initialize",new ee(t,this)),this._isInitialized=!0}}onInitialize(t){}on(t,e){super.on(t,e)}off(t,e){super.off(t,e)}once(t,e){super.once(t,e)}update(t,e){if(this._initialize(t),this._preupdate(t,e),this.pos=this.pos.add(this.vel.scale(e/1e3)),this.zoom+=this.dz*e/1e3,this.vel=this.vel.add(this.acc.scale(e/1e3)),this.dz+=this.az*e/1e3,this.rotation+=this.angularVelocity*e/1e3,this._isZooming)if(this._currentZoomTime<this._zoomDuration){const t=(0,this._zoomEasing)(this._currentZoomTime,this._zoomStart,this._zoomEnd,this._zoomDuration);this.zoom=t,this._currentZoomTime+=e}else this._isZooming=!1,this.zoom=this._zoomEnd,this._currentZoomTime=0,this._zoomResolve(!0);if(this._cameraMoving)if(this._currentLerpTime<this._lerpDuration){const t=is.CreateVectorEasingFunction(this._easing)(this._currentLerpTime,this._lerpStart,this._lerpEnd,this._lerpDuration);this.pos=t,this._currentLerpTime+=e}else{this.pos=this._lerpEnd;const t=this._lerpEnd.clone();this._lerpStart=null,this._lerpEnd=null,this._currentLerpTime=0,this._cameraMoving=!1,this._lerpResolve(t)}this._isDoneShaking()?(this._isShaking=!1,this._elapsedShakeTime=0,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._xShake=0,this._yShake=0):(this._elapsedShakeTime+=e,this._xShake=1+(Math.random()*this._shakeMagnitudeX|0),this._yShake=1+(Math.random()*this._shakeMagnitudeY|0));for(const i of this._cameraStrategies)this.pos=i.action.call(i,i.target,this,t,e);this._viewport=new B(this.x-this._halfWidth,this.y-this._halfHeight,this.x+this._halfWidth,this.y+this._halfHeight),this._postupdate(t,e)}draw(t){let e=0,i=0;t instanceof CanvasRenderingContext2D?(e=t.canvas.width,i=t.canvas.height):(e=t.width,i=t.height);const s=this.getFocus(),n=this._engine?this._engine.pixelRatio:1,r=this.zoom,o=e/r/n,a=i/r/n;t.scale(r,r),t.translate(-s.x+o/2+this._xShake,-s.y+a/2+this._yShake)}debugDraw(t){}_isDoneShaking(){return!this._isShaking||this._elapsedShakeTime>=this._shakeDuration}}function Hs(t){return t instanceof As}const Ns={pos:A.Zero,width:10,height:10,visible:!1,action:()=>{},filter:()=>!0,repeat:-1};class Ws extends Cs{constructor(t){super({x:t.pos.x,y:t.pos.y,width:t.width,height:t.height}),this.action=()=>{},this.filter=()=>!0,this.repeat=-1,t={...Ns,...t},this.filter=t.filter||this.filter,this.repeat=t.repeat||this.repeat,this.action=t.action||this.action,t.target&&(this.target=t.target),this.graphics.visible=t.visible,this.body.collisionType=ni.Passive,this.eventDispatcher=new he,this.events.on("collisionstart",(t=>{this.filter(t.other)&&(this.emit("enter",new oe(this,t.other)),this._dispatchAction(),0===this.repeat&&this.kill())})),this.events.on("collisionend",(t=>{this.filter(t.other)&&this.emit("exit",new ae(this,t.other))}))}set target(t){this._target=t,this.filter=e=>e===t}get target(){return this._target}_initialize(t){super._initialize(t)}_dispatchAction(){0!==this.repeat&&(this.action.call(this),this.repeat--)}debugDraw(t){super.debugDraw(t),t.save(),t.translate(this.pos.x,this.pos.y);const e=this.collider.bounds,i=this.getGlobalPos();e.left=e.left-i.x,e.right=e.right-i.x,e.top=e.top-i.y,e.bottom=e.bottom-i.y,t.fillStyle=T.Violet.toString(),t.strokeStyle=T.Violet.toString(),t.fillText("Trigger",10,10),e.debugDraw(t),t.restore()}}var Vs;!function(t){t.Update="update",t.Draw="draw"}(Vs||(Vs={}));class Gs{constructor(){this.priority=0}notify(t){}}class Xs{constructor(t){this.data=t,this.type="Entity Added"}}function js(t){return!!t&&"Entity Added"===t.type}class qs{constructor(t){this.data=t,this.type="Entity Removed"}}function Ks(t){return!!t&&"Entity Removed"===t.type}class Zs{constructor(t){this._world=t,this.entities=[],this._entityIndex={},this._entitiesToRemove=[]}updateEntities(t,e){for(const i of this.entities)i.update(t.engine,e),i.active||this.removeEntity(i)}findEntitiesForRemoval(){for(const t of this.entities)t.active||this.removeEntity(t)}notify(t){Wi(t)&&this._world.queryManager.addEntity(t.data.entity),Gi(t)&&this._world.queryManager.removeComponent(t.data.entity,t.data.component)}addEntity(t){t.active=!0,t&&!this._entityIndex[t.id]&&(this._entityIndex[t.id]=t,this.entities.push(t),this._world.queryManager.addEntity(t),t.componentAdded$.register(this),t.componentRemoved$.register(this),t.children.forEach((t=>this.addEntity(t))),t.childrenAdded$.register({notify:t=>{this.addEntity(t)}}),t.childrenRemoved$.register({notify:t=>{this.removeEntity(t,!1)}}))}removeEntity(t,e=!0){var i;let s=0;s=t instanceof Xi?t.id:t;const n=this._entityIndex[s];n&&n.active&&n.kill(),n&&e?this._entitiesToRemove.push(n):(delete this._entityIndex[s],n&&(G(n,this.entities),this._world.queryManager.removeEntity(n),n.componentAdded$.unregister(this),n.componentRemoved$.unregister(this),n.children.forEach((t=>this.removeEntity(t,e))),n.childrenAdded$.clear(),n.childrenRemoved$.clear(),(null===(i=this._world.context)||void 0===i?void 0:i.engine)&&this._world.context.engine.stats.currFrame.actors.killed++))}processEntityRemovals(){for(const t of this._entitiesToRemove)t.active||this.removeEntity(t,!1)}processComponentRemovals(){for(const t of this.entities)t.processComponentRemoval()}getById(t){return this._entityIndex[t]}getByName(t){return this.entities.filter((e=>e.name===t))}clear(){for(const t of this.entities)this.removeEntity(t)}}const Ys=t=>[...t].sort(((t,e)=>t.localeCompare(e))).join("+");class Qs extends fi{constructor(t){super(),this._entities=[],t[0]instanceof Function?this.types=t.map((t=>(new t).type)):this.types=t}get key(){return this._key?this._key:this._key=Ys(this.types)}getEntities(t){return t&&this._entities.sort(t),this._entities}addEntity(t){!X(this._entities,t)&&this.matches(t)&&(this._entities.push(t),this.notifyAll(new Xs(t)))}removeEntity(t){G(t,this._entities)&&this.notifyAll(new qs(t))}clear(){this._entities.length=0;for(const t of this.observers)this.unregister(t)}matches(t){let e=[];e=t instanceof Xi?t.types:t;let i=!0;for(const t of this.types)if(i=i&&e.indexOf(t)>-1,!i)return!1;return i}contain(t){return this.types.indexOf(t)>-1}}class $s{constructor(t){this._world=t,this._queries={}}_addQuery(t){this._queries[Ys(t.types)]=t;for(const e of this._world.entityManager.entities)t.addEntity(e)}maybeRemoveQuery(t){0===t.observers.length&&(t.clear(),delete this._queries[Ys(t.types)])}addEntity(t){for(const e in this._queries)this._queries[e]&&this._queries[e].addEntity(t)}removeComponent(t,e){for(const i in this._queries)this._queries[i].contain(e.type)&&this._queries[i].removeEntity(t)}removeEntity(t){for(const e in this._queries)this._queries[e].removeEntity(t)}createQuery(t){const e=this.getQuery(t);if(e)return e;const i=new Qs(t);return this._addQuery(i),i}getQuery(t){const e=Ys(t);return this._queries[e]?this._queries[e]:null}}class Js{constructor(t){this._world=t,this.systems=[],this.initialized=!1}get(t){return this.systems.find((e=>e instanceof t))}addSystem(t){if(!t.types||0===t.types.length)throw new Error("Attempted to add a System without any types");const e=this._world.queryManager.createQuery(t.types);this.systems.push(t),this.systems.sort(((t,e)=>t.priority-e.priority)),e.register(t),this.initialized&&t.initialize&&t.initialize(this._world.context)}removeSystem(t){G(t,this.systems);const e=this._world.queryManager.getQuery(t.types);e&&(e.unregister(t),this._world.queryManager.maybeRemoveQuery(e))}initialize(){if(!this.initialized){this.initialized=!0;for(const t of this.systems)t.initialize&&t.initialize(this._world.context)}}updateSystems(t,e,i){const s=this.systems.filter((e=>e.systemType===t));for(const t of s)t.preupdate&&t.preupdate(e,i);for(const t of s){const s=this._world.queryManager.getQuery(t.types).getEntities(t.sort);if(e instanceof Dn)for(const t of s)t._initialize(null==e?void 0:e.engine);t.update(s,i)}for(const t of s)t.postupdate&&t.postupdate(e,i)}clear(){for(const t of this.systems)this.removeSystem(t)}}class tn{constructor(t){this.context=t,this.queryManager=new $s(this),this.entityManager=new Zs(this),this.systemManager=new Js(this)}update(t,e){t===Vs.Update&&this.entityManager.updateEntities(this.context,e),this.systemManager.updateSystems(t,this.context,e),this.entityManager.findEntitiesForRemoval(),this.entityManager.processComponentRemovals(),this.entityManager.processEntityRemovals()}add(t){t instanceof Xi&&this.entityManager.addEntity(t),t instanceof Gs&&this.systemManager.addSystem(t)}remove(t,e=!0){t instanceof Xi&&this.entityManager.removeEntity(t,e),t instanceof Gs&&this.systemManager.removeSystem(t)}clearEntities(){this.entityManager.clear()}clearSystems(){this.systemManager.clear()}}class en{static integrate(t,e,i,s){const n=s/1e3;e.vel.addEqual(i.scale(n)),t.pos.addEqual(e.vel.scale(n)).addEqual(i.scale(.5*n*n)),e.angularVelocity+=e.torque*(1/e.inertia)*n,t.rotation+=e.angularVelocity*n,t.scale.addEqual(e.scaleFactor.scale(n))}}class sn extends Gs{constructor(){super(...arguments),this.types=["ex.transform","ex.motion"],this.systemType=Vs.Update,this.priority=-1}update(t,e){let i,s;for(const n of t){i=n.get(gi),s=n.get(_i);const t=n.get(Oi);if(null==t?void 0:t.sleeping)continue;const r=s.acc.clone();(null==t?void 0:t.collisionType)===ni.Active&&(null==t?void 0:t.useGravity)&&r.addEqual(li.gravity),null==t||t.captureOldTransform(),en.integrate(i,s,r,e)}}debugDraw(t){}}class nn{solve(t){return this.preSolve(t),t=t.filter((t=>!t.isCanceled())),this.solveVelocity(t),this.solvePosition(t),this.postSolve(t),t}}class rn extends nn{preSolve(t){for(const e of t){const t=P.fromDirection(e.mtv),i=e.mtv.negate();e.colliderA.events.emit("precollision",new qt(e.colliderA,e.colliderB,t,i)),e.colliderB.events.emit("precollision",new qt(e.colliderB,e.colliderA,P.getOpposite(t),i.negate()))}}postSolve(t){var e,i;for(const s of t){const t=s.colliderA,n=s.colliderB,r=null===(e=t.owner)||void 0===e?void 0:e.get(Oi),o=null===(i=n.owner)||void 0===i?void 0:i.get(Oi);if(r&&o&&(r.collisionType===ni.Passive||o.collisionType===ni.Passive))continue;const a=P.fromDirection(s.mtv),h=s.mtv.negate();s.colliderA.events.emit("postcollision",new Kt(s.colliderA,s.colliderB,a,h)),s.colliderB.events.emit("postcollision",new Kt(s.colliderB,s.colliderA,P.getOpposite(a),h.negate()))}}solvePosition(t){var e,i;for(const s of t){if(!s.colliderA.bounds.intersect(s.colliderB.bounds))continue;let t=s.mtv;const n=s.colliderA,r=s.colliderB,o=null===(e=n.owner)||void 0===e?void 0:e.get(Oi),a=null===(i=r.owner)||void 0===i?void 0:i.get(Oi);if(o&&a){if(o.collisionType===ni.Passive||a.collisionType===ni.Passive)continue;o.collisionType===ni.Active&&a.collisionType===ni.Active&&(t=t.scale(.5)),o.collisionType===ni.Active&&(o.pos.x-=t.x,o.pos.y-=t.y),a.collisionType===ni.Active&&(a.pos.x+=t.x,a.pos.y+=t.y)}}}solveVelocity(t){var e,i;for(const s of t){const t=s.colliderA,n=s.colliderB,r=null===(e=t.owner)||void 0===e?void 0:e.get(Oi),o=null===(i=n.owner)||void 0===i?void 0:i.get(Oi);if(r&&o){if(r.collisionType===ni.Passive||o.collisionType===ni.Passive)continue;const t=s.normal,e=t.negate();if(r.collisionType===ni.Active){const e=t.scale(t.dot(r.vel.negate()));r.vel=r.vel.add(e)}if(o.collisionType===ni.Active){const t=e.scale(e.dot(o.vel.negate()));o.vel=o.vel.add(t)}}}}}class on{constructor(t,e,i){this.point=t,this.local=e,this.contact=i,this.normalImpulse=0,this.tangentImpulse=0,this.normalMass=0,this.tangentMass=0,this.aToContact=new A(0,0),this.bToContact=new A(0,0),this.update()}update(){var t,e;const i=null===(t=this.contact.colliderA.owner)||void 0===t?void 0:t.get(Oi),s=null===(e=this.contact.colliderB.owner)||void 0===e?void 0:e.get(Oi);if(i&&s){const t=this.contact.normal,e=this.contact.tangent;this.aToContact=this.point.sub(i.pos),this.bToContact=this.point.sub(s.pos);const n=this.aToContact.cross(t),r=this.bToContact.cross(t);this.normalMass=i.inverseMass+s.inverseMass+i.inverseInertia*n*n+s.inverseInertia*r*r;const o=this.aToContact.cross(e),a=this.bToContact.cross(e);this.tangentMass=i.inverseMass+s.inverseMass+i.inverseInertia*o*o+s.inverseInertia*a*a}return this}getRelativeVelocity(){var t,e;const i=null===(t=this.contact.colliderA.owner)||void 0===t?void 0:t.get(Oi),s=null===(e=this.contact.colliderB.owner)||void 0===e?void 0:e.get(Oi);if(i&&s){const t=i.vel.add(A.cross(i.angularVelocity,this.aToContact));return s.vel.add(A.cross(s.angularVelocity,this.bToContact)).sub(t)}return A.Zero}}class an extends nn{constructor(){super(...arguments),this.lastFrameContacts=new Map,this.idToContactConstraint=new Map}getContactConstraints(t){var e;return null!==(e=this.idToContactConstraint.get(t))&&void 0!==e?e:[]}preSolve(t){var e,i,s;for(const e of t){const t=P.fromDirection(e.mtv);e.colliderA.events.emit("precollision",new qt(e.colliderA,e.colliderB,t,e.mtv)),e.colliderA.events.emit("beforecollisionresolve",new Qt(e.colliderA,e.colliderB,t,e.mtv,e)),e.colliderB.events.emit("precollision",new qt(e.colliderB,e.colliderA,P.getOpposite(t),e.mtv.negate())),e.colliderB.events.emit("beforecollisionresolve",new Qt(e.colliderB,e.colliderA,P.getOpposite(t),e.mtv.negate(),e)),e.matchAwake()}const n=Array.from(this.idToContactConstraint.keys());for(const r of t){const t=n.indexOf(r.id);t>-1&&n.splice(t,1);const o=null!==(e=this.idToContactConstraint.get(r.id))&&void 0!==e?e:[];let a=0;const h=r.colliderA.owner.get(Oi),l=r.colliderB.owner.get(Oi);if(h&&l)for(const t of r.points){const e=r.normal,n=r.tangent,c=t.sub(h.pos),d=t.sub(l.pos),u=c.cross(e),p=d.cross(e),g=h.inverseMass+l.inverseMass+h.inverseInertia*u*u+l.inverseInertia*p*p,_=c.cross(n),m=d.cross(n),f=h.inverseMass+l.inverseMass+h.inverseInertia*_*_+l.inverseInertia*m*m;o[a]&&(null===(s=null===(i=o[a])||void 0===i?void 0:i.point)||void 0===s?void 0:s.squareDistance(t))<4?(o[a].point=t,o[a].local=r.localPoints[a]):o[a]=new on(t,r.localPoints[a],r),o[a].aToContact=c,o[a].bToContact=d,o[a].normalMass=g,o[a].tangentMass=f,a++}this.idToContactConstraint.set(r.id,o)}for(const t of n)this.idToContactConstraint.delete(t);if(li.warmStart)this.warmStart(t);else for(const e of t){const t=this.getContactConstraints(e.id);for(const e of t)e.normalImpulse=0,e.tangentImpulse=0}}postSolve(t){for(const e of t){const t=e.colliderA.owner.get(Oi),i=e.colliderB.owner.get(Oi);if(t&&i){if(t.collisionType===ni.Passive||i.collisionType===ni.Passive)continue;t.updateMotion(),i.updateMotion()}const s=P.fromDirection(e.mtv);e.colliderA.events.emit("postcollision",new Kt(e.colliderA,e.colliderB,s,e.mtv)),e.colliderA.events.emit("aftercollisionresolve",new $t(e.colliderA,e.colliderB,s,e.mtv,e)),e.colliderB.events.emit("postcollision",new Kt(e.colliderB,e.colliderA,P.getOpposite(s),e.mtv.negate())),e.colliderB.events.emit("aftercollisionresolve",new $t(e.colliderB,e.colliderA,P.getOpposite(s),e.mtv.negate(),e))}this.lastFrameContacts.clear();for(const e of t)this.lastFrameContacts.set(e.id,e)}warmStart(t){var e,i,s;for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Oi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Oi);if(t&&r){const e=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const i of e)if(li.warmStart){const e=n.normal.scale(i.normalImpulse),s=n.tangent.scale(i.tangentImpulse),o=e.add(s);t.applyImpulse(i.point,o.negate()),r.applyImpulse(i.point,o)}else i.normalImpulse=0,i.tangentImpulse=0}}}solvePosition(t){var e,i,s;for(let n=0;n<li.positionIterations;n++)for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Oi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Oi);if(t&&r){if(t.collisionType===ni.Passive||r.collisionType===ni.Passive)continue;const e=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const i of e){const e=n.normal,s=Di.FindContactSeparation(n,i.local),o=-5,a=L(li.steeringFactor*(s+li.slop),o,0),h=e.scale(-a/i.normalMass);t.collisionType===ni.Active&&(t.pos=t.pos.add(h.negate().scale(t.inverseMass)),t.rotation-=i.aToContact.cross(h)*t.inverseInertia),r.collisionType===ni.Active&&(r.pos=r.pos.add(h.scale(r.inverseMass)),r.rotation+=i.bToContact.cross(h)*r.inverseInertia)}}}}solveVelocity(t){var e,i,s;for(let n=0;n<li.velocityIterations;n++)for(const n of t){const t=null===(e=n.colliderA.owner)||void 0===e?void 0:e.get(Oi),r=null===(i=n.colliderB.owner)||void 0===i?void 0:i.get(Oi);if(t&&r){if(t.collisionType===ni.Passive||r.collisionType===ni.Passive)continue;const e=t.bounciness*r.bounciness,i=Math.min(t.friction,r.friction),o=null!==(s=this.idToContactConstraint.get(n.id))&&void 0!==s?s:[];for(const e of o){let s=-e.getRelativeVelocity().dot(n.tangent)/e.tangentMass;const o=i*e.normalImpulse,a=L(e.tangentImpulse+s,-o,o);s=a-e.tangentImpulse,e.tangentImpulse=a;const h=n.tangent.scale(s);t.applyImpulse(e.point,h.negate()),r.applyImpulse(e.point,h)}for(const i of o){let s=-(1+e)*i.getRelativeVelocity().dot(n.normal)/i.normalMass;const o=Math.max(i.normalImpulse+s,0);s=o-i.normalImpulse,i.normalImpulse=o;const a=n.normal.scale(s);t.applyImpulse(i.point,a.negate()),r.applyImpulse(i.point,a)}}}}}class hn extends Gs{constructor(){super(...arguments),this.types=["ex.transform","ex.motion","ex.collider"],this.systemType=Vs.Update,this.priority=-1,this._realisticSolver=new an,this._arcadeSolver=new rn,this._processor=new Ci,this._lastFrameContacts=new Map,this._currentFrameContacts=new Map,this._trackCollider=t=>this._processor.track(t),this._untrackCollider=t=>this._processor.untrack(t)}notify(t){if(js(t)){const e=t.data.get(Li);e.$colliderAdded.subscribe(this._trackCollider),e.$colliderRemoved.subscribe(this._untrackCollider);const i=e.get();i&&this._processor.track(i)}else{const e=t.data.get(Li),i=e.get();e&&i&&this._processor.untrack(i)}}initialize(t){this._engine=t.engine}update(t,e){var i;if(!li.enabled)return;let s=[];for(const e of t){const t=e.get(Li),n=null==t?void 0:t.get();t&&(null===(i=t.owner)||void 0===i?void 0:i.active)&&n&&(t.update(),n instanceof Si?s=s.concat(n.getColliders()):s.push(n))}this._processor.update(s);const n=this._processor.broadphase(s,e);this._currentFrameContacts.clear();let r=this._processor.narrowphase(n,this._engine.debug.stats.currFrame);r=this.getSolver().solve(r),r.forEach((t=>this._currentFrameContacts.set(t.id,t))),this.runContactStartEnd(),this._lastFrameContacts.clear(),this._lastFrameContacts=new Map(this._currentFrameContacts)}getSolver(){return li.collisionResolutionStrategy===ri.Realistic?this._realisticSolver:this._arcadeSolver}debug(t){this._processor.debug(t)}runContactStartEnd(){for(const[t,e]of this._currentFrameContacts)if(!this._lastFrameContacts.has(t)){const t=e.colliderA,i=e.colliderB;t.events.emit("collisionstart",new Jt(t,i,e)),t.events.emit("contactstart",new Zt(t,i,e)),i.events.emit("collisionstart",new Jt(i,t,e)),i.events.emit("contactstart",new Zt(i,t,e))}for(const[t,e]of this._lastFrameContacts)if(!this._currentFrameContacts.has(t)){const t=e.colliderA,i=e.colliderB;t.events.emit("collisionend",new te(t,i)),t.events.emit("contactend",new Yt(t,i)),i.events.emit("collisionend",new te(i,t)),i.events.emit("contactend",new Yt(i,t))}}}var ln,cn,dn;!function(t){t.Forward="forward",t.Backward="backward"}(ln||(ln={})),function(t){t.End="end",t.Loop="loop",t.PingPong="pingpong",t.Freeze="freeze"}(cn||(cn={}));class un extends yt{constructor(t){var e,i;super(t),this.events=new he,this.frames=[],this.strategy=cn.Loop,this.frameDuration=100,this.timeScale=1,this._idempotencyToken=-1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=0,this._direction=1,this._done=!1,this._playing=!0,this._reversed=!1,this.frames=t.frames,this.strategy=null!==(e=t.strategy)&&void 0!==e?e:this.strategy,this.frameDuration=t.totalDuration?t.totalDuration/this.frames.length:null!==(i=t.frameDuration)&&void 0!==i?i:this.frameDuration,t.reverse&&this.reverse(),this.goToFrame(0)}clone(){return new un({frames:this.frames.map((t=>({...t}))),frameDuration:this.frameDuration,reverse:this._reversed,strategy:this.strategy,...this.cloneGraphicOptions()})}static fromSpriteSheet(t,e,i,s=cn.Loop){const n=t.sprites.length-1,r=e.filter((t=>t<0||t>n));return r.length&&un._LOGGER.warn(`Indices into SpriteSheet were provided that don't exist: ${r.join(",")} no frame will be shown`),new un({frames:t.sprites.filter(((t,i)=>e.indexOf(i)>-1)).map((t=>({graphic:t,duration:i}))),strategy:s})}static toLegacyAnimation(t,e){const i=e.frames.map((t=>Se.toLegacySprite(t.graphic)));return new Re({sprites:i,loop:e.strategy===cn.Loop,freezeFrame:e.strategy===cn.Freeze?i.length-1:void 0,speed:e.frameDuration,engine:t})}get currentFrame(){return this._currentFrame>=0&&this._currentFrame<this.frames.length?this.frames[this._currentFrame]:null}get currentFrameIndex(){return this._currentFrame}get isPlaying(){return this._playing}reverse(){this.frames=this.frames.slice().reverse(),this._reversed=!this._reversed}get direction(){return!(!this._reversed||1!==this._direction)?ln.Backward:ln.Forward}play(){this._playing=!0}pause(){this._playing=!1,this._firstTick=!0}reset(){this._done=!1,this._firstTick=!0,this._currentFrame=0}get canFinish(){switch(this.strategy){case cn.End:case cn.Freeze:return!0;default:return!1}}get done(){return this._done}goToFrame(t){var e,i;this._currentFrame=t,this._timeLeftInFrame=this.frameDuration;const s=this.frames[this._currentFrame];s&&!this._done&&(this._timeLeftInFrame=(null==s?void 0:s.duration)||this.frameDuration,this.width=null===(e=s.graphic)||void 0===e?void 0:e.width,this.height=null===(i=s.graphic)||void 0===i?void 0:i.height,this.events.emit("frame",s))}_nextFrame(){const t=this._currentFrame;if(this._done)return t;let e=-1;switch(this.strategy){case cn.Loop:e=(t+1)%this.frames.length,0===e&&this.events.emit("loop",this);break;case cn.End:e=t+1,e>=this.frames.length&&(this._done=!0,this._currentFrame=this.frames.length,this.events.emit("end",this));break;case cn.Freeze:e=L(t+1,0,this.frames.length-1),e>=this.frames.length-1&&(this._done=!0,this.events.emit("end",this));break;case cn.PingPong:t+this._direction>=this.frames.length&&(this._direction=-1,this.events.emit("loop",this)),t+this._direction<0&&(this._direction=1,this.events.emit("loop",this)),e=t+this._direction%this.frames.length}return e}tick(t,e=0){this._idempotencyToken!==e&&(this._idempotencyToken=e,this._playing&&(this._firstTick&&(this._firstTick=!1,this.events.emit("frame",this.currentFrame)),this._timeLeftInFrame-=t*this.timeScale,this._timeLeftInFrame<=0&&this.goToFrame(this._nextFrame()),this._updateDimensions()))}_updateDimensions(){var t,e;this.currentFrame&&(this.width=null===(t=this.currentFrame.graphic)||void 0===t?void 0:t.width,this.height=null===(e=this.currentFrame.graphic)||void 0===e?void 0:e.height)}_drawImage(t,e,i){this.currentFrame&&this.currentFrame.graphic.draw(t,e,i)}}un._LOGGER=_.getInstance();class pn extends yt{constructor(t){super(t),this.members=[],this.members=t.members,this._updateDimensions()}clone(){return new pn({members:[...this.members],...this.cloneGraphicOptions()})}_updateDimensions(){let t=new B;for(const{graphic:e,pos:i}of this.members)t=e.localBounds.translate(i).combine(t);return this.width=t.width,this.height=t.height,t}get localBounds(){let t=new B;for(const{graphic:e,pos:i}of this.members)t=e.localBounds.translate(i).combine(t);return t}_isAnimationOrGroup(t){return t instanceof un||t instanceof pn}tick(t,e){for(const i of this.members){const s=i.graphic;this._isAnimationOrGroup(s)&&s.tick(t,e)}}reset(){for(const t of this.members){const e=t.graphic;this._isAnimationOrGroup(e)&&e.reset()}}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,e,i)}_drawImage(t,e,i){for(const s of this.members)t.save(),t.translate(e,i),s.graphic.draw(t,s.pos.x,s.pos.y),this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}}!function(t){t[t.Circle=0]="Circle",t[t.Rectangle=1]="Rectangle"}(dn||(dn={}));class gn extends Xi{constructor(t,e,i,s,n,r,o,a,h,l){super(),this.position=new A(0,0),this.velocity=new A(0,0),this.acceleration=new A(0,0),this.particleRotationalVelocity=0,this.currentRotation=0,this.focus=null,this.focusAccel=0,this.opacity=1,this.beginColor=T.White,this.endColor=T.White,this.life=300,this.fadeFlag=!1,this._rRate=1,this._gRate=1,this._bRate=1,this._aRate=0,this._currentColor=T.White,this.emitter=null,this.particleSize=5,this.particleSprite=null,this.sizeRate=0,this.elapsedMultiplier=0,this.visible=!0,this.isOffscreen=!1;let c=t;if(c&&!(t instanceof mn)){const d=t;c=d.emitter,e=d.life,i=d.opacity,n=d.endColor,s=d.beginColor,r=d.position,o=d.velocity,a=d.acceleration,h=d.startSize,l=d.endSize}this.emitter=c,this.life=e||this.life,this.opacity=i||this.opacity,this.endColor=n||this.endColor.clone(),this.beginColor=s||this.beginColor.clone(),this._currentColor=this.beginColor.clone(),this.position=(r||this.position).add(this.emitter.pos),this.velocity=o||this.velocity,this.acceleration=a||this.acceleration,this._rRate=(this.endColor.r-this.beginColor.r)/this.life,this._gRate=(this.endColor.g-this.beginColor.g)/this.life,this._bRate=(this.endColor.b-this.beginColor.b)/this.life,this._aRate=this.opacity/this.life,this.startSize=h||0,this.endSize=l||0,this.endSize>0&&this.startSize>0&&(this.sizeRate=(this.endSize-this.startSize)/this.life,this.particleSize=this.startSize),this.addComponent(this.transform=new gi),this.addComponent(new ji((t=>this.draw(t)))),this.addComponent(this.graphics=new Yi),this.transform.pos=this.position,this.transform.rotation=this.currentRotation,this.transform.scale=S(1,1),this.particleSprite?(this.graphics.opacity=this.opacity,this.graphics.use(Se.fromLegacySprite(this.particleSprite))):this.graphics.onPostDraw=t=>{t.save(),this.graphics.opacity=this.opacity;const e=this._currentColor.clone();e.a=1,t.debug.drawPoint(S(0,0),{color:e,size:this.particleSize}),t.restore()}}kill(){this.emitter.removeParticle(this)}update(t,e){if(this.life=this.life-e,this.elapsedMultiplier=this.elapsedMultiplier+e,this.life<0&&this.kill(),this.fadeFlag&&(this.opacity=L(this._aRate*this.life,1e-4,1)),this.startSize>0&&this.endSize>0&&(this.particleSize=L(this.sizeRate*e+this.particleSize,Math.min(this.startSize,this.endSize),Math.max(this.startSize,this.endSize))),this._currentColor.r=L(this._currentColor.r+this._rRate*e,0,255),this._currentColor.g=L(this._currentColor.g+this._gRate*e,0,255),this._currentColor.b=L(this._currentColor.b+this._bRate*e,0,255),this._currentColor.a=L(this.opacity,1e-4,1),this.focus){const t=this.focus.sub(this.position).normalize().scale(this.focusAccel).scale(e/1e3);this.velocity=this.velocity.add(t)}else this.velocity=this.velocity.add(this.acceleration.scale(e/1e3));this.position=this.position.add(this.velocity.scale(e/1e3)),this.particleRotationalVelocity&&(this.currentRotation=(this.currentRotation+this.particleRotationalVelocity*e/1e3)%(2*Math.PI)),this.transform.pos=this.position,this.transform.rotation=this.currentRotation,this.transform.scale=S(1,1),this.graphics.opacity=this.opacity}draw(t){if(this.particleSprite)return this.particleSprite.opacity(this.opacity),void this.particleSprite.draw(t,0,0);t.save(),this._currentColor.a=L(this.opacity,1e-4,1),t.fillStyle=this._currentColor.toString(),t.beginPath(),t.arc(0,0,this.particleSize,0,2*Math.PI),t.fill(),t.closePath(),t.restore()}}class _n extends(xe(gn)){constructor(t,e,i,s,n,r,o,a,h,l){super(t,e,i,s,n,r,o,a,h,l)}}class mn extends Cs{constructor(t){var e,i;super({width:null!==(e=t.width)&&void 0!==e?e:0,height:null!==(i=t.height)&&void 0!==i?i:0}),this._particlesToEmit=0,this.numParticles=0,this.isEmitting=!0,this.particles=[],this.deadParticles=[],this.minVel=0,this.maxVel=0,this.acceleration=new A(0,0),this.minAngle=0,this.maxAngle=0,this.emitRate=1,this.particleLife=2e3,this.fadeFlag=!1,this.focus=null,this.focusAccel=null,this.startSize=null,this.endSize=null,this.minSize=5,this.maxSize=5,this.beginColor=T.White,this.endColor=T.White,this._og=null,this._sprite=null,this.emitterType=dn.Rectangle,this.radius=0,this.particleRotationalVelocity=0,this.randomRotation=!1;const{x:s,y:n,pos:r,isEmitting:o,minVel:a,maxVel:h,acceleration:l,minAngle:c,maxAngle:d,emitRate:u,particleLife:p,opacity:g,fadeFlag:_,focus:m,focusAccel:f,startSize:w,endSize:y,minSize:v,maxSize:x,beginColor:b,endColor:C,particleSprite:P,emitterType:E,radius:R,particleRotationalVelocity:B,randomRotation:M,random:F}={...t};this.pos=null!=r?r:S(null!=s?s:0,null!=n?n:0),this.isEmitting=null!=o?o:this.isEmitting,this.minVel=null!=a?a:this.minVel,this.maxVel=null!=h?h:this.maxVel,this.acceleration=null!=l?l:this.acceleration,this.minAngle=null!=c?c:this.minAngle,this.maxAngle=null!=d?d:this.maxAngle,this.emitRate=null!=u?u:this.emitRate,this.particleLife=null!=p?p:this.particleLife,this.opacity=null!=g?g:this.opacity,this.fadeFlag=null!=_?_:this.fadeFlag,this.focus=null!=m?m:this.focus,this.focusAccel=null!=f?f:this.focusAccel,this.startSize=null!=w?w:this.startSize,this.endSize=null!=y?y:this.endSize,this.minSize=null!=v?v:this.minSize,this.maxSize=null!=x?x:this.maxSize,this.beginColor=null!=b?b:this.beginColor,this.endColor=null!=C?C:this.endColor,this.particleSprite=null!=P?P:this.particleSprite,this.emitterType=null!=E?E:this.emitterType,this.radius=null!=R?R:this.radius,this.particleRotationalVelocity=null!=B?B:this.particleRotationalVelocity,this.randomRotation=null!=M?M:this.randomRotation,this.body.collisionType=ni.PreventCollision,this.random=null!=F?F:new D;for(let t=0;t<this.traits.length;t++)this.traits[t]instanceof Hi&&this.traits.splice(t,1)}get opacity(){return super.graphics.opacity}set opacity(t){super.graphics.opacity=t}get particleSprite(){return this._og}set particleSprite(t){this._og=t,t&&(this._sprite=Se.fromLegacySprite(t))}removeParticle(t){this.deadParticles.push(t)}emitParticles(t){var e;for(let i=0;i<t;i++){const t=this._createParticle();this.particles.push(t),(null===(e=null==this?void 0:this.scene)||void 0===e?void 0:e.world)&&this.scene.world.add(t)}}clearParticles(){this.particles.length=0}_createParticle(){let t=0,e=0;const i=z(this.minAngle,this.maxAngle,this.random),s=z(this.minVel,this.maxVel,this.random),n=this.startSize||z(this.minSize,this.maxSize,this.random),r=s*Math.cos(i),o=s*Math.sin(i);if(this.emitterType===dn.Rectangle)t=z(0,this.width,this.random),e=z(0,this.height,this.random);else if(this.emitterType===dn.Circle){const s=z(0,this.radius,this.random);t=s*Math.cos(i),e=s*Math.sin(i)}const a=new _n(this,this.particleLife,this.opacity,this.beginColor,this.endColor,new A(t,e),new A(r,o),this.acceleration,this.startSize,this.endSize);return a.fadeFlag=this.fadeFlag,a.particleSize=n,this.particleSprite&&(a.particleSprite=this.particleSprite,a.graphics.opacity=this.opacity,a.graphics.use(this._sprite)),a.particleRotationalVelocity=this.particleRotationalVelocity,this.randomRotation&&(a.currentRotation=z(0,2*Math.PI,this.random)),this.focus&&(a.focus=this.focus.add(new A(this.pos.x,this.pos.y)),a.focusAccel=this.focusAccel),a}update(t,e){var i;super.update(t,e),this.isEmitting&&(this._particlesToEmit+=this.emitRate*(e/1e3),this._particlesToEmit>1&&(this.emitParticles(Math.floor(this._particlesToEmit)),this._particlesToEmit=this._particlesToEmit-Math.floor(this._particlesToEmit)));for(let t=0;t<this.deadParticles.length;t++)G(this.deadParticles[t],this.particles),(null===(i=null==this?void 0:this.scene)||void 0===i?void 0:i.world)&&this.scene.world.remove(this.deadParticles[t],!1);this.deadParticles.length=0}draw(t){this.particles.forEach((e=>e.draw(t)))}debugDraw(t){super.debugDraw(t),t.fillStyle=T.Black.toString(),t.fillText("Particles: "+this.particles.length,this.pos.x,this.pos.y+20),this.focus&&(t.fillRect(this.focus.x+this.pos.x,this.focus.y+this.pos.y,3,3),Ze(t,T.Yellow,this.focus.x+this.pos.x,this.focus.y+this.pos.y,this.center.x,this.center.y),t.fillText("Focus",this.focus.x+this.pos.x,this.focus.y+this.pos.y))}}class fn extends Gs{constructor(){super(...arguments),this.types=["ex.transform","ex.graphics"],this.systemType=Vs.Draw,this.priority=0,this._token=0}initialize(t){this._graphicsContext=t.engine.graphicsContext,this._camera=t.camera,this._engine=t.engine}sort(t,e){return t.get(gi).z-e.get(gi).z}update(t,e){let i,s;this._clearScreen(),this._token++;for(const n of t){i=n.get(gi),s=n.get(Yi);const t=this._isOffscreen(i,s);if(t&&!n.hasTag("offscreen")&&(n.eventDispatcher.emit("exitviewport",new ne(n)),n.addComponent(new ui("offscreen"))),!t&&n.hasTag("offscreen")&&(n.eventDispatcher.emit("enterviewport",new re(n)),n.removeComponent("offscreen")),t)continue;this._pushCameraTransform(i),this._graphicsContext.save(),s.update(e,this._token),this._applyTransform(n),s.onPreDraw&&s.onPreDraw(this._graphicsContext,e);const r=n instanceof _n?n.opacity:1;this._graphicsContext.opacity=s.opacity*r,this._drawGraphicsComponent(s),s.onPostDraw&&s.onPostDraw(this._graphicsContext,e),this._graphicsContext.restore(),this._popCameraTransform(i)}this._graphicsContext.flush(),this._engine.stats.currFrame.graphics.drawnImages=rt.DrawnImagesCount,this._engine.stats.currFrame.graphics.drawCalls=rt.DrawCallCount}_clearScreen(){this._graphicsContext.clear()}_isOffscreen(t,e){if(t.coordPlane===pi.World){return!this._camera.viewport.intersect(e.localBounds.transform(t.getGlobalMatrix()))}return!1}_drawGraphicsComponent(t){var e,i;if(t.visible)for(const s of t.layers.get())for(const{graphic:n,options:r}of s.graphics){let o=t.anchor,a=t.offset;(null==r?void 0:r.anchor)&&(o=r.anchor),(null==r?void 0:r.offset)&&(a=r.offset);const h=-n.width*o.x+a.x,l=-n.height*o.y+a.y;if(null==n||n.draw(this._graphicsContext,h+s.offset.x,l+s.offset.y),(null===(e=this._engine)||void 0===e?void 0:e.isDebug)&&this._engine.debug.graphics.showBounds){const t=S(h+s.offset.x,l+s.offset.y);if(n instanceof pn)for(const e of n.members)null===(i=e.graphic)||void 0===i||i.localBounds.translate(t.add(e.pos)).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor);else null==n||n.localBounds.translate(t).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor)}}}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(gi);e&&(this._graphicsContext.translate(e.pos.x,e.pos.y),this._graphicsContext.scale(e.scale.x,e.scale.y),this._graphicsContext.rotate(e.rotation))}}_pushCameraTransform(t){t.coordPlane===pi.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===pi.World&&this._graphicsContext.restore()}}class wn extends Gs{constructor(){super(...arguments),this.types=["ex.transform","ex.canvas"],this.systemType=Vs.Draw,this.priority=-1}initialize(t){this._ctx=t.engine.ctx,this._engine=t.engine,this._camera=t.camera}sort(t,e){return t.get(gi).z-e.get(gi).z}update(t,e){var i,s,n;let r,o;this._clearScreen();const a=t.length;for(let h=0;h<a;h++){const a=null===(n=null===(s=null===(i=t[h])||void 0===i?void 0:i.graphics)||void 0===s?void 0:s.visible)||void 0===n||n,l=t[h].isOffScreen;a&&!l&&(r=t[h].get(gi),o=t[h].get(ji),this._ctx.save(),this._pushCameraTransform(r),this._ctx.save(),this._applyTransform(t[h]),o.draw(this._ctx,e),this._ctx.restore(),this._popCameraTransform(r),this._ctx.restore()),this._engine.isDebug&&(this._ctx.save(),this._pushCameraTransform(r),this._ctx.strokeStyle="yellow",t[h].debugDraw(this._ctx),this._popCameraTransform(r),this._ctx.restore())}this._engine.isDebug&&(this._ctx.save(),this._camera.draw(this._ctx),this._camera.debugDraw(this._ctx),this._ctx.restore()),this._engine.stats.currFrame.graphics.drawnImages=rt.DrawnImagesCount,this._engine.stats.currFrame.graphics.drawCalls=rt.DrawCallCount}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(gi);e&&(this._ctx.translate(e.pos.x,e.pos.y),this._ctx.rotate(e.rotation),this._ctx.scale(e.scale.x,e.scale.y))}}_clearScreen(){this._ctx.clearRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height),this._ctx.fillStyle=this._engine.backgroundColor.toString(),this._ctx.fillRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height)}_pushCameraTransform(t){t.coordPlane===pi.World&&(this._ctx.save(),this._camera&&this._camera.draw(this._ctx))}_popCameraTransform(t){t.coordPlane===pi.World&&this._ctx.restore()}}class yn extends Gs{constructor(){super(...arguments),this.types=["ex.transform"],this.systemType=Vs.Draw,this.priority=999}initialize(t){this._graphicsContext=t.engine.graphicsContext,this._camera=t.camera,this._engine=t.engine,this._collisionSystem=t.world.systemManager.get(hn)}update(t,e){var i,s;if(!this._engine.isDebug)return;const n=this._engine.debug.filter;let r,o;const a=this._engine.debug.entity;let h;const l=this._engine.debug.transform;let c;const d=this._engine.debug.motion;let u;const p=this._engine.debug.collider,g=this._engine.debug.physics;let _;const m=this._engine.debug.graphics;let f;const w=this._engine.debug.body,y=this._engine.debug.camera;for(const e of t){if(e.hasTag("offscreen"))continue;if(e instanceof _n)continue;if(n.useFilter){if(!(0===n.ids.length||n.ids.includes(e.id)))continue;if(!(""===n.nameQuery||e.name.includes(n.nameQuery)))continue}let t=A.Zero;const g=S(0,16);if(r=e.id,o=e.name,h=e.get(gi),this._pushCameraTransform(h),this._graphicsContext.save(),this._applyTransform(e),h&&((l.showAll||l.showPosition)&&(this._graphicsContext.debug.drawPoint(A.Zero,{size:2,color:l.positionColor}),this._graphicsContext.debug.drawText(`pos${h.pos.toString(2)}`,t),t=t.add(g)),(a.showAll||a.showId)&&(this._graphicsContext.debug.drawText(`id(${r}) ${h.parent?"child of id("+(null===(s=null===(i=h.parent)||void 0===i?void 0:i.owner)||void 0===s?void 0:s.id)+")":""}`,t),t=t.add(g)),(a.showAll||a.showName)&&(this._graphicsContext.debug.drawText(`name(${o})`,t),t=t.add(g)),(l.showAll||l.showRotation)&&(this._graphicsContext.drawLine(A.Zero,A.fromAngle(h.rotation).scale(50).add(A.Zero),l.rotationColor,2),this._graphicsContext.debug.drawText(`rot deg(${H(h.rotation).toFixed(2)})`,t),t=t.add(g)),(l.showAll||l.showScale)&&this._graphicsContext.drawLine(A.Zero,h.scale.add(A.Zero),l.scaleColor,2)),_=e.get(Yi),_&&(m.showAll||m.showBounds)){_.localBounds.draw(this._graphicsContext,m.boundsColor)}if(f=e.get(Oi),f&&((w.showAll||w.showCollisionGroup)&&(this._graphicsContext.debug.drawText(`collision group(${f.group.name})`,t),t=t.add(g)),(w.showAll||w.showCollisionType)&&(this._graphicsContext.debug.drawText(`collision type(${f.collisionType})`,t),t=t.add(g)),(w.showAll||w.showMass)&&(this._graphicsContext.debug.drawText(`mass(${f.mass})`,t),t=t.add(g)),(w.showAll||w.showMotion)&&(this._graphicsContext.debug.drawText(`motion(${f.sleepMotion})`,t),t=t.add(g)),(w.showAll||w.showSleeping)&&(this._graphicsContext.debug.drawText(`sleeping(${f.canSleep?f.sleeping:"cant sleep"})`,t),t=t.add(g))),this._graphicsContext.restore(),c=e.get(_i),c&&((d.showAll||d.showVelocity)&&(this._graphicsContext.debug.drawText(`vel${c.vel.toString(2)}`,t.add(h.globalPos)),this._graphicsContext.drawLine(h.globalPos,h.globalPos.add(c.vel),d.velocityColor,2),t=t.add(g)),(d.showAll||d.showAcceleration)&&this._graphicsContext.drawLine(h.globalPos,h.globalPos.add(c.acc),d.accelerationColor,2)),u=e.get(Li),u){const t=u.get();if((p.showAll||p.showGeometry)&&t&&t.debug(this._graphicsContext,p.geometryColor),p.showAll||p.showBounds)if(t instanceof Si){const e=t.getColliders();for(const t of e){const e=t.bounds,i=S(e.left,e.top);this._graphicsContext.debug.drawRect(i.x,i.y,e.width,e.height,{color:p.boundsColor}),(p.showAll||p.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${t.owner.id})`,i)}u.bounds.draw(this._graphicsContext,p.boundsColor)}else if(t){const t=u.bounds,e=S(t.left,t.top);this._graphicsContext.debug.drawRect(e.x,e.y,t.width,t.height,{color:p.boundsColor}),(p.showAll||p.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${u.owner.id})`,e)}}this._popCameraTransform(h)}if(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(g.showAll||g.showBroadphaseSpacePartitionDebug)&&this._collisionSystem.debug(this._graphicsContext),g.showAll||g.showCollisionContacts||g.showCollisionNormals)for(const[t,e]of this._engine.debug.stats.currFrame.physics.contacts){if(g.showAll||g.showCollisionContacts)for(const t of e.points)this._graphicsContext.debug.drawPoint(t,{size:5,color:g.collisionContactColor});if(g.showAll||g.showCollisionNormals)for(const t of e.points)this._graphicsContext.debug.drawLine(t,e.normal.scale(30).add(t),{color:g.collisionNormalColor})}this._graphicsContext.restore(),y&&(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(y.showAll||y.showFocus)&&this._graphicsContext.drawCircle(this._camera.pos,4,y.focusColor),(y.showAll||y.showZoom)&&this._graphicsContext.debug.drawText(`zoom(${this._camera.zoom})`,this._camera.pos),this._graphicsContext.restore()),this._graphicsContext.flush()}_applyTransform(t){const e=t.getAncestors();for(const t of e){const e=null==t?void 0:t.get(gi);e&&(this._graphicsContext.translate(e.pos.x,e.pos.y),this._graphicsContext.scale(e.scale.x,e.scale.y),this._graphicsContext.rotate(e.rotation))}}_pushCameraTransform(t){t.coordPlane===pi.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===pi.World&&this._graphicsContext.restore()}}class vn extends Gs{constructor(){super(...arguments),this.types=["ex.transform","ex.pointer"],this.systemType=Vs.Update,this.priority=-1,this.lastFrameEntityToPointers=new Map,this.currentFrameEntityToPointers=new Map}initialize(t){this._engine=t.engine,this._receiver=this._engine.input.pointers}sort(t,e){return e.get(gi).z-t.get(gi).z}entityCurrentlyUnderPointer(t,e){return this.currentFrameEntityToPointers.has(t.id)&&this.currentFrameEntityToPointers.get(t.id).includes(e)}entityWasUnderPointer(t,e){return this.lastFrameEntityToPointers.has(t.id)&&this.lastFrameEntityToPointers.get(t.id).includes(e)}entered(t,e){return this.entityCurrentlyUnderPointer(t,e)&&!this.lastFrameEntityToPointers.has(t.id)}left(t,e){return!this.currentFrameEntityToPointers.has(t.id)&&this.entityWasUnderPointer(t,e)}addPointerToEntity(t,e){if(!this.currentFrameEntityToPointers.has(t.id))return void this.currentFrameEntityToPointers.set(t.id,[e]);const i=this.currentFrameEntityToPointers.get(t.id);this.currentFrameEntityToPointers.set(t.id,i.concat(e))}update(t){this._processPointerToEntity(t),this._dispatchEvents(t),this._receiver.update(),this.lastFrameEntityToPointers.clear(),this.lastFrameEntityToPointers=new Map(this.currentFrameEntityToPointers),this.currentFrameEntityToPointers.clear(),this._receiver.clear()}_processPointerToEntity(t){var e;let i,s,n,r;for(const o of t){if(i=o.get(gi),r=null!==(e=o.get(Ji))&&void 0!==e?e:new Ji,s=o.get(Li),s&&r.useColliderShape){const t=s.get();if(t)for(const[e,i]of this._receiver.currentFramePointerPositions.entries())t.contains(i)&&this.addPointerToEntity(o,e)}if(n=o.get(Yi),n&&r.useGraphicsBounds){const t=n.localBounds.transform(i.getGlobalMatrix());for(const[e,i]of this._receiver.currentFramePointerPositions.entries())t.contains(i)&&this.addPointerToEntity(o,e)}}}_processDownAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameDown)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointerdown",i),this._receiver.isDragStart(i.pointerId)&&t.events.emit("pointerdragstart",i)),e.set(i.pointerId,i);return e}_processUpAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameUp)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointerup",i),this._receiver.isDragEnd(i.pointerId)&&t.events.emit("pointerdragend",i)),e.set(i.pointerId,i);return e}_processMoveAndEmit(t){const e=new Map;for(const i of this._receiver.currentFrameMove)i.active&&t.active&&this.entityCurrentlyUnderPointer(t,i.pointerId)&&(t.events.emit("pointermove",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragmove",i)),e.set(i.pointerId,i);return e}_processEnterLeaveAndEmit(t,e){for(const i of e){if(i.active&&t.active&&this.entered(t,i.pointerId)){t.events.emit("pointerenter",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragenter",i);break}if(i.active&&t.active&&(this.left(t,i.pointerId)||this.entityCurrentlyUnderPointer(t,i.pointerId)&&"up"===i.type)){t.events.emit("pointerleave",i),this._receiver.isDragging(i.pointerId)&&t.events.emit("pointerdragleave",i);break}}}_processCancelAndEmit(t){for(const e of this._receiver.currentFrameCancel)e.active&&t.active&&this.entityCurrentlyUnderPointer(t,e.pointerId)&&t.events.emit("pointercancel",e)}_processWheelAndEmit(t){for(const e of this._receiver.currentFrameWheel)e.active&&t.active&&this.entityCurrentlyUnderPointer(t,0)&&t.events.emit("pointerwheel",e)}_dispatchEvents(t){const e=new Set(this.lastFrameEntityToPointers.keys()),i=new Set(this.currentFrameEntityToPointers.keys()),s=t.filter((t=>e.has(t.id)||i.has(t.id)));let n,r,o;for(const t of s){o=this._processDownAndEmit(t),r=this._processUpAndEmit(t),n=this._processMoveAndEmit(t);const e=[...n.values(),...o.values(),...r.values()];this._processEnterLeaveAndEmit(t,e),this._processCancelAndEmit(t),this._processWheelAndEmit(t)}}}class xn extends Gs{constructor(){super(...arguments),this.types=["ex.actions"],this.systemType=Vs.Update,this.priority=-1}update(t,e){let i;for(const s of t)i=s.get(xs),i.update(e)}}var bn,Cn,An,Sn,Pn,En,Tn,Rn,Bn,Mn=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class Dn extends Ke{constructor(){super(),this._logger=_.getInstance(),this.camera=new Us,this.world=new tn(this),this._isInitialized=!1,this._timers=[],this._cancelQueue=[],this.world.add(new xn),this.world.add(new sn),this.world.add(new hn),this.world.add(new vn),p.isEnabled(c.LegacyDrawing)?this.world.add(new wn):this.world.add(new fn),this.world.add(new yn)}get actors(){return this.world.entityManager.entities.filter((t=>t instanceof Cs))}get entities(){return this.world.entityManager.entities}get triggers(){return this.world.entityManager.entities.filter((t=>t instanceof Ws))}get tileMaps(){return this.world.entityManager.entities.filter((t=>t instanceof Bs))}get screenElements(){return this.actors.filter((t=>t instanceof As))}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}onInitialize(t){}onActivate(t,e){}onDeactivate(t,e){}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreDraw(t,e){}onPostDraw(t,e){}_initializeChildren(){for(const t of this.entities)t._initialize(this.engine)}get isInitialized(){return this._isInitialized}_initialize(t){this.isInitialized||(this.engine=t,this.camera._initialize(t),this.world.systemManager.initialize(),this.onInitialize.call(this,t),this._initializeChildren(),this._logger.debug("Scene.onInitialize",this,t),this.eventDispatcher.emit("initialize",new ee(t,this)),this._isInitialized=!0)}_activate(t,e){this._logger.debug("Scene.onActivate",this),this.onActivate(t,e)}_deactivate(t,e){this._logger.debug("Scene.onDeactivate",this),this.onDeactivate(t,e)}_preupdate(t,e){this.emit("preupdate",new It(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new Lt(t,e,this)),this.onPostUpdate(t,e)}_predraw(t,e){this.emit("predraw",new Mt(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new Dt(t,e,this)),this.onPostDraw(t,e)}update(t,e){let i,s;for(this._preupdate(t,e),this.camera&&this.camera.update(t,e),i=0,s=this._cancelQueue.length;i<s;i++)this.removeTimer(this._cancelQueue[i]);this._cancelQueue.length=0;for(const t of this._timers)t.update(e);this.world.update(Vs.Update,e),this._collectActorStats(t),this._postupdate(t,e)}draw(t,e){var i;this._predraw(t,e),this.world.update(Vs.Draw,e),(null===(i=this.engine)||void 0===i?void 0:i.isDebug)&&this.debugDraw(t),this._postdraw(t,e)}debugDraw(t){this.emit("predebugdraw",new Ft(t,this)),this.emit("postdebugdraw",new kt(t,this))}contains(t){return this.actors.indexOf(t)>-1}add(t){this.emit("entityadded",{target:t}),this.world.add(t),t.scene=this,t instanceof Ps&&(X(this._timers,t)||this.addTimer(t))}remove(t){t instanceof Xi&&(this.emit("entityremoved",{target:t}),this.world.remove(t)),t instanceof Ps&&this.removeTimer(t)}addScreenElement(t){this.add(t)}removeScreenElement(t){this.remove(t)}addTileMap(t){this.world.add(t)}removeTileMap(t){this.world.remove(t)}addTimer(t){return this._timers.push(t),t.scene=this,t}removeTimer(t){const e=this._timers.indexOf(t);return-1!==e&&this._timers.splice(e,1),t}cancelTimer(t){return this._cancelQueue.push(t),t}isTimerActive(t){return this._timers.indexOf(t)>-1&&!t.complete}isCurrentScene(){return!!this.engine&&this.engine.currentScene===this}_collectActorStats(t){const e=this.actors.filter((t=>t instanceof As));for(const i of e)t.stats.currFrame.actors.ui++;for(const e of this.actors){t.stats.currFrame.actors.alive++;for(const i of e.children)Hs(i)?t.stats.currFrame.actors.ui++:t.stats.currFrame.actors.alive++}}}Mn([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"ScreenElements now are normal actors with a Transform Coordinate Plane of Screen"})],Dn.prototype,"screenElements",null),Mn([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Scene.add"})],Dn.prototype,"addScreenElement",null),Mn([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Scene.remove"})],Dn.prototype,"removeScreenElement",null),Mn([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Scene.add"})],Dn.prototype,"addTileMap",null),Mn([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Scene.remove"})],Dn.prototype,"removeTileMap",null),function(t){t[t.Protanope=0]="Protanope",t[t.Deuteranope=1]="Deuteranope",t[t.Tritanope=2]="Tritanope"}(bn||(bn={}));class Fn{constructor(t,e=!1,i=bn.Protanope){this.engine=t,this.simulate=e,this.colorMode=i,this._vertexShader="attribute vec2 a_position;attribute vec2 a_texCoord;uniform vec2 u_resolution;varying vec2 v_texCoord;void main() {vec2 zeroToOne = a_position / u_resolution;vec2 zeroToTwo = zeroToOne * 2.0;vec2 clipSpace = zeroToTwo - 1.0;gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);v_texCoord = a_texCoord;}",this._fragmentShader="precision mediump float;uniform sampler2D u_image;varying vec2 v_texCoord;void main() {vec4 o = texture2D(u_image, v_texCoord);float L = (17.8824 * o.r) + (43.5161 * o.g) + (4.11935 * o.b);float M = (3.45565 * o.r) + (27.1554 * o.g) + (3.86714 * o.b);float S = (0.0299566 * o.r) + (0.184309 * o.g) + (1.46709 * o.b);//MODE CODE//vec4 error;error.r = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s);error.g = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s);error.b = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s);error.a = 1.0;vec4 diff = o - error;vec4 correction;correction.r = 0.0;correction.g = (diff.r * 0.7) + (diff.g * 1.0);correction.b = (diff.r * 0.7) + (diff.b * 1.0);correction = o + correction;correction.a = o.a;//SIMULATE//}",this._internalCanvas=document.createElement("canvas"),this._internalCanvas.width=t.drawWidth,this._internalCanvas.height=t.drawHeight,this._gl=this._internalCanvas.getContext("webgl",{preserveDrawingBuffer:!0}),this._program=this._gl.createProgram();const s=this._getShader("Fragment",this._getFragmentShaderByMode(i)),n=this._getShader("Vertex",this._vertexShader);this._gl.attachShader(this._program,n),this._gl.attachShader(this._program,s),this._gl.linkProgram(this._program),this._gl.getProgramParameter(this._program,this._gl.LINK_STATUS)||_.getInstance().error("Unable to link shader program!"),this._gl.useProgram(this._program)}_getFragmentShaderByMode(t){let e="";return t===bn.Protanope?e="float l = 0.0 * L + 2.02344 * M + -2.52581 * S;float m = 0.0 * L + 1.0 * M + 0.0 * S;float s = 0.0 * L + 0.0 * M + 1.0 * S;":t===bn.Deuteranope?e="float l = 1.0 * L + 0.0 * M + 0.0 * S;float m = 0.494207 * L + 0.0 * M + 1.24827 * S;float s = 0.0 * L + 0.0 * M + 1.0 * S;":t===bn.Tritanope&&(e="float l = 1.0 * L + 0.0 * M + 0.0 * S;float m = 0.0 * L + 1.0 * M + 0.0 * S;float s = -0.395913 * L + 0.801109 * M + 0.0 * S;"),this.simulate?this._fragmentShader=this._fragmentShader.replace("//SIMULATE//","gl_FragColor = error.rgba;"):this._fragmentShader=this._fragmentShader.replace("//SIMULATE//","gl_FragColor = correction.rgba;"),this._fragmentShader.replace("//MODE CODE//",e)}_setRectangle(t,e,i,s){const n=t,r=t+i,o=e,a=e+s;this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array([n,o,r,o,n,a,n,a,r,o,r,a]),this._gl.STATIC_DRAW)}_getShader(t,e){let i;return"Fragment"===t?i=this._gl.createShader(this._gl.FRAGMENT_SHADER):"Vertex"===t?i=this._gl.createShader(this._gl.VERTEX_SHADER):_.getInstance().error("Error unknown shader type",t),this._gl.shaderSource(i,e),this._gl.compileShader(i),this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)?i:(_.getInstance().error("Unable to compile shader!",this._gl.getShaderInfoLog(i)),null)}process(t,e){const i=this._gl.getAttribLocation(this._program,"a_position"),s=this._gl.getAttribLocation(this._program,"a_texCoord"),n=this._gl.createBuffer();this._gl.bindBuffer(this._gl.ARRAY_BUFFER,n),this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this._gl.STATIC_DRAW),this._gl.enableVertexAttribArray(s),this._gl.vertexAttribPointer(s,2,this._gl.FLOAT,!1,0,0);const r=this._gl.createTexture();this._gl.bindTexture(this._gl.TEXTURE_2D,r),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.NEAREST),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.NEAREST),this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,1),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);const o=this._gl.getUniformLocation(this._program,"u_resolution");this._gl.uniform2f(o,this._internalCanvas.width,this._internalCanvas.height);const a=this._gl.createBuffer();this._gl.bindBuffer(this._gl.ARRAY_BUFFER,a),this._gl.enableVertexAttribArray(i),this._gl.vertexAttribPointer(i,2,this._gl.FLOAT,!1,0,0),this._setRectangle(0,0,t.width,t.height),this._gl.drawArrays(this._gl.TRIANGLES,0,6);const h=new Uint8Array(t.width*t.height*4);this._gl.readPixels(0,0,t.width,t.height,this._gl.RGBA,this._gl.UNSIGNED_BYTE,h),t.data.set(h),e.putImageData(t,0,0)}}class kn{constructor(t){this._engine=t}correct(t){this._engine.postProcessors.push(new Fn(this._engine,!1,t))}simulate(t){this._engine.postProcessors.push(new Fn(this._engine,!0,t))}}class In{constructor(t){this.stats={currFrame:new Ln,prevFrame:new Ln},this.filter={useFilter:!1,nameQuery:"",ids:[]},this.entity={showAll:!1,showId:!0,showName:!1},this.transform={showAll:!1,showPosition:!1,positionColor:T.Yellow,showScale:!1,scaleColor:T.Green,showRotation:!1,rotationColor:T.Blue},this.graphics={showAll:!1,showBounds:!0,boundsColor:T.Yellow},this.collider={showAll:!1,showBounds:!0,boundsColor:T.Blue,showOwner:!1,showGeometry:!0,geometryColor:T.Green},this.physics={showAll:!1,showBroadphaseSpacePartitionDebug:!1,showCollisionNormals:!1,collisionNormalColor:T.Cyan,showCollisionContacts:!0,collisionContactColor:T.Red},this.motion={showAll:!1,showVelocity:!1,velocityColor:T.Yellow,showAcceleration:!1,accelerationColor:T.Red},this.body={showAll:!1,showCollisionGroup:!1,showCollisionType:!1,showSleeping:!1,showMotion:!1,showMass:!1},this.camera={showAll:!1,showFocus:!1,focusColor:T.Red,showZoom:!1},this._engine=t,this.colorBlindMode=new kn(this._engine)}useTestClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toTestClock();return e&&i.start(),this._engine.clock=i,i}useStandardClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toStandardClock();return e&&i.start(),this._engine.clock=i,i}}class Ln{constructor(){this._id=0,this._delta=0,this._fps=0,this._actorStats={alive:0,killed:0,ui:0,get remaining(){return this.alive-this.killed},get total(){return this.remaining+this.ui}},this._durationStats={update:0,draw:0,get total(){return this.update+this.draw}},this._physicsStats=new zn,this._graphicsStats={drawCalls:0,drawnImages:0}}reset(t){t?(this.id=t.id,this.delta=t.delta,this.fps=t.fps,this.actors.alive=t.actors.alive,this.actors.killed=t.actors.killed,this.actors.ui=t.actors.ui,this.duration.update=t.duration.update,this.duration.draw=t.duration.draw,this._physicsStats.reset(t.physics),this.graphics.drawCalls=t.graphics.drawCalls,this.graphics.drawnImages=t.graphics.drawnImages):(this.id=this.delta=this.fps=0,this.actors.alive=this.actors.killed=this.actors.ui=0,this.duration.update=this.duration.draw=0,this._physicsStats.reset(),this.graphics.drawnImages=this.graphics.drawCalls=0)}clone(){const t=new Ln;return t.reset(this),t}get id(){return this._id}set id(t){this._id=t}get delta(){return this._delta}set delta(t){this._delta=t}get fps(){return this._fps}set fps(t){this._fps=t}get actors(){return this._actorStats}get duration(){return this._durationStats}get physics(){return this._physicsStats}get graphics(){return this._graphicsStats}}class zn{constructor(){this._pairs=0,this._collisions=0,this._contacts=new Map,this._fastBodies=0,this._fastBodyCollisions=0,this._broadphase=0,this._narrowphase=0}reset(t){t?(this.pairs=t.pairs,this.collisions=t.collisions,this.contacts=t.contacts,this.fastBodies=t.fastBodies,this.fastBodyCollisions=t.fastBodyCollisions,this.broadphase=t.broadphase,this.narrowphase=t.narrowphase):(this.pairs=this.collisions=this.fastBodies=0,this.fastBodyCollisions=this.broadphase=this.narrowphase=0,this.contacts.clear())}clone(){const t=new zn;return t.reset(this),t}get pairs(){return this._pairs}set pairs(t){this._pairs=t}get collisions(){return this._collisions}set collisions(t){this._collisions=t}get contacts(){return this._contacts}set contacts(t){this._contacts=t}get fastBodies(){return this._fastBodies}set fastBodies(t){this._fastBodies=t}get fastBodyCollisions(){return this._fastBodyCollisions}set fastBodyCollisions(t){this._fastBodyCollisions=t}get broadphase(){return this._broadphase}set broadphase(t){this._broadphase=t}get narrowphase(){return this._narrowphase}set narrowphase(t){this._narrowphase=t}}!function(t){t.Canvas="Canvas",t.Document="Document"}(Cn||(Cn={})),function(t){t.Num0="Numpad0",t.Num1="Numpad1",t.Num2="Numpad2",t.Num3="Numpad3",t.Num4="Numpad4",t.Num5="Numpad5",t.Num6="Numpad6",t.Num7="Numpad7",t.Num8="Numpad8",t.Num9="Numpad9",t.NumAdd="NumpadAdd",t.NumSubtract="NumpadSubtract",t.NumMultiply="NumpadMultiply",t.NumDivide="NumpadDivide",t.NumDecimal="NumpadDecimal",t.Numpad0="Numpad0",t.Numpad1="Numpad1",t.Numpad2="Numpad2",t.Numpad3="Numpad3",t.Numpad4="Numpad4",t.Numpad5="Numpad5",t.Numpad6="Numpad6",t.Numpad7="Numpad7",t.Numpad8="Numpad8",t.Numpad9="Numpad9",t.NumpadAdd="NumpadAdd",t.NumpadSubtract="NumpadSubtract",t.NumpadMultiply="NumpadMultiply",t.NumpadDivide="NumpadDivide",t.NumpadDecimal="NumpadDecimal",t.NumLock="NumLock",t.ShiftLeft="ShiftLeft",t.ShiftRight="ShiftRight",t.AltLeft="AltLeft",t.AltRight="AltRight",t.Key0="Digit0",t.Key1="Digit1",t.Key2="Digit2",t.Key3="Digit3",t.Key4="Digit4",t.Key5="Digit5",t.Key6="Digit6",t.Key7="Digit7",t.Key8="Digit8",t.Key9="Digit9",t.Digit0="Digit0",t.Digit1="Digit1",t.Digit2="Digit2",t.Digit3="Digit3",t.Digit4="Digit4",t.Digit5="Digit5",t.Digit6="Digit6",t.Digit7="Digit7",t.Digit8="Digit8",t.Digit9="Digit9",t.A="KeyA",t.B="KeyB",t.C="KeyC",t.D="KeyD",t.E="KeyE",t.F="KeyF",t.G="KeyG",t.H="KeyH",t.I="KeyI",t.J="KeyJ",t.K="KeyK",t.L="KeyL",t.M="KeyM",t.N="KeyN",t.O="KeyO",t.P="KeyP",t.Q="KeyQ",t.R="KeyR",t.S="KeyS",t.T="KeyT",t.U="KeyU",t.V="KeyV",t.W="KeyW",t.X="KeyX",t.Y="KeyY",t.Z="KeyZ",t.KeyA="KeyA",t.KeyB="KeyB",t.KeyC="KeyC",t.KeyD="KeyD",t.KeyE="KeyE",t.KeyF="KeyF",t.KeyG="KeyG",t.KeyH="KeyH",t.KeyI="KeyI",t.KeyJ="KeyJ",t.KeyK="KeyK",t.KeyL="KeyL",t.KeyM="KeyM",t.KeyN="KeyN",t.KeyO="KeyO",t.KeyP="KeyP",t.KeyQ="KeyQ",t.KeyR="KeyR",t.KeyS="KeyS",t.KeyT="KeyT",t.KeyU="KeyU",t.KeyV="KeyV",t.KeyW="KeyW",t.KeyX="KeyX",t.KeyY="KeyY",t.KeyZ="KeyZ",t.Semicolon="Semicolon",t.Quote="Quote",t.Comma="Comma",t.Minus="Minus",t.Period="Period",t.Slash="Slash",t.Equal="Equal",t.BracketLeft="BracketLeft",t.Backslash="Backslash",t.BracketRight="BracketRight",t.Backquote="Backquote",t.Up="ArrowUp",t.Down="ArrowDown",t.Left="ArrowLeft",t.Right="ArrowRight",t.ArrowUp="ArrowUp",t.ArrowDown="ArrowDown",t.ArrowLeft="ArrowLeft",t.ArrowRight="ArrowRight",t.Space="Space",t.Esc="Escape",t.Escape="Escape"}(An||(An={}));class On extends St{constructor(t,e,i){super(),this.key=t,this.value=e,this.originalEvent=i}}class Un extends Ke{constructor(){super(),this._keys=[],this._keysUp=[],this._keysDown=[]}on(t,e){super.on(t,e)}init(t){if(!t)try{const e=()=>{};window.top.addEventListener("blur",e),window.top.removeEventListener("blur",e),t=window.top}catch(e){t=window,_.getInstance().warn("Failed to bind to keyboard events to top frame. If you are trying to embed Excalibur in a cross-origin iframe, keyboard events will not fire.")}t.addEventListener("blur",(()=>{this._keys.length=0})),t.addEventListener("keyup",(t=>{const e=t.code,i=this._keys.indexOf(e);this._keys.splice(i,1),this._keysUp.push(e);const s=new On(e,t.key,t);this.eventDispatcher.emit("up",s),this.eventDispatcher.emit("release",s)})),t.addEventListener("keydown",(t=>{const e=t.code;if(-1===this._keys.indexOf(e)){this._keys.push(e),this._keysDown.push(e);const i=new On(e,t.key,t);this.eventDispatcher.emit("down",i),this.eventDispatcher.emit("press",i)}}))}update(){this._keysDown.length=0,this._keysUp.length=0;for(let t=0;t<this._keys.length;t++)this.eventDispatcher.emit("hold",new On(this._keys[t]))}getKeys(){return this._keys}wasPressed(t){return this._keysDown.indexOf(t)>-1}isHeld(t){return this._keys.indexOf(t)>-1}wasReleased(t){return this._keysUp.indexOf(t)>-1}}class Hn extends Ke{constructor(){super(),this.enabled=!1,this.supported=!!navigator.getGamepads,this._gamePadTimeStamps=[0,0,0,0],this._oldPads=[],this._pads=[],this._initSuccess=!1,this._navigator=navigator,this._minimumConfiguration=null}init(){this.supported&&(this._initSuccess||(this._oldPads=this._clonePads(this._navigator.getGamepads()),this._oldPads.length&&this._oldPads[0]&&(this._initSuccess=!0)))}setMinimumGamepadConfiguration(t){this._enableAndUpdate(),this._minimumConfiguration=t}_enableAndUpdate(){this.enabled||(this.enabled=!0,this.update())}_isGamepadValid(t){if(!this._minimumConfiguration)return!0;if(!t)return!1;const e=t.axes.filter((t=>void 0!==typeof t)).length,i=t.buttons.filter((t=>void 0!==typeof t)).length;return e>=this._minimumConfiguration.axis&&i>=this._minimumConfiguration.buttons&&t.connected}on(t,e){this._enableAndUpdate(),super.on(t,e)}off(t,e){this._enableAndUpdate(),super.off(t,e)}update(){if(!this.enabled||!this.supported)return;this.init();const t=this._navigator.getGamepads();for(let e=0;e<t.length;e++){if(!t[e]){const t=this.at(e);t.connected&&this.eventDispatcher.emit("disconnect",new Ht(e,t)),t.connected=!1;continue}if(!this.at(e).connected&&this._isGamepadValid(t[e])&&this.eventDispatcher.emit("connect",new Ut(e,this.at(e))),this.at(e).connected=!0,t[e].timestamp&&t[e].timestamp===this._gamePadTimeStamps[e])continue;let i,s,n,r,o;for(i in this._gamePadTimeStamps[e]=t[e].timestamp,this.at(e).navigatorGamepad=t[e],Sn)s=Sn[i],"number"==typeof s&&t[e].buttons[s]&&(o=t[e].buttons[s].value,o!==this._oldPads[e].getButton(s)&&(t[e].buttons[s].pressed?(this.at(e).updateButton(s,o),this.at(e).eventDispatcher.emit("button",new Nt(s,o,this.at(e)))):this.at(e).updateButton(s,0)));for(n in Pn)r=Pn[n],"number"==typeof r&&(o=t[e].axes[r],o!==this._oldPads[e].getAxes(r)&&(this.at(e).updateAxes(r,o),this.at(e).eventDispatcher.emit("axis",new Wt(r,o,this.at(e)))));this._oldPads[e]=this._clonePad(t[e])}}at(t){if(this._enableAndUpdate(),t>=this._pads.length)for(let e=this._pads.length-1,i=t;e<i;e++)this._pads.push(new Nn),this._oldPads.push(new Nn);return this._pads[t]}getValidGamepads(){this._enableAndUpdate();const t=[];for(let e=0;e<this._pads.length;e++)this._isGamepadValid(this.at(e).navigatorGamepad)&&this.at(e).connected&&t.push(this.at(e));return t}count(){return this._pads.filter((t=>t.connected)).length}_clonePads(t){const e=[];for(let i=0,s=t.length;i<s;i++)e.push(this._clonePad(t[i]));return e}_clonePad(t){let e,i;const s=new Nn;if(!t)return s;for(e=0,i=t.buttons.length;e<i;e++)t.buttons[e]&&s.updateButton(e,t.buttons[e].value);for(e=0,i=t.axes.length;e<i;e++)s.updateAxes(e,t.axes[e]);return s}}Hn.MinAxisMoveThreshold=.05;class Nn extends Ke{constructor(){super(),this.connected=!1,this._buttons=new Array(16),this._axes=new Array(4);for(let t=0;t<this._buttons.length;t++)this._buttons[t]=0;for(let t=0;t<this._axes.length;t++)this._axes[t]=0}isButtonPressed(t,e=1){return this._buttons[t]>=e}getButton(t){return this._buttons[t]}getAxes(t){const e=this._axes[t];return Math.abs(e)<Hn.MinAxisMoveThreshold?0:e}updateButton(t,e){this._buttons[t]=e}updateAxes(t,e){this._axes[t]=e}}!function(t){t[t.Face1=0]="Face1",t[t.Face2=1]="Face2",t[t.Face3=2]="Face3",t[t.Face4=3]="Face4",t[t.LeftBumper=4]="LeftBumper",t[t.RightBumper=5]="RightBumper",t[t.LeftTrigger=6]="LeftTrigger",t[t.RightTrigger=7]="RightTrigger",t[t.Select=8]="Select",t[t.Start=9]="Start",t[t.LeftStick=10]="LeftStick",t[t.RightStick=11]="RightStick",t[t.DpadUp=12]="DpadUp",t[t.DpadDown=13]="DpadDown",t[t.DpadLeft=14]="DpadLeft",t[t.DpadRight=15]="DpadRight"}(Sn||(Sn={})),function(t){t[t.LeftStickX=0]="LeftStickX",t[t.LeftStickY=1]="LeftStickY",t[t.RightStickX=2]="RightStickX",t[t.RightStickY=3]="RightStickY"}(Pn||(Pn={}));class Wn{constructor(t){this.nativeComponent=t,this._paused=!1,this._nativeHandlers={}}on(t,e){this._nativeHandlers[t]&&this.off(t,this._nativeHandlers[t]),this._nativeHandlers[t]=this._decorate(e),this.nativeComponent.addEventListener(t,this._nativeHandlers[t])}off(t,e){e||(e=this._nativeHandlers[t]),this.nativeComponent.removeEventListener(t,e),this._nativeHandlers[t]=null}_decorate(t){return e=>{this._paused||t(e)}}pause(){this._paused=!0}resume(){this._paused=!1}clear(){for(const t in this._nativeHandlers)this.off(t)}}class Vn{constructor(t,e){this._windowGlobal=t,this._documentGlobal=e,this._windowComponent=new Wn(this._windowGlobal),this._documentComponent=new Wn(this._documentGlobal)}get window(){return this._windowComponent}get document(){return this._documentComponent}pause(){this.window.pause(),this.document.pause()}resume(){this.window.resume(),this.document.resume()}clear(){this.window.clear(),this.document.clear()}}class Gn{constructor(t){this._ex=t,this._debugText=new He}drawRect(t,e,i,s){this._ex.__ctx.save(),this._ex.__ctx.strokeStyle="red",this._ex.__ctx.strokeRect(this._ex.snapToPixel?~~t:t,this._ex.snapToPixel?~~e:e,this._ex.snapToPixel?~~i:i,this._ex.snapToPixel?~~s:s),this._ex.__ctx.restore()}drawLine(t,e,i={color:T.Black}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.strokeStyle=i.color.toString(),this._ex.__ctx.moveTo(this._ex.snapToPixel?~~t.x:t.x,this._ex.snapToPixel?~~t.y:t.y),this._ex.__ctx.lineTo(this._ex.snapToPixel?~~e.x:e.x,this._ex.snapToPixel?~~e.y:e.y),this._ex.__ctx.lineWidth=2,this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawPoint(t,e={color:T.Black,size:5}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.fillStyle=e.color.toString(),this._ex.__ctx.arc(this._ex.snapToPixel?~~t.x:t.x,this._ex.snapToPixel?~~t.y:t.y,e.size,0,2*Math.PI),this._ex.__ctx.fill(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawText(t,e){this._debugText.write(this._ex,t,e)}}class Xn{constructor(t){this.backgroundColor=T.ExcaliburBlue,this._state=new it,this.snapToPixel=!0,this.debug=new Gn(this);const{canvasElement:e,enableTransparency:i,snapToPixel:s,smoothing:n,backgroundColor:r}=t;this.__ctx=e.getContext("2d",{alpha:null==i||i}),this.backgroundColor=null!=r?r:this.backgroundColor,this.snapToPixel=null!=s?s:this.snapToPixel,this.smoothing=null!=n?n:this.smoothing}get width(){return this.__ctx.canvas.width}get height(){return this.__ctx.canvas.height}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get smoothing(){return this.__ctx.imageSmoothingEnabled}set smoothing(t){this.__ctx.imageSmoothingEnabled=t}resetTransform(){this.__ctx.resetTransform()}updateViewport(){}drawImage(t,e,i,s,n,r,o,a,h){if(0===s||0===n)return;if(0===a||0===h)return;if(0===t.width||0===t.height)return;this.__ctx.globalAlpha=this.opacity;const l=[t,e,i,s,n,r,o,a,h].filter((t=>void 0!==t)).map((t=>"number"==typeof t&&this.snapToPixel?~~t:t));this.__ctx.drawImage.apply(this.__ctx,l),rt.DrawCallCount++,rt.DrawnImagesCount=1}drawLine(t,e,i,s=1){this.__ctx.save(),this.__ctx.beginPath(),this.__ctx.strokeStyle=i.toString(),this.__ctx.moveTo(this.snapToPixel?~~t.x:t.x,this.snapToPixel?~~t.y:t.y),this.__ctx.lineTo(this.snapToPixel?~~e.x:e.x,this.snapToPixel?~~e.y:e.y),this.__ctx.lineWidth=s,this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}drawRectangle(t,e,i,s){this.__ctx.save(),this.__ctx.fillStyle=s.toString(),this.__ctx.fillRect(this.snapToPixel?~~t.x:t.x,this.snapToPixel?~~t.y:t.y,this.snapToPixel?~~e:e,this.snapToPixel?~~i:i),this.__ctx.restore()}drawCircle(t,e,i){this.__ctx.save(),this.__ctx.beginPath(),this.__ctx.fillStyle=i.toString(),this.__ctx.arc(this.snapToPixel?~~t.x:t.x,this.snapToPixel?~~t.y:t.y,e,0,2*Math.PI),this.__ctx.fill(),this.__ctx.closePath(),this.__ctx.restore()}save(){this.__ctx.save()}restore(){this.__ctx.restore()}translate(t,e){this.__ctx.translate(this.snapToPixel?~~t:t,this.snapToPixel?~~e:e)}rotate(t){this.__ctx.rotate(t)}scale(t,e){this.__ctx.scale(t,e)}clear(){this.__ctx.clearRect(0,0,this.width,this.height),this.__ctx.fillStyle=this.backgroundColor.toString(),this.__ctx.fillRect(0,0,this.width,this.height),rt.clear()}flush(){}}class jn{constructor(t,e,i){this.worldPos=t,this.pagePos=e,this.screenPos=i}static fromPagePosition(t,e,i){let s,n,r,o;3===arguments.length?(s=t,n=e,r=new A(s,n),o=i):(r=t,s=r.x,n=r.y,o=e);const a=o.screen.pageToScreenCoordinates(r),h=o.screen.screenToWorldCoordinates(a);return new jn(h,r,a)}}class qn{constructor(t,e,i,s,n,r){this.type=t,this.pointerId=e,this.button=i,this.pointerType=s,this.coordinates=n,this.nativeEvent=r,this.active=!0}cancel(){this.active=!1}get pagePos(){return this.coordinates.pagePos}get screenPos(){return this.coordinates.screenPos}get worldPos(){return this.coordinates.worldPos}}class Kn{constructor(t,e,i,s,n,r,o,a,h,l,c,d){this.x=t,this.y=e,this.pageX=i,this.pageY=s,this.screenX=n,this.screenY=r,this.index=o,this.deltaX=a,this.deltaY=h,this.deltaZ=l,this.deltaMode=c,this.ev=d,this.active=!0}cancel(){this.active=!1}}class Zn extends Ke{constructor(){super(),this.lastPagePos=A.Zero,this.lastScreenPos=A.Zero,this.lastWorldPos=A.Zero,this._onPointerMove=t=>{this.lastPagePos=new A(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new A(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new A(t.worldPos.x,t.worldPos.y)},this._onPointerDown=t=>{this.lastPagePos=new A(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new A(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new A(t.worldPos.x,t.worldPos.y)},this.on("move",this._onPointerMove),this.on("down",this._onPointerDown)}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}}!function(t){t.Pixel="Pixel",t.Line="Line",t.Page="Page"}(En||(En={})),function(t){t[t.NoButton=-1]="NoButton",t[t.Left=0]="Left",t[t.Middle=1]="Middle",t[t.Right=2]="Right",t[t.Unknown=3]="Unknown"}(Tn||(Tn={})),function(t){t.Left="Left",t.Middle="Middle",t.Right="Right",t.Unknown="Unknown",t.NoButton="NoButton"}(Rn||(Rn={})),function(t){t.Touch="Touch",t.Mouse="Mouse",t.Pen="Pen",t.Unknown="Unknown"}(Bn||(Bn={}));class Yn extends Ke{constructor(t,e){super(),this.target=t,this.engine=e,this.primary=new Zn,this._activeNativePointerIdsToNormalized=new Map,this.lastFramePointerPosition=new Map,this.currentFramePointerPositions=new Map,this.currentFramePointerDown=new Map,this.lastFramePointerDown=new Map,this.currentFrameDown=[],this.currentFrameUp=[],this.currentFrameMove=[],this.currentFrameCancel=[],this.currentFrameWheel=[],this._pointers=[this.primary],this._boundHandle=this._handle.bind(this),this._boundWheel=this._handleWheel.bind(this)}at(t){if(t>=this._pointers.length)for(let e=this._pointers.length-1,i=t;e<i;e++)this._pointers.push(new Zn);return this._pointers[t]}count(){return this._pointers.length}isDown(t){var e;return null!==(e=this.currentFramePointerDown.get(t))&&void 0!==e&&e}wasDown(t){var e;return null!==(e=this.lastFramePointerDown.get(t))&&void 0!==e&&e}isDragging(t){return this.isDown(t)}isDragStart(t){return this.isDown(t)&&!this.wasDown(t)}isDragEnd(t){return!this.isDown(t)&&this.wasDown(t)}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}update(){this.lastFramePointerDown=new Map(this.currentFramePointerDown),this.lastFramePointerPosition=new Map(this.currentFramePointerPositions);for(const t of this.currentFrameDown){this.emit("down",t);this.at(t.pointerId).emit("down",t),this.primary.emit("pointerdown",t)}for(const t of this.currentFrameUp){this.emit("up",t);this.at(t.pointerId).emit("up",t)}for(const t of this.currentFrameMove){this.emit("move",t);this.at(t.pointerId).emit("move",t)}for(const t of this.currentFrameCancel){this.emit("cancel",t);this.at(t.pointerId).emit("cancel",t)}for(const t of this.currentFrameWheel)this.emit("wheel",t),this.primary.emit("pointerwheel",t)}clear(){for(const t of this.currentFrameUp){this.currentFramePointerPositions.delete(t.pointerId);const e=this._activeNativePointerIdsToNormalized.entries();for(const[i,s]of e)s===t.pointerId&&this._activeNativePointerIdsToNormalized.delete(i)}this.currentFrameDown.length=0,this.currentFrameUp.length=0,this.currentFrameMove.length=0,this.currentFrameCancel.length=0,this.currentFrameWheel.length=0}init(){this.engine.canvas.style.touchAction="none",window.PointerEvent?(this.target.addEventListener("pointerdown",this._boundHandle),this.target.addEventListener("pointerup",this._boundHandle),this.target.addEventListener("pointermove",this._boundHandle),this.target.addEventListener("pointercancel",this._boundHandle)):(this.target.addEventListener("touchstart",this._boundHandle),this.target.addEventListener("touchend",this._boundHandle),this.target.addEventListener("touchmove",this._boundHandle),this.target.addEventListener("touchcancel",this._boundHandle),this.target.addEventListener("mousedown",this._boundHandle),this.target.addEventListener("mouseup",this._boundHandle),this.target.addEventListener("mousemove",this._boundHandle));const t={passive:!(this.engine.pageScrollPreventionMode===er.All||this.engine.pageScrollPreventionMode===er.Canvas)};"onwheel"in document.createElement("div")?this.target.addEventListener("wheel",this._boundWheel,t):void 0!==document.onmousewheel?this.target.addEventListener("mousewheel",this._boundWheel,t):this.target.addEventListener("MozMousePixelScroll",this._boundWheel,t)}detach(){window.PointerEvent?(this.target.removeEventListener("pointerdown",this._boundHandle),this.target.removeEventListener("pointerup",this._boundHandle),this.target.removeEventListener("pointermove",this._boundHandle),this.target.removeEventListener("pointercancel",this._boundHandle)):(this.target.removeEventListener("touchstart",this._boundHandle),this.target.removeEventListener("touchend",this._boundHandle),this.target.removeEventListener("touchmove",this._boundHandle),this.target.removeEventListener("touchcancel",this._boundHandle),this.target.removeEventListener("mousedown",this._boundHandle),this.target.removeEventListener("mouseup",this._boundHandle),this.target.removeEventListener("mousemove",this._boundHandle)),"onwheel"in document.createElement("div")?this.target.removeEventListener("wheel",this._boundWheel):void 0!==document.onmousewheel?this.target.addEventListener("mousewheel",this._boundWheel):this.target.addEventListener("MozMousePixelScroll",this._boundWheel)}_normalizePointerId(t){this._activeNativePointerIdsToNormalized.set(t,-1);const e=Array.from(this._activeNativePointerIdsToNormalized.keys()).sort(((t,e)=>t-e)).findIndex((e=>e===t));return this._activeNativePointerIdsToNormalized.set(t,e),e}_handle(t){t.preventDefault();const e=new Map;let i,s;if(n=t,globalThis.TouchEvent&&n instanceof globalThis.TouchEvent){i=Rn.Unknown,s=Bn.Touch;for(let i=0;i<t.changedTouches.length;i++){const s=t.changedTouches[i],n=jn.fromPagePosition(s.pageX,s.pageY,this.engine),r=i+1,o=this._normalizePointerId(r);this.currentFramePointerPositions.set(o,n.worldPos),e.set(o,n)}}else{i=this._nativeButtonToPointerButton(t.button),s=Bn.Mouse;const n=jn.fromPagePosition(t.pageX,t.pageY,this.engine);let r=1;(function(t){return globalThis.PointerEvent&&t instanceof globalThis.PointerEvent})(t)&&(r=t.pointerId,s=this._stringToPointerType(t.pointerType));const o=this._normalizePointerId(r);this.currentFramePointerPositions.set(o,n.worldPos),e.set(o,n)}var n;for(const[n,r]of e.entries())switch(t.type){case"mousedown":case"pointerdown":case"touchstart":this.currentFrameDown.push(new qn("down",n,i,s,r,t)),this.currentFramePointerDown.set(n,!0);break;case"mouseup":case"pointerup":case"touchend":this.currentFrameUp.push(new qn("up",n,i,s,r,t)),this.currentFramePointerDown.set(n,!1);break;case"mousemove":case"pointermove":case"touchmove":this.currentFrameMove.push(new qn("move",n,i,s,r,t));break;case"touchcancel":case"pointercance":this.currentFrameCancel.push(new qn("cancel",n,i,s,r,t))}}_handleWheel(t){(this.engine.pageScrollPreventionMode===er.All||this.engine.pageScrollPreventionMode===er.Canvas&&t.target===this.engine.canvas)&&t.preventDefault();const e=this.engine.screen.pageToScreenCoordinates(S(t.pageX,t.pageY)),i=this.engine.screen.screenToWorldCoordinates(e),s=-1/40,n=t.deltaX||t.wheelDeltaX*s||0,r=t.deltaY||t.wheelDeltaY*s||t.wheelDelta*s||t.detail||0,o=t.deltaZ||0;let a=En.Pixel;t.deltaMode&&(1===t.deltaMode?a=En.Line:2===t.deltaMode&&(a=En.Page));const h=new Kn(i.x,i.y,t.pageX,t.pageY,e.x,e.y,0,n,r,o,a,t);this.currentFrameWheel.push(h)}triggerEvent(t,e){const i=this.engine.screen.worldToPageCoordinates(e);window.PointerEvent?this._handle(new window.PointerEvent("pointer"+t,{pointerId:0,clientX:i.x,clientY:i.y})):this._handle(new window.MouseEvent("mouse"+t,{clientX:i.x,clientY:i.y}));const s=this.engine.currentScene.world.systemManager.get(vn),n=this.engine.currentScene.world.queryManager.createQuery(s.types);s.update(n.getEntities())}_nativeButtonToPointerButton(t){switch(t){case Tn.NoButton:return Rn.NoButton;case Tn.Left:return Rn.Left;case Tn.Middle:return Rn.Middle;case Tn.Right:return Rn.Right;case Tn.Unknown:return Rn.Unknown;default:return Z(t)}}_stringToPointerType(t){switch(t){case"touch":return Bn.Touch;case"mouse":return Bn.Mouse;case"pen":return Bn.Pen;default:return Bn.Unknown}}}class Qn{constructor(t){var e;this._samplePeriod=100,this._currentFrameTime=0,this._frames=0,this._previousSampleTime=0,this._beginFrameTime=0,this._fps=t.initialFps,this._samplePeriod=null!==(e=t.samplePeriod)&&void 0!==e?e:this._samplePeriod,this._currentFrameTime=1e3/t.initialFps,this._nowFn=t.nowFn,this._previousSampleTime=this._nowFn()}start(){this._beginFrameTime=this._nowFn()}end(){this._frames++;const t=this._nowFn();this._currentFrameTime=t-this._beginFrameTime,t>=this._previousSampleTime+this._samplePeriod&&(this._fps=1e3*this._frames/(t-this._previousSampleTime),this._previousSampleTime=t,this._frames=0)}get fps(){return this._fps}get instant(){return 1e3/this._currentFrameTime}}class $n{constructor(t){var e,i,s;this._onFatalException=()=>{},this._maxFps=1/0,this._lastTime=0,this._elapsed=1,this._scheduledCbs=[],this._totalElapsed=0,this._options=t,this.tick=t.tick,this._lastTime=null!==(e=this.now())&&void 0!==e?e:0,this._maxFps=null!==(i=t.maxFps)&&void 0!==i?i:this._maxFps,this._onFatalException=null!==(s=t.onFatalException)&&void 0!==s?s:this._onFatalException,this.fpsSampler=new Qn({initialFps:60,nowFn:()=>this.now()})}elapsed(){return this._elapsed}now(){return performance.now()}toTestClock(){return new tr({...this._options,defaultUpdateMs:16.6})}toStandardClock(){return new Jn({...this._options})}schedule(t,e=0){const i=this.now()+e;this._scheduledCbs.push([t,i])}_runScheduledCbs(){for(let t=this._scheduledCbs.length-1;t>-1;t--)this._scheduledCbs[t][1]<=this._totalElapsed&&(this._scheduledCbs[t][0](),this._scheduledCbs.splice(t,1))}update(t){try{this.fpsSampler.start();const e=this.now();let i=e-this._lastTime||1;const s=this._maxFps===1/0?0:1e3/this._maxFps;if(i<=s)return;i>200&&(i=1),this._elapsed=t||i,this._totalElapsed+=this._elapsed,this._runScheduledCbs(),this.tick(t||i),this._lastTime=s>0?e-i%s:e,this.fpsSampler.end()}catch(t){this._onFatalException(t),this.stop()}}}class Jn extends $n{constructor(t){super(t),this._running=!1}isRunning(){return this._running}start(){this._running=!0;const t=()=>{if(this._running)try{this._requestId=window.requestAnimationFrame(t),this.update()}catch(t){throw window.cancelAnimationFrame(this._requestId),t}};t()}stop(){this._running=!1}}class tr extends $n{constructor(t){super({...t}),this._logger=_.getInstance(),this._running=!1,this._currentTime=0,this._updateMs=t.defaultUpdateMs}now(){var t;return null!==(t=this._currentTime)&&void 0!==t?t:0}isRunning(){return this._running}start(){this._running=!0}stop(){this._running=!1}step(t){const e=null!=t?t:this._updateMs;this._running?(this.update(e),this._currentTime+=e):this._logger.warn("The clock is not running, no step will be performed")}run(t,e){for(let i=0;i<t;i++)this.step(null!=e?e:this._updateMs)}}var er,ir=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};u(),function(t){t[t.None=0]="None",t[t.Canvas=1]="Canvas",t[t.All=2]="All"}(er||(er={}));class sr extends Ke{constructor(t){var e,i,s,n;super(),this.maxFps=Number.POSITIVE_INFINITY,this._hasStarted=!1,this.postProcessors=[],this.scenes={},this._animations=[],this._suppressPlayButton=!1,this.pauseAudioWhenHidden=!0,this._isDebug=!1,this.debugColor=new T(255,255,255),this.enableCanvasTransparency=!0,this.onFatalException=t=>{_.getInstance().fatal(t)},this._timescale=1,this._isInitialized=!1,this._deferredGoTo=null,this._loadingComplete=!1,this._isReady=!1,this._isReadyPromise=new Promise((t=>{this._isReadyResolve=t})),t={...sr._DEFAULT_ENGINE_OPTIONS,...t},p.freeze(),this.browser=new Vn(window,document);const r=new si;if(!t.suppressMinimumBrowserFeatureDetection&&!(this._compatible=r.test())){const e=document.createElement("div");if(e.innerText="Sorry, your browser does not support all the features needed for Excalibur",document.body.appendChild(e),r.failedTests.forEach((function(t){const e=document.createElement("div");e.innerText="Browser feature missing "+t,document.body.appendChild(e)})),t.canvasElementId){const e=document.getElementById(t.canvasElementId);e&&e.parentElement.removeChild(e)}return}this._compatible=!0,console.log&&!t.suppressConsoleBootMessage&&(console.log(`%cPowered by Excalibur.js (v${Nr})`,"background: #176BAA; color: white; border-radius: 5px; padding: 15px; font-size: 1.5em; line-height: 80px;"),console.log("\n /| ________________\nO|===|* >________________>\n \\|"),console.log("Visit","http://excaliburjs.com","for more information")),t.suppressPlayButton&&(this._suppressPlayButton=!0),this._logger=_.getInstance(),this._logger.defaultLevel===d.Debug&&r.logBrowserFeatures(),this._logger.debug("Building engine..."),this.canvasElementId=t.canvasElementId,t.canvasElementId?(this._logger.debug("Using Canvas element specified: "+t.canvasElementId),this.canvas=document.getElementById(t.canvasElementId)):t.canvasElement?(this._logger.debug("Using Canvas element specified:",t.canvasElement),this.canvas=t.canvasElement):(this._logger.debug("Using generated canvas element"),this.canvas=document.createElement("canvas"));let o=null!==(e=t.displayMode)&&void 0!==e?e:Ve.Fixed;if(t.width&&t.height||t.viewport?(void 0===t.displayMode&&(o=Ve.Fixed),this._logger.debug("Engine viewport is size "+t.width+" x "+t.height)):t.displayMode||(this._logger.debug("Engine viewport is fit"),o=Ve.FitScreen),p.isEnabled(c.Canvas)){const e=new Xn({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:t.antialiasing,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel});this.graphicsContext=e,this.ctx=e.__ctx}else{const e=new We({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,smoothing:t.antialiasing,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel});this.graphicsContext=e,this.ctx=e.__ctx}this.screen=new Xe({canvas:this.canvas,context:this.graphicsContext,antialiasing:null===(i=t.antialiasing)||void 0===i||i,browser:this.browser,viewport:null!==(s=t.viewport)&&void 0!==s?s:t.width&&t.height?{width:t.width,height:t.height}:Ge.SVGA,resolution:t.resolution,displayMode:o,position:t.position,pixelRatio:t.suppressHiDPIScaling?1:null}),t.backgroundColor&&(this.backgroundColor=t.backgroundColor.clone()),this.maxFps=null!==(n=t.maxFps)&&void 0!==n?n:this.maxFps,this.clock=new Jn({maxFps:this.maxFps,tick:this._mainloop.bind(this),onFatalException:t=>this.onFatalException(t)}),this.enableCanvasTransparency=t.enableCanvasTransparency,this._loader=new ei,this.debug=new In(this),this._initialize(t),this.rootScene=this.currentScene=new Dn,this.addScene("root",this.rootScene)}get canvasWidth(){return this.screen.canvasWidth}get halfCanvasWidth(){return this.screen.halfCanvasWidth}get canvasHeight(){return this.screen.canvasHeight}get halfCanvasHeight(){return this.screen.halfCanvasHeight}get drawWidth(){return this.screen.drawWidth}get halfDrawWidth(){return this.screen.halfDrawWidth}get drawHeight(){return this.screen.drawHeight}get halfDrawHeight(){return this.screen.halfDrawHeight}get isHiDpi(){return this.screen.isHiDpi}get stats(){return this.debug.stats}get isFullscreen(){return this.screen.isFullScreen}get displayMode(){return this.screen.displayMode}get pixelRatio(){return this.screen.pixelRatio}get isDebug(){return this._isDebug}on(t,e){super.on(t,e)}once(t,e){super.once(t,e)}off(t,e){super.off(t,e)}getWorldBounds(){return this.screen.getWorldBounds()}get timescale(){return this._timescale}set timescale(t){t<=0?_.getInstance().error("Cannot set engine.timescale to a value of 0 or less than 0."):this._timescale=t}playAnimation(t,e,i){this._animations.push(new nr(t,e,i))}addTileMap(t){this.currentScene.addTileMap(t)}removeTileMap(t){this.currentScene.removeTileMap(t)}addTimer(t){return this.currentScene.addTimer(t)}removeTimer(t){return this.currentScene.removeTimer(t)}addScene(t,e){this.scenes[t]&&this._logger.warn("Scene",t,"already exists overwriting"),this.scenes[t]=e}removeScene(t){if(t instanceof Dn)for(const e in this.scenes)this.scenes.hasOwnProperty(e)&&this.scenes[e]===t&&delete this.scenes[e];"string"==typeof t&&delete this.scenes[t]}add(t){2!==arguments.length?this._deferredGoTo&&this.scenes[this._deferredGoTo]?this.scenes[this._deferredGoTo].add(t):this.currentScene.add(t):this.addScene(arguments[0],arguments[1])}remove(t){t instanceof Xi&&this.currentScene.remove(t),t instanceof Dn&&this.removeScene(t),"string"==typeof t&&this.removeScene(t)}goToScene(t){if(this.isInitialized)if(this.scenes[t]){const e=this.currentScene,i=this.scenes[t];this._logger.debug("Going to scene:",t),this.currentScene.isInitialized&&(this.currentScene._deactivate.apply(this.currentScene,[e,i]),this.currentScene.eventDispatcher.emit("deactivate",new se(i,this.currentScene))),this.currentScene=i,this.screen.setCurrentCamera(i.camera),this.currentScene._initialize(this),this.currentScene._activate.apply(this.currentScene,[e,i]),this.currentScene.eventDispatcher.emit("activate",new ie(e,this.currentScene))}else this._logger.error("Scene",t,"does not exist!");else this._deferredGoTo=t}screenToWorldCoordinates(t){return this.screen.screenToWorldCoordinates(t)}worldToScreenCoordinates(t){return this.screen.worldToScreenCoordinates(t)}_initialize(t){this.pageScrollPreventionMode=t.scrollPreventionMode;const e=t&&t.pointerScope===Cn.Document?document:this.canvas;let i,s;this.input={keyboard:new Un,pointers:new Yn(e,this),gamepads:new Hn},this.input.keyboard.init(),this.input.pointers.init(),this.input.gamepads.init(),void 0!==document.hidden?(i="hidden",s="visibilitychange"):"msHidden"in document?(i="msHidden",s="msvisibilitychange"):"webkitHidden"in document&&(i="webkitHidden",s="webkitvisibilitychange"),this.browser.document.on(s,(()=>{document[i]?(this.eventDispatcher.emit("hidden",new jt(this)),this._logger.debug("Window hidden")):(this.eventDispatcher.emit("visible",new Xt(this)),this._logger.debug("Window visible"))})),this.canvasElementId||t.canvasElement||document.body.appendChild(this.canvas)}onInitialize(t){}setAntialiasing(t){this.screen.antialiasing=t}getAntialiasing(){return this.screen.antialiasing}get isInitialized(){return this._isInitialized}_overrideInitialize(t){this.isInitialized||(this.onInitialize(t),super.emit("initialize",new ee(t,this)),this._isInitialized=!0,this._deferredGoTo?this.goToScene(this._deferredGoTo):this.goToScene("root"))}_update(t){if(!this.ready)return this._loader.update(this,t),this.input.keyboard.update(),void this.input.gamepads.update();this._preupdate(t),this.currentScene.update(this,t),this._animations=this._animations.filter((function(t){return!t.animation.isDone()})),this.input.keyboard.update(),this.input.gamepads.update(),this._postupdate(t)}_preupdate(t){this.emit("preupdate",new It(this,t,this)),this.onPreUpdate(this,t)}onPreUpdate(t,e){}_postupdate(t){this.emit("postupdate",new Lt(this,t,this)),this.onPostUpdate(this,t)}onPostUpdate(t,e){}_draw(t){const e=this.ctx;if(this._predraw(e,t),!this._isReady)return this._loader.canvas.draw(this.graphicsContext,0,0),void this.graphicsContext.flush();this.graphicsContext.backgroundColor=this.backgroundColor,this.currentScene.draw(this.ctx,t);let i=0;const s=this._animations.length;for(;i<s;i++)this._animations[i].animation.draw(e,this._animations[i].x,this._animations[i].y);if(this.isDebug){this.ctx.font="Consolas",this.ctx.fillStyle=this.debugColor.toString();const t=this.input.keyboard.getKeys();for(let e=0;e<t.length;e++)this.ctx.fillText(t[e].toString()+" : "+(An[t[e]]?An[t[e]]:"Not Mapped"),100,10*e+10);this.ctx.fillText("FPS:"+this.stats.currFrame.fps.toFixed(2).toString(),10,10)}for(let t=0;t<this.postProcessors.length;t++)this.postProcessors[t].process(this.ctx.getImageData(0,0,this.canvasWidth,this.canvasHeight),this.ctx);this._postdraw(e,t)}_predraw(t,e){this.emit("predraw",new Mt(t,e,this)),this.onPreDraw(t,e)}onPreDraw(t,e){}_postdraw(t,e){this.emit("postdraw",new Dt(t,e,this)),this.onPostDraw(t,e)}onPostDraw(t,e){}showDebug(t){this._isDebug=t}toggleDebug(){return this._isDebug=!this._isDebug,this._isDebug}get loadingComplete(){return this._loadingComplete}get ready(){return this._isReady}isReady(){return this._isReadyPromise}async start(t){if(!this._compatible)throw new Error("Excalibur is incompatible with your browser");return t&&(this.screen.pushResolutionAndViewport(),this.screen.resolution=this.screen.viewport,this.screen.applyResolutionAndViewport(),this.graphicsContext.updateViewport(),this._loader=t,this._loader.suppressPlayButton=this._suppressPlayButton||this._loader.suppressPlayButton,this._loader.wireEngine(this)),this._logger.debug("Starting game clock..."),this.browser.resume(),this.clock.start(),this._logger.debug("Game clock started"),t&&(await this.load(this._loader),this._loadingComplete=!0,this.screen.popResolutionAndViewport(),this.screen.applyResolutionAndViewport(),this.graphicsContext.updateViewport()),this._loadingComplete=!0,this._overrideInitialize(this),this._isReady=!0,this._isReadyResolve(),this.emit("start",new Rt(this)),this._isReadyPromise}_mainloop(t){this.emit("preframe",new zt(this,this.stats.prevFrame));const e=t*this.timescale,i=this.stats.prevFrame.id+1;this.stats.currFrame.reset(),this.stats.currFrame.id=i,this.stats.currFrame.delta=e,this.stats.currFrame.fps=this.clock.fpsSampler.fps;const s=this.clock.now();this._update(e);const n=this.clock.now();this._draw(e);const r=this.clock.now();this.stats.currFrame.duration.update=n-s,this.stats.currFrame.duration.draw=r-n,this.emit("postframe",new Ot(this,this.stats.currFrame))}static createMainLoop(t,e,i){let s=i();const n=new Qn({nowFn:i,initialFps:t.maxFps===1/0?60:t.maxFps});return function r(){if(t._hasStarted)try{t._requestId=e(r),n.start(),t.emit("preframe",new zt(t,t.stats.prevFrame));const o=i();let a=o-s||1;const h=t.maxFps===Number.POSITIVE_INFINITY?0:1e3/t.maxFps;if(a<=h)return;a>200&&(a=1);const l=a*t.timescale,c=t.stats.prevFrame.id+1;t.stats.currFrame.reset(),t.stats.currFrame.id=c,t.stats.currFrame.delta=l,t.stats.currFrame.fps=n.fps;const d=i();t._update(l);const u=i();t._draw(l);const p=i();t.stats.currFrame.duration.update=u-d,t.stats.currFrame.duration.draw=p-u,s=h>0?o-a%h:o,t.emit("postframe",new Ot(t,t.stats.currFrame)),n.end(),t.stats.prevFrame.reset(t.stats.currFrame)}catch(e){window.cancelAnimationFrame(t._requestId),t.stop(),t.onFatalException(e)}}}stop(){this.clock.isRunning()&&(this.emit("stop",new Bt(this)),this.browser.pause(),this.clock.stop(),this._logger.debug("Game stopped"))}isPaused(){return!this.clock.isRunning()}screenshot(){const t=new Image,e=this.canvas.toDataURL("image/png");return t.src=e,t}async load(t){try{await t.load()}catch(t){await Promise.resolve()}}}sr._DEFAULT_ENGINE_OPTIONS={width:0,height:0,enableCanvasTransparency:!0,canvasElementId:"",canvasElement:void 0,snapToPixel:!1,pointerScope:Cn.Canvas,suppressConsoleBootMessage:null,suppressMinimumBrowserFeatureDetection:null,suppressHiDPIScaling:null,suppressPlayButton:null,scrollPreventionMode:er.Canvas,backgroundColor:T.fromHex("#2185d0")},ir([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use Actor.graphics"})],sr.prototype,"playAnimation",null);let nr=class{constructor(t,e,i){this.animation=t,this.x=e,this.y=i}};nr=ir([b({message:"Will be removed in excalibur v0.26.0"})],nr);class rr extends St{constructor(t,e="MediaEvent"){super(),this.target=t,this._name=e}set bubbles(t){}get bubbles(){return!1}get _path(){return null}set _path(t){}stopPropagation(){}action(){}propagate(){}layPath(t){}}class or extends rr{constructor(t,e){super(t,"NativeSoundEvent"),this.track=e}}class ar extends rr{constructor(t,e){super(t,"NativeSoundProcessedEvent"),this._processedData=e,this.data=this._processedData}}class hr extends bt{constructor(t={}){var e,i,s,n,r,o,a,h,l,c,d,u;super(t),this.quality=2,this.family="sans-serif",this.style=Fe.Normal,this.bold=!1,this.unit=Be.Px,this.textAlign=Me.Left,this.baseAlign=De.Alphabetic,this.direction=ke.LeftToRight,this.size=10,this.shadow=null,this._textBounds=new B,this._textWidth=0,this._textHeight=0,this.family=null!==(e=null==t?void 0:t.family)&&void 0!==e?e:this.family,this.style=null!==(i=null==t?void 0:t.style)&&void 0!==i?i:this.style,this.bold=null!==(s=null==t?void 0:t.bold)&&void 0!==s?s:this.bold,this.size=null!==(n=null==t?void 0:t.size)&&void 0!==n?n:this.size,this.unit=null!==(r=null==t?void 0:t.unit)&&void 0!==r?r:this.unit,this.textAlign=null!==(o=null==t?void 0:t.textAlign)&&void 0!==o?o:this.textAlign,this.baseAlign=null!==(a=null==t?void 0:t.baseAlign)&&void 0!==a?a:this.baseAlign,this.direction=null!==(h=null==t?void 0:t.direction)&&void 0!==h?h:this.direction,this.quality=null!==(l=null==t?void 0:t.quality)&&void 0!==l?l:this.quality,(null==t?void 0:t.shadow)&&(this.shadow={},this.shadow.blur=null!==(c=t.shadow.blur)&&void 0!==c?c:this.shadow.blur,this.shadow.offset=null!==(d=t.shadow.offset)&&void 0!==d?d:this.shadow.offset,this.shadow.color=null!==(u=t.shadow.color)&&void 0!==u?u:this.shadow.color),this.flagDirty()}clone(){return new hr({...this.cloneGraphicOptions(),...this.cloneRasterOptions(),size:this.size,unit:this.unit,family:this.family,style:this.style,bold:this.bold,textAlign:this.textAlign,baseAlign:this.baseAlign,direction:this.direction,shadow:this.shadow?{blur:this.shadow.blur,offset:this.shadow.offset,color:this.shadow.color}:null})}get fontString(){return`${this.style} ${this.bold?"bold":""} ${this.size}${this.unit} ${this.family}`}get width(){return this._textWidth}set width(t){this._textWidth=t}get height(){var t,e;const i=null!==(e=null===(t=this._lines)||void 0===t?void 0:t.length)&&void 0!==e?e:1;return this._textHeight*i}set height(t){var e,i;const s=null!==(i=null===(e=this._lines)||void 0===e?void 0:e.length)&&void 0!==i?i:1;this._textHeight=t/s}get _rasterWidth(){return this._bitmap.width}get _rasterHeight(){return this._bitmap.height}get _halfRasterWidth(){return Math.floor(this._bitmap.width/2)}get _halfRasterHeight(){return Math.floor(this._bitmap.height/2)}get localBounds(){return this._textBounds}_drawImage(t,e,i){this.dirty&&this.rasterize(),t.drawImage(this._bitmap,0,0,this._rasterWidth,this._rasterHeight,e-this._rasterWidth/this.quality/2,i-this._rasterHeight/this.quality/2,this._rasterWidth/this.quality,this._rasterHeight/this.quality)}_rotate(t){var e;const i=null!==(e=this.origin)&&void 0!==e?e:this._textBounds.center;t.translate(i.x,i.y),t.rotate(this.rotation),t.translate(-i.x,-i.y)}_flip(t){this.flipHorizontal&&(t.translate(this._textBounds.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,-this._textBounds.height/2/this.scale.y),t.scale(1,-1))}updateText(t){this._text!==t&&(this._text=t,this._lines=this._text.split("\n"),this._updateDimensions(),this.flagDirty())}_updateDimensions(){if(this._text){this._applyFont(this._ctx);const t=this._lines.reduce(((t,e)=>t.length>e.length?t:e)),e=this._ctx.measureText(t);this._textWidth=Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight),this._textHeight=Math.abs(e.actualBoundingBoxAscent)+Math.abs(e.actualBoundingBoxDescent);const i=this._textHeight*this._lines.length;this._bitmap.width=2*(this._textWidth+2*this.padding)*this.quality,this._bitmap.height=2*(i+2*this.padding)*this.quality;const s=0,n=0,r=i-Math.abs(e.actualBoundingBoxAscent);this._textBounds=new B({left:s-Math.abs(e.actualBoundingBoxLeft)-this.padding,top:n-Math.abs(e.actualBoundingBoxAscent)-this.padding,bottom:n+r+this.padding,right:s+Math.abs(e.actualBoundingBoxRight)+this.padding})}}_preDraw(t,e,i){this.dirty&&this._updateDimensions(),super._preDraw(t,e,i)}_postDraw(t){this.showDebug&&t.debug.drawRect(-this._halfRasterWidth,-this._halfRasterHeight,this._rasterWidth,this._rasterHeight),t.restore()}_applyFont(t){t.translate(this.padding+this._halfRasterWidth,this.padding+this._halfRasterHeight),t.scale(this.quality,this.quality),t.textAlign=this.textAlign,t.textBaseline=this.baseAlign,t.font=this.fontString,t.direction=this.direction,this.shadow&&(t.shadowColor=this.shadow.color.toString(),t.shadowBlur=this.shadow.blur,t.shadowOffsetX=this.shadow.offset.x,t.shadowOffsetY=this.shadow.offset.y)}execute(t){if(this._text){this._applyRasterProperites(t),this._applyFont(t);const e=this._textHeight;for(let i=0;i<this._lines.length;i++){const s=this._lines[i];this.color&&t.fillText(s,0,i*e),this.strokeColor&&t.strokeText(s,0,i*e)}this.showDebug&&(Ze(t,T.Red,-this._halfRasterWidth,0,this._halfRasterWidth,0,2),Ze(t,T.Red,0,-this._halfRasterHeight,0,this._halfRasterHeight,2))}}render(t,e,i,s){this.updateText(e),this.draw(t,i,s)}}class lr extends yt{constructor(t){var e,i;super(t),this._text="",this.font=null!==(e=t.font)&&void 0!==e?e:new hr,this.color=null!==(i=t.color)&&void 0!==i?i:this.color,this.text=t.text}clone(){return new lr({text:this.text.slice(),color:this.color.clone(),font:this.font.clone()})}get text(){return this._text}set text(t){this._text=t,this.font.updateText(t)}get color(){return this.font instanceof hr?this.font.color:T.Black}set color(t){this.font instanceof hr&&(this.font.color=t)}get font(){return this._font}set font(t){this._font=t instanceof hr?vt(t,(t=>t.flagDirty())):t}get width(){return this.font.width}get height(){return this.font.height}get localBounds(){return this.font.localBounds}_rotate(t){}_flip(t){}_drawImage(t,e,i){this.font instanceof hr&&(this.font.color=this.color),this.font.flipHorizontal=this.flipHorizontal,this.font.flipVertical=this.flipVertical,this.font.scale=this.scale,this.font.rotation=this.rotation,this.font.origin=this.origin,this.font.opacity=this.opacity,this.font.render(t,this._text,e,i)}}var cr=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};class dr extends Cs{constructor(t){super(t),this.font=new hr,this._text=new lr({text:"",font:this.font}),this.letterSpacing=0,this.caseInsensitive=!0;const{text:e,pos:i,x:s,y:n,spriteFont:r,font:o,color:a}=t;this.pos=null!=i?i:s&&n?S(s,n):this.pos,this.text=null!=e?e:this.text,this.spriteFont=null!=r?r:this.spriteFont,this.font=null!=o?o:this.font,this.color=null!=a?a:this.color;const h=this.get(Yi);h.anchor=A.Zero,h.use(this._text)}get text(){return this._text.text}set text(t){this._text.text=t}get color(){return this._text.color}set color(t){this._text.color=t}get opacity(){return this._text.opacity}set opacity(t){this._text.opacity=t}get bold(){return this.font.bold}set bold(t){this.font.bold=t}get fontFamily(){return this.font.family}set fontFamily(t){this.font.family=t}get fontSize(){return this.font.size}set fontSize(t){this.font.size=t}get fontStyle(){return this.font.style}set fontStyle(t){this.font.style=t}get fontUnit(){return this.font.unit}set fontUnit(t){this.font.unit=t}get textAlign(){return this.font.textAlign}set textAlign(t){this.font.textAlign=t}get baseAlign(){return this.font.baseAlign}set baseAlign(t){this.font.baseAlign=t}get spriteFont(){return this._legacySpriteFont}set spriteFont(t){if(t){if(t instanceof ze)return this._legacySpriteFont=t,this._spriteFont=Ue.fromLegacySpriteFont(t),void(this._text.font=this._spriteFont);this._spriteFont=t,this._text.font=this._spriteFont}}_initialize(t){super._initialize(t),this._graphicsContext=t.graphicsContext}getTextWidth(){return this._text.width}setTextShadow(t,e,i){this.font.shadow={offset:S(t,e),blur:2,color:i}}useTextShadow(t){this.spriteFont&&this.spriteFont.useTextShadow(t)}clearTextShadow(){this.font.shadow=null}draw(t,e){const i=this._graphicsContext;this._text.draw(i,0,0)}}cr([b({message:"Label.bold will be removed in v0.26.0",alternateMethod:"Use Label.font.bold"})],dr.prototype,"bold",null),cr([b({message:"Label.fontFamily will be removed in v0.26.0",alternateMethod:"Use Label.font.family"})],dr.prototype,"fontFamily",null),cr([b({message:"Label.fontSize will be removed in v0.26.0",alternateMethod:"Use Label.font.size"})],dr.prototype,"fontSize",null),cr([b({message:"Label.fontStyle will be removed in v0.26.0",alternateMethod:"Use Lable.font.style"})],dr.prototype,"fontStyle",null),cr([b({message:"Label.fontUnit will be removed in v0.26.0",alternateMethod:"Use Label.font.unit"})],dr.prototype,"fontUnit",null),cr([b({message:"Label.textAlign will be removed in v0.26.0",alternateMethod:"Use Label.font.textAlign"})],dr.prototype,"textAlign",null),cr([b({message:"Label.baseAlign will be removed in v0.26.0",alternateMethod:"Use Label.font.baseAlign"})],dr.prototype,"baseAlign",null),cr([b()],dr.prototype,"spriteFont",null),cr([b({message:"Label.setTextShadow will be removed in v0.26.0",alternateMethod:"Use Label.font.shadow"})],dr.prototype,"setTextShadow",null),cr([b({message:"Label.useTextShadow will be removed in v0.26.0",alternateMethod:"Use Label.font.shadow"})],dr.prototype,"useTextShadow",null),cr([b({message:"Label.clearTextShadow will be removed in v0.26.0",alternateMethod:"Use Label.font.shadow"})],dr.prototype,"clearTextShadow",null);class ur{static create(t,e){if(this._CURRENT_GROUP>this._MAX_GROUPS)throw new Error(`Cannot have more than ${this._MAX_GROUPS} collision groups`);if(this._GROUPS.get(t))throw new Error(`Collision group ${t} already exists`);const i=new mi(t,this._CURRENT_BIT,void 0!==e?e:~this._CURRENT_BIT);return this._CURRENT_BIT=this._CURRENT_BIT<<1|0,this._CURRENT_GROUP++,this._GROUPS.set(t,i),i}static get groups(){return Array.from(this._GROUPS.values())}static groupByName(t){return this._GROUPS.get(t)}static reset(){this._GROUPS=new Map,this._CURRENT_BIT=this._STARTING_BIT,this._CURRENT_GROUP=1}}ur._STARTING_BIT=1,ur._MAX_GROUPS=32,ur._CURRENT_GROUP=1,ur._CURRENT_BIT=ur._STARTING_BIT,ur._GROUPS=new Map;var pr=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};let gr=class{constructor(t){this.lineWidth=5,this.filled=!1,this._points=[],this.anchor=A.Zero,this.offset=A.Zero,this.rotation=0,this.scale=A.One,this.opacity=1,this._points=t;const e=this._points.reduce(((t,e)=>Math.min(t,e.x)),0),i=this._points.reduce(((t,e)=>Math.max(t,e.x)),0);this.drawWidth=i-e;const s=this._points.reduce(((t,e)=>Math.min(t,e.y)),0),n=this._points.reduce(((t,e)=>Math.max(t,e.y)),0);this.drawHeight=n-s,this.height=this.drawHeight,this.width=this.drawWidth}addEffect(){}removeEffect(){}clearEffects(){}reset(){}draw(t,e,i){t instanceof CanvasRenderingContext2D?this._drawWithOptions({ctx:t,x:e,y:i}):this._drawWithOptions(t)}_drawWithOptions(t){var e,i,s,n,r,o,a,h,l;const{ctx:c,x:d,y:u,rotation:p,drawWidth:g,drawHeight:_,anchor:m,offset:f,opacity:w,flipHorizontal:y,flipVertical:v}={...t,rotation:null!==(e=t.rotation)&&void 0!==e?e:this.rotation,drawWidth:null!==(i=t.drawWidth)&&void 0!==i?i:this.drawWidth,drawHeight:null!==(s=t.drawHeight)&&void 0!==s?s:this.drawHeight,flipHorizontal:null!==(n=t.flipHorizontal)&&void 0!==n?n:this.flipHorizontal,flipVertical:null!==(r=t.flipVertical)&&void 0!==r?r:this.flipVertical,anchor:null!==(o=t.anchor)&&void 0!==o?o:this.anchor,offset:null!==(a=t.offset)&&void 0!==a?a:this.offset,opacity:(null!==(h=t.opacity)&&void 0!==h?h:1)*(null!==(l=this.opacity)&&void 0!==l?l:1)},x=g*m.x+f.x+d,b=_*m.y+f.y+u;c.save(),c.translate(x,b),c.scale(this.scale.x,this.scale.y),c.rotate(p),c.beginPath(),c.lineWidth=this.lineWidth;const C=this._points[0];c.moveTo(C.x,C.y);let A=0;const S=this._points.length;for(;A<S;A++)c.lineTo(this._points[A].x,this._points[A].y);c.lineTo(C.x,C.y),c.closePath(),this.filled&&(c.fillStyle=this.fillColor.toString(),c.fill()),c.strokeStyle=this.lineColor.toString(),y&&(c.translate(g,0),c.scale(-1,1)),v&&(c.translate(0,_),c.scale(1,-1));const P=c.globalAlpha;c.globalAlpha=w,c.stroke(),c.globalAlpha=P,c.restore()}};gr=pr([b({message:"Polygon will be removed in v0.26.0",alternateMethod:"Use Graphics.Polygon"})],gr);class _r{}function mr(t){return!!t._initialize}function fr(t){return!!t.onInitialize}function wr(t){return!!t._preupdate}function yr(t){return!!t.onPreUpdate}function vr(t){return!!t.onPostUpdate}function xr(t){return!!t.onPostUpdate}function br(t){return!!t.onPreDraw}function Cr(t){return!!t.onPostDraw}_r.type={any:"",blob:"blob",json:"json",text:"text",document:"document",arraybuffer:"arraybuffer"};class Ar{constructor(t){this._src=t,this._volume=1,this._duration=void 0,this._loop=!1,this._isPlaying=!1,this._isPaused=!1,this._audioContext=je.create(),this._volumeNode=this._audioContext.createGain(),this._currentOffset=0,this._createNewBufferSource()}set loop(t){this._loop=t,this._instance&&(this._instance.loop=t,this._wireUpOnEnded())}get loop(){return this._loop}set volume(t){t=L(t,0,1),this._volume=t,this._isPlaying&&this._volumeNode.gain.setTargetAtTime?this._volumeNode.gain.setTargetAtTime(t,this._audioContext.currentTime,.1):this._volumeNode.gain.value=t}get volume(){return this._volume}set duration(t){this._duration=t}get duration(){return this._duration}get _playbackRate(){return this._instance?1/(this._instance.playbackRate.value||1):null}isPlaying(){return this._isPlaying}play(t=(()=>{})){return this._isPaused&&(this._resumePlayBack(),t()),this._isPlaying||(this._startPlayBack(),t()),this._playingPromise}pause(){this._isPlaying&&(this._isPaused=!0,this._isPlaying=!1,this._instance.stop(0),this._setPauseOffset())}stop(){this._isPlaying&&(this._isPlaying=!1,this._isPaused=!1,this._currentOffset=0,this._instance.stop(0),this._instance.onended||this._handleOnEnded())}_startPlayBack(){this._isPlaying=!0,this._isPaused=!1,this._playingPromise=new Promise((t=>{this._playingResolve=t})),this._instance||this._createNewBufferSource(),this._rememberStartTime(),this._volumeNode.connect(this._audioContext.destination),this._instance.start(0,0),this._currentOffset=0,this._wireUpOnEnded()}_resumePlayBack(){if(!this._isPaused)return;this._isPaused=!1,this._isPlaying=!0,this._instance.onended=null,this._createNewBufferSource();const t=this._playbackRate*this._src.duration,e=this._currentOffset%t;this._rememberStartTime(-1e3*e),this._instance.start(0,e),this._wireUpOnEnded()}_wireUpOnEnded(){this.loop||(this._instance.onended=()=>this._handleOnEnded())}_handleOnEnded(){this._isPaused||(this._isPlaying=!1,this._playingResolve(!0))}_rememberStartTime(t){this._startTime=(new Date).getTime()+(0|t)}_setPauseOffset(){this._currentOffset=((new Date).getTime()-this._startTime)*this._playbackRate/1e3}_createNewBufferSource(){this._instance=this._audioContext.createBufferSource(),this._instance.buffer=this._src,this._instance.loop=this.loop,this._instance.playbackRate.setValueAtTime(1,0),this._instance.connect(this._volumeNode)}}function Sr(t){try{const e=new Audio,i=/.*\.([A-Za-z0-9]+)$/,s=t.match(i)[1];return!!e.canPlayType("audio/"+s)}catch(t){return _.getInstance().warn("Cannot determine audio support, assuming no support for the Audio Tag",t),!1}}class Pr extends Ke{constructor(...t){super(),this.logger=_.getInstance(),this._loop=!1,this._volume=1,this._duration=void 0,this._isStopped=!1,this._isPaused=!1,this._tracks=[],this._wasPlayingOnHidden=!1,this._audioContext=je.create(),this._resource=new le("",_r.type.arraybuffer);for(const e of t)if(Sr(e)){this.path=e;break}this.path||(this.logger.warn("This browser does not support any of the audio files specified:",t.join(", ")),this.logger.warn("Attempting to use",t[0]),this.path=t[0])}set loop(t){this._loop=t;for(const t of this._tracks)t.loop=this._loop;this.logger.debug("Set loop for all instances of sound",this.path,"to",this._loop)}get loop(){return this._loop}set volume(t){this._volume=t;for(const t of this._tracks)t.volume=this._volume;this.emit("volumechange",new or(this)),this.logger.debug("Set loop for all instances of sound",this.path,"to",this._volume)}get volume(){return this._volume}get duration(){return this._duration}get instances(){return this._tracks}get path(){return this._resource.path}set path(t){this._resource.path=t}isLoaded(){return!!this.data}async load(){if(this.data)return this.data;const t=await this._resource.load(),e=await this.decodeAudio(t.slice(0));return this._duration="object"==typeof e?e.duration:void 0,this.emit("processed",new ar(this,e)),this.data=e}async decodeAudio(t){try{return await this._audioContext.decodeAudioData(t.slice(0))}catch(t){return this.logger.error("Unable to decode this browser may not fully support this format, or the file may be corrupt, if this is an mp3 try removing id3 tags and album art from the file."),await Promise.reject()}}wireEngine(t){t&&(this._engine=t,this._engine.on("hidden",(()=>{t.pauseAudioWhenHidden&&this.isPlaying()&&(this._wasPlayingOnHidden=!0,this.pause())})),this._engine.on("visible",(()=>{t.pauseAudioWhenHidden&&this._wasPlayingOnHidden&&(this.play(),this._wasPlayingOnHidden=!1)})),this._engine.on("start",(()=>{this._isStopped=!1})),this._engine.on("stop",(()=>{this.stop(),this._isStopped=!0})))}instanceCount(){return this._tracks.length}isPlaying(){return this._tracks.some((t=>t.isPlaying()))}play(t){return this.isLoaded()?this._isStopped?(this.logger.warn("Cannot start playing. Engine is in a stopped state."),Promise.resolve(!1)):(this.volume=t||this.volume,this._isPaused?this._resumePlayback():this._startPlayback()):(this.logger.warn("Cannot start playing. Resource",this.path,"is not loaded yet"),Promise.resolve(!0))}pause(){if(this.isPlaying()){for(const t of this._tracks)t.pause();this._isPaused=!0,this.emit("pause",new or(this)),this.logger.debug("Paused all instances of sound",this.path)}}stop(){for(const t of this._tracks)t.stop();this.emit("stop",new or(this)),this._isPaused=!1,this._tracks.length=0,this.logger.debug("Stopped all instances of sound",this.path)}getTrackId(t){return this._tracks.indexOf(t)}async _resumePlayback(){if(this._isPaused){const t=[];for(const e of this._tracks)t.push(e.play());this._isPaused=!1,this.emit("resume",new or(this)),this.logger.debug("Resuming paused instances for sound",this.path,this._tracks),await Promise.all(t)}return!0}async _startPlayback(){const t=await this._getTrackInstance(this.data),e=await t.play((()=>{this.emit("playbackstart",new or(this,t)),this.logger.debug("Playing new instance for sound",this.path)}));return this.emit("playbackend",new or(this,t)),this._tracks.splice(this.getTrackId(t),1),e}_getTrackInstance(t){const e=new Ar(t);return e.loop=this.loop,e.volume=this.volume,e.duration=this.duration,this._tracks.push(e),e}}class Er{constructor(t,e=T.Magenta,i=!0){this.path=t,this.color=e,this.bustCache=i,this._stream=null,this._gif=null,this._textures=[],this._animation=null,this._transparentColor=null,this._resource=new le(t,"arraybuffer",i),this._transparentColor=e}async load(){const t=await this._resource.load();this._stream=new Br(t),this._gif=new Mr(this._stream,this._transparentColor);const e=this._gif.images.map((t=>new Pe(t.src,!1)));return await Promise.all(e.map((t=>t.load()))),this.data=this._textures=e}isLoaded(){return!!this.data}toLegacySprite(t=0){return Se.toLegacySprite(this.toSprite(t))}toLegacySpriteSheet(){return Oe.toLegacySpriteSheet(this.toSpriteSheet())}toLegacyAnimation(t,e){return un.toLegacyAnimation(t,this.toAnimation(e))}toSprite(t=0){return this._textures[t].toSprite()}toSpriteSheet(){const t=this._textures.map((t=>t.toSprite()));return new Oe({sprites:t})}toAnimation(t){const e=this.toSpriteSheet(),i=e.sprites.length;return this._animation=un.fromSpriteSheet(e,Y(0,i),t),this._animation}get readCheckBytes(){return this._gif.checkBytes}}const Tr=t=>t.reduce((function(t,e){return 2*t+e}),0),Rr=t=>{const e=[];for(let i=7;i>=0;i--)e.push(!!(t&1<<i));return e};class Br{constructor(t){if(this.data=null,this.len=0,this.position=0,this.readByte=()=>{if(this.position>=this.data.byteLength)throw new Error("Attempted to read past end of stream.");return this.data[this.position++]},this.readBytes=t=>{const e=[];for(let i=0;i<t;i++)e.push(this.readByte());return e},this.read=t=>{let e="";for(let i=0;i<t;i++)e+=String.fromCharCode(this.readByte());return e},this.readUnsigned=()=>{const t=this.readBytes(2);return(t[1]<<8)+t[0]},this.data=new Uint8Array(t),this.len=this.data.byteLength,0===this.len)throw new Error("No data loaded from file")}}class Mr{constructor(t,e=T.Magenta){this._st=null,this._handler={},this._transparentColor=null,this.frames=[],this.images=[],this.globalColorTable=[],this.checkBytes=[],this.parseColorTable=t=>{const e=[];for(let i=0;i<t;i++){const t="#"+this._st.readBytes(3).map((t=>{const e=t.toString(16);return 1===e.length?"0"+e:e})).join("");e.push(t)}return e},this.readSubBlocks=()=>{let t,e;e="";do{t=this._st.readByte(),e+=this._st.read(t)}while(0!==t);return e},this.parseHeader=()=>{const t={sig:null,ver:null,width:null,height:null,colorRes:null,globalColorTableSize:null,gctFlag:null,sorted:null,globalColorTable:[],bgColor:null,pixelAspectRatio:null};if(t.sig=this._st.read(3),t.ver=this._st.read(3),"GIF"!==t.sig)throw new Error("Not a GIF file.");t.width=this._st.readUnsigned(),t.height=this._st.readUnsigned();const e=Rr(this._st.readByte());t.gctFlag=e.shift(),t.colorRes=Tr(e.splice(0,3)),t.sorted=e.shift(),t.globalColorTableSize=Tr(e.splice(0,3)),t.bgColor=this._st.readByte(),t.pixelAspectRatio=this._st.readByte(),t.gctFlag&&(t.globalColorTable=this.parseColorTable(1<<t.globalColorTableSize+1),this.globalColorTable=t.globalColorTable),this._handler.hdr&&this._handler.hdr(t)&&this.checkBytes.push(this._handler.hdr)},this.parseExt=t=>{const e=t=>{this.checkBytes.push(this._st.readByte());const e=Rr(this._st.readByte());t.reserved=e.splice(0,3),t.disposalMethod=Tr(e.splice(0,3)),t.userInput=e.shift(),t.transparencyGiven=e.shift(),t.delayTime=this._st.readUnsigned(),t.transparencyIndex=this._st.readByte(),t.terminator=this._st.readByte(),this._handler.gce&&this._handler.gce(t)&&this.checkBytes.push(this._handler.gce)},i=t=>{t.comment=this.readSubBlocks(),this._handler.com&&this._handler.com(t)&&this.checkBytes.push(this._handler.com)},s=t=>{this.checkBytes.push(this._st.readByte()),t.ptHeader=this._st.readBytes(12),t.ptData=this.readSubBlocks(),this._handler.pte&&this._handler.pte(t)&&this.checkBytes.push(this._handler.pte)},n=t=>{const e=t=>{this.checkBytes.push(this._st.readByte()),t.unknown=this._st.readByte(),t.iterations=this._st.readUnsigned(),t.terminator=this._st.readByte(),this._handler.app&&this._handler.app.NETSCAPE&&this._handler.app.NETSCAPE(t)&&this.checkBytes.push(this._handler.app)},i=t=>{t.appData=this.readSubBlocks(),this._handler.app&&this._handler.app[t.identifier]&&this._handler.app[t.identifier](t)&&this.checkBytes.push(this._handler.app[t.identifier])};if(this.checkBytes.push(this._st.readByte()),t.identifier=this._st.read(8),t.authCode=this._st.read(3),"NETSCAPE"===t.identifier)e(t);else i(t)},r=t=>{t.data=this.readSubBlocks(),this._handler.unknown&&this._handler.unknown(t)&&this.checkBytes.push(this._handler.unknown)};switch(t.label=this._st.readByte(),t.label){case 249:t.extType="gce",e(t);break;case 254:t.extType="com",i(t);break;case 1:t.extType="pte",s(t);break;case 255:t.extType="app",n(t);break;default:t.extType="unknown",r(t)}},this.parseImg=t=>{t.leftPos=this._st.readUnsigned(),t.topPos=this._st.readUnsigned(),t.width=this._st.readUnsigned(),t.height=this._st.readUnsigned();const e=Rr(this._st.readByte());t.lctFlag=e.shift(),t.interlaced=e.shift(),t.sorted=e.shift(),t.reserved=e.splice(0,2),t.lctSize=Tr(e.splice(0,3)),t.lctFlag&&(t.lct=this.parseColorTable(1<<t.lctSize+1)),t.lzwMinCodeSize=this._st.readByte();const i=this.readSubBlocks();t.pixels=function(t,e){let i=0;const s=function(t){let s=0;for(let n=0;n<t;n++)e.charCodeAt(i>>3)&1<<(7&i)&&(s|=1<<n),i++;return s},n=[],r=1<<t,o=r+1;let a=t+1,h=[];const l=function(){h=[],a=t+1;for(let t=0;t<r;t++)h[t]=[t];h[r]=[],h[o]=null};let c,d;for(;;)if(d=c,c=s(a),c!==r){if(c===o)break;if(c<h.length)d!==r&&h.push(h[d].concat(h[c][0]));else{if(c!==h.length)throw new Error("Invalid LZW code.");h.push(h[d].concat(h[d][0]))}n.push.apply(n,h[c]),h.length===1<<a&&a<12&&a++}else l();return n}(t.lzwMinCodeSize,i),t.interlaced&&(t.pixels=((t,e)=>{const i=new Array(t.length),s=t.length/e,n=(s,n)=>{const r=t.slice(n*e,(n+1)*e);i.splice.apply(i,[s*e,e].concat(r))},r=[0,4,2,1],o=[8,8,4,2];let a=0;for(let t=0;t<4;t++)for(let e=r[t];e<s;e+=o[t])n(e,a),a++;return i})(t.pixels,t.width)),this.frames.push(t),this.arrayToImage(t),this._handler.img&&this._handler.img(t)&&this.checkBytes.push(this._handler)},this.parseBlock=()=>{const t={sentinel:this._st.readByte(),type:""};switch(String.fromCharCode(t.sentinel)){case"!":t.type="ext",this.parseExt(t);break;case",":t.type="img",this.parseImg(t);break;case";":t.type="eof",this._handler.eof&&this._handler.eof(t)&&this.checkBytes.push(this._handler.eof);break;default:throw new Error("Unknown block: 0x"+t.sentinel.toString(16))}"eof"!==t.type&&this.parseBlock()},this.arrayToImage=t=>{let e=0;const i=document.createElement("canvas");i.id=e.toString(),i.width=t.width,i.height=t.height,e++;const s=i.getContext("2d");let n=0,r=0;for(let e=0;e<t.pixels.length;e++)r%t.width==0&&(n++,r=0),this.globalColorTable[t.pixels[e]]===this._transparentColor.toHex()?s.fillStyle="rgba(0, 0, 0, 0)":s.fillStyle=this.globalColorTable[t.pixels[e]],s.fillRect(r,n,1,1),r++;const o=new Image;o.src=i.toDataURL(),this.images.push(o)},this._st=t,this._handler={},this._transparentColor=e,this.parseHeader(),this.parseBlock()}}class Dr extends bt{constructor(t){super(t),this.points=t.points,this.rasterize()}get points(){return this._points}set points(t){this._points=t;const e=this.minPoint;this.width=this._points.reduce(((t,e)=>Math.max(e.x,t)),0)-e.x,this.height=this._points.reduce(((t,e)=>Math.max(e.y,t)),0)-e.y,this.flagDirty()}get minPoint(){return S(this._points.reduce(((t,e)=>Math.min(e.x,t)),1/0),this._points.reduce(((t,e)=>Math.min(e.y,t)),1/0))}clone(){return new Dr({points:this.points.map((t=>t.clone())),...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){if(this.points&&this.points.length){t.beginPath();const e=this.minPoint.negate(),i=this.points[0].add(e);t.moveTo(i.x,i.y),this.points.forEach((i=>{t.lineTo(i.x+e.x,i.y+e.y)})),t.lineTo(i.x,i.y),t.closePath(),this.color&&t.fill(),this.strokeColor&&t.stroke()}}}var Fr=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};let kr=class{constructor(t){this._getComparable=t}find(t){return this._find(this._root,t)}_find(t,e){return null!=t&&(this._getComparable(e)===t.getKey()?t.getData().indexOf(e)>-1:this._getComparable(e)<t.getKey()?this._find(t.getLeft(),e):this._find(t.getRight(),e))}get(t){return this._get(this._root,t)}_get(t,e){return null==t?[]:e===t.getKey()?t.getData():e<t.getKey()?this._get(t.getLeft(),e):this._get(t.getRight(),e)}add(t){return null==this._root?(this._root=new Ir(this._getComparable(t),[t],null,null),!0):this._insert(this._root,t)}_insert(t,e){return null!=t&&(this._getComparable(e)===t.getKey()?!(t.getData().indexOf(e)>-1)&&(t.getData().push(e),!0):this._getComparable(e)<t.getKey()?null==t.getLeft()?(t.setLeft(new Ir(this._getComparable(e),[e],null,null)),!0):this._insert(t.getLeft(),e):null==t.getRight()?(t.setRight(new Ir(this._getComparable(e),[e],null,null)),!0):this._insert(t.getRight(),e))}removeByComparable(t){this._root=this._remove(this._root,t)}_remove(t,e){if(null==t)return null;if(this._getComparable(e)!==t.getKey())return this._getComparable(e)<t.getKey()?(t.setLeft(this._remove(t.getLeft(),e)),t):(t.setRight(this._remove(t.getRight(),e)),t);{const i=t.getData().indexOf(e);if(i>-1){if(t.getData().splice(i,1),0===t.getData().length){if(null==t.getLeft()&&null==t.getRight())return null;if(null==t.getLeft())return t.getRight();if(null==t.getRight())return t.getLeft();const e=this._findMinNode(t.getRight());return t.setKey(e.getKey()),t.setData(e.getData()),t.setRight(this._cleanup(t.getRight(),e)),t}return t}}return null}_cleanup(t,e){const i=e.getKey();if(null==t)return null;if(i===t.getKey()){if(null==t.getLeft()&&null==t.getRight())return null;if(null==t.getLeft())return t.getRight();if(null==t.getRight())return t.getLeft();const e=this._findMinNode(t.getRight());return t.setKey(e.getKey()),t.setData(e.getData()),t.setRight(this._cleanup(t.getRight(),e)),t}return e.getKey()<t.getKey()?(t.setLeft(this._cleanup(t.getLeft(),e)),t):(t.setRight(this._cleanup(t.getRight(),e)),t)}_findMinNode(t){let e=t;for(;null!=e.getLeft();)e=e.getLeft();return e}list(){const t=new Array;return this._list(this._root,t),t}_list(t,e){null!=t&&(this._list(t.getLeft(),e),t.getData().forEach((t=>{e.push(t)})),this._list(t.getRight(),e))}};kr=Fr([b({message:"Will be removed in excalibur v0.26.0",alternateMethod:"Use built in JS array.sort"})],kr);let Ir=class{constructor(t,e,i,s){this._key=t,this._data=e,this._left=i,this._right=s}getKey(){return this._key}setKey(t){this._key=t}getData(){return this._data}setData(t){this._data=t}getLeft(){return this._left}setLeft(t){this._left=t}getRight(){return this._right}setRight(t){this._right=t}};Ir=Fr([b({message:"Will be removed in excalibur v0.26.0"})],Ir);class Lr{constructor(t){this._key=0,this._key=t}getTheKey(){return this._key}setKey(t){this._key=t}}var zr,Or,Ur=function(t,e,i,s){var n,r=arguments.length,o=r<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(n=t[a])&&(o=(r<3?n(o):r>3?n(e,i,o):n(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o};!function(t){t[t.Resolved=0]="Resolved",t[t.Rejected=1]="Rejected",t[t.Pending=2]="Pending"}(Or||(Or={}));let Hr=zr=class{constructor(){this._state=Or.Pending,this._successCallbacks=[],this._rejectCallback=()=>{}}static resolve(t){return(new zr).resolve(t)}static reject(t){return(new zr).reject(t)}static join(){let t=[];if(arguments.length>0&&!Array.isArray(arguments[0]))for(let e=0;e<arguments.length;e++)t[e-0]=arguments[e];else 1===arguments.length&&Array.isArray(arguments[0])&&(t=arguments[0]);const e=new zr;if(!t||!t.length)return e.resolve();const i=t.length;let s=0,n=0;const r=[];return t.forEach((t=>{t.then((()=>{s+=1,s===i?e.resolve():s+n+r.length===i&&e.reject(r)}),(()=>{n+=1,s+n+r.length===i&&e.reject(r)})).error((t=>{r.push(t),r.length+s+n===i&&e.reject(r)}))})),e}then(t,e){if(t&&(this._successCallbacks.push(t),this.state()===Or.Resolved))try{t.call(this,this._value)}catch(t){this._handleError(t)}if(e&&(this._rejectCallback=e,this.state()===Or.Rejected))try{e.call(this,this._value)}catch(t){this._handleError(t)}return this}error(t){return t&&(this._errorCallback=t),this}resolve(t){if(this._state!==Or.Pending)throw new Error("Cannot resolve a promise that is not in a pending state!");this._value=t;try{this._state=Or.Resolved,this._successCallbacks.forEach((t=>{t.call(this,this._value)}))}catch(t){this._handleError(t)}return this}reject(t){if(this._state!==Or.Pending)throw new Error("Cannot reject a promise that is not in a pending state!");this._value=t;try{this._state=Or.Rejected,this._rejectCallback.call(this,this._value)}catch(t){this._handleError(t)}return this}state(){return this._state}_handleError(t){if(!this._errorCallback)throw t;this._errorCallback.call(this,t)}};Hr=zr=Ur([b({message:"ex.Promises are being replaced by native browser promises in v0.26.0",alternateMethod:"Use browser native promises"})],Hr);const Nr="0.26.0-alpha.314+ff3f7ae";u()})(),s})()}));
|
|
3
3
|
//# sourceMappingURL=excalibur.min.js.map
|