EmulatorJS/data/emulator.min.js
2023-07-21 15:15:58 +00:00

1 line
No EOL
258 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("nipplejs",[],t):"object"==typeof exports?exports.nipplejs=t():e.nipplejs=t()}(window,function(){return n=[function(e,t,n){"use strict";n.r(t);function _(e,t){var n=t.x-e.x,t=t.y-e.y;return Math.sqrt(n*n+t*t)}function T(e){return e*(Math.PI/180)}function o(e){f.has(e)&&clearTimeout(f.get(e)),f.set(e,setTimeout(e,100))}function s(e,t,n){for(var i,o=t.split(/[ ,]+/g),s=0;s<o.length;s+=1)i=o[s],e.addEventListener?e.addEventListener(i,n,!1):e.attachEvent&&e.attachEvent(i,n)}function i(e,t,n){for(var i,o=t.split(/[ ,]+/g),s=0;s<o.length;s+=1)i=o[s],e.removeEventListener?e.removeEventListener(i,n):e.detachEvent&&e.detachEvent(i,n)}function a(e){return e.preventDefault(),e.type.match(/^touch/)?e.changedTouches:e}function r(){return{x:void 0!==window.pageXOffset?window.pageXOffset:(document.documentElement||document.body.parentNode||document.body).scrollLeft,y:void 0!==window.pageYOffset?window.pageYOffset:(document.documentElement||document.body.parentNode||document.body).scrollTop}}function l(e,t){t.top||t.right||t.bottom||t.left?(e.style.top=t.top,e.style.right=t.right,e.style.bottom=t.bottom,e.style.left=t.left):(e.style.left=t.x+"px",e.style.top=t.y+"px")}function c(e,t,n){var i,o=h(e);for(i in o)if(o.hasOwnProperty(i))if("string"==typeof t)o[i]=t+" "+n;else{for(var s="",a=0,r=t.length;a<r;a+=1)s+=t[a]+" "+n+", ";o[i]=s.slice(0,-2)}return o}function h(t){var n={};return n[t]="",["webkit","Moz","o"].forEach(function(e){n[e+t.charAt(0).toUpperCase()+t.slice(1)]=""}),n}function d(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function u(e,t){if(e.length)for(var n=0,i=e.length;n<i;n+=1)t(e[n]);else t(e)}var p,f=new Map,n=!!("ontouchstart"in window),m=!!window.PointerEvent,y=!!window.MSPointerEvent,g={start:"mousedown",move:"mousemove",end:"mouseup"},v={};function b(){}m?p={start:"pointerdown",move:"pointermove",end:"pointerup, pointercancel"}:y?p={start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:n?(p={start:"touchstart",move:"touchmove",end:"touchend, touchcancel"},v=g):p=g,b.prototype.on=function(e,t){var n,i=e.split(/[ ,]+/g);this._handlers_=this._handlers_||{};for(var o=0;o<i.length;o+=1)n=i[o],this._handlers_[n]=this._handlers_[n]||[],this._handlers_[n].push(t);return this},b.prototype.off=function(e,t){return this._handlers_=this._handlers_||{},void 0===e?this._handlers_={}:void 0===t?this._handlers_[e]=null:this._handlers_[e]&&0<=this._handlers_[e].indexOf(t)&&this._handlers_[e].splice(this._handlers_[e].indexOf(t),1),this},b.prototype.trigger=function(e,t){var n,i=this,o=e.split(/[ ,]+/g);i._handlers_=i._handlers_||{};for(var s=0;s<o.length;s+=1)n=o[s],i._handlers_[n]&&i._handlers_[n].length&&i._handlers_[n].forEach(function(e){e.call(i,{type:n,target:i},t)})},b.prototype.config=function(e){this.options=this.defaults||{},e&&(this.options=function(e,t){var n,i={};for(n in e)e.hasOwnProperty(n)&&t.hasOwnProperty(n)?i[n]=t[n]:e.hasOwnProperty(n)&&(i[n]=e[n]);return i}(this.options,e))},b.prototype.bindEvt=function(e,t){var n=this;return n._domHandlers_=n._domHandlers_||{},n._domHandlers_[t]=function(){"function"==typeof n["on"+t]?n["on"+t].apply(n,arguments):console.warn('[WARNING] : Missing "on'+t+'" handler.')},s(e,p[t],n._domHandlers_[t]),v[t]&&s(e,v[t],n._domHandlers_[t]),n},b.prototype.unbindEvt=function(e,t){return this._domHandlers_=this._domHandlers_||{},i(e,p[t],this._domHandlers_[t]),v[t]&&i(e,v[t],this._domHandlers_[t]),delete this._domHandlers_[t],this};m=b;function w(e,t){return this.identifier=t.identifier,this.position=t.position,this.frontPosition=t.frontPosition,this.collection=e,this.defaults={size:100,threshold:.1,color:"white",fadeTime:250,dataOnly:!1,restJoystick:!0,restOpacity:.5,mode:"dynamic",zone:document.body,lockX:!1,lockY:!1,shape:"circle"},this.config(t),"dynamic"===this.options.mode&&(this.options.restOpacity=0),this.id=w.id,w.id+=1,this.buildEl().stylize(),this.instance={el:this.ui.el,on:this.on.bind(this),off:this.off.bind(this),show:this.show.bind(this),hide:this.hide.bind(this),add:this.addToDom.bind(this),remove:this.removeFromDom.bind(this),destroy:this.destroy.bind(this),setPosition:this.setPosition.bind(this),resetDirection:this.resetDirection.bind(this),computeDirection:this.computeDirection.bind(this),trigger:this.trigger.bind(this),position:this.position,frontPosition:this.frontPosition,ui:this.ui,identifier:this.identifier,id:this.id,options:this.options},this.instance}w.prototype=new m,(w.constructor=w).id=0,w.prototype.buildEl=function(e){return this.ui={},this.options.dataOnly||(this.ui.el=document.createElement("div"),this.ui.back=document.createElement("div"),this.ui.front=document.createElement("div"),this.ui.el.className="nipple collection_"+this.collection.id,this.ui.back.className="back",this.ui.front.className="front",this.ui.el.setAttribute("id","nipple_"+this.collection.id+"_"+this.id),this.ui.el.appendChild(this.ui.back),this.ui.el.appendChild(this.ui.front)),this},w.prototype.stylize=function(){var e,t,n;return this.options.dataOnly||(t=this.options.fadeTime+"ms",e=function(){var e,t=h("borderRadius");for(e in t)t.hasOwnProperty(e)&&(t[e]="50%");return t}(),t=c("transition","opacity",t),(n={}).el={position:"absolute",opacity:this.options.restOpacity,display:"block",zIndex:999},n.back={position:"absolute",display:"block",width:this.options.size+"px",height:this.options.size+"px",marginLeft:-this.options.size/2+"px",marginTop:-this.options.size/2+"px",background:this.options.color,opacity:".5"},n.front={width:this.options.size/2+"px",height:this.options.size/2+"px",position:"absolute",display:"block",marginLeft:-this.options.size/4+"px",marginTop:-this.options.size/4+"px",background:this.options.color,opacity:".5",transform:"translate(0px, 0px)"},d(n.el,t),"circle"===this.options.shape&&d(n.back,e),d(n.front,e),this.applyStyles(n)),this},w.prototype.applyStyles=function(e){for(var t in this.ui)if(this.ui.hasOwnProperty(t))for(var n in e[t])this.ui[t].style[n]=e[t][n];return this},w.prototype.addToDom=function(){return this.options.dataOnly||document.body.contains(this.ui.el)||this.options.zone.appendChild(this.ui.el),this},w.prototype.removeFromDom=function(){return!this.options.dataOnly&&document.body.contains(this.ui.el)&&this.options.zone.removeChild(this.ui.el),this},w.prototype.destroy=function(){clearTimeout(this.removeTimeout),clearTimeout(this.showTimeout),clearTimeout(this.restTimeout),this.trigger("destroyed",this.instance),this.removeFromDom(),this.off()},w.prototype.show=function(e){var t=this;return t.options.dataOnly||(clearTimeout(t.removeTimeout),clearTimeout(t.showTimeout),clearTimeout(t.restTimeout),t.addToDom(),t.restCallback(),setTimeout(function(){t.ui.el.style.opacity=1},0),t.showTimeout=setTimeout(function(){t.trigger("shown",t.instance),"function"==typeof e&&e.call(this)},t.options.fadeTime)),t},w.prototype.hide=function(t){var e,n,i=this;return i.options.dataOnly||(i.ui.el.style.opacity=i.options.restOpacity,clearTimeout(i.removeTimeout),clearTimeout(i.showTimeout),clearTimeout(i.restTimeout),i.removeTimeout=setTimeout(function(){var e="dynamic"===i.options.mode?"none":"block";i.ui.el.style.display=e,"function"==typeof t&&t.call(i),i.trigger("hidden",i.instance)},i.options.fadeTime),i.options.restJoystick&&(e=i.options.restJoystick,(n={}).x=!0===e||!1!==e.x?0:i.instance.frontPosition.x,n.y=!0===e||!1!==e.y?0:i.instance.frontPosition.y,i.setPosition(t,n))),i},w.prototype.setPosition=function(e,t){var n=this,t=(n.frontPosition={x:t.x,y:t.y},n.options.fadeTime+"ms"),i={},t=(i.front=c("transition",["transform"],t),{front:{}});t.front={transform:"translate("+n.frontPosition.x+"px,"+n.frontPosition.y+"px)"},n.applyStyles(i),n.applyStyles(t),n.restTimeout=setTimeout(function(){"function"==typeof e&&e.call(n),n.restCallback()},n.options.fadeTime)},w.prototype.restCallback=function(){var e={};e.front=c("transition","none",""),this.applyStyles(e),this.trigger("rested",this.instance)},w.prototype.resetDirection=function(){this.direction={x:!1,y:!1,angle:!1}},w.prototype.computeDirection=function(e){var t,n,i,o=e.angle.radian,s=Math.PI/4,a=Math.PI/2;if(s<o&&o<3*s&&!e.lockX?t="up":-s<o&&o<=s&&!e.lockY?t="left":3*-s<o&&o<=-s&&!e.lockX?t="down":e.lockY||(t="right"),e.lockY||(n=-a<o&&o<a?"left":"right"),e.lockX||(i=0<o?"up":"down"),e.force>this.options.threshold){var r,l={};for(r in this.direction)this.direction.hasOwnProperty(r)&&(l[r]=this.direction[r]);var c={};for(r in this.direction={x:n,y:i,angle:t},e.direction=this.direction,l)l[r]===this.direction[r]&&(c[r]=!0);if(c.x&&c.y&&c.angle)return e;c.x&&c.y||this.trigger("plain",e),c.x||this.trigger("plain:"+n,e),c.y||this.trigger("plain:"+i,e),c.angle||this.trigger("dir dir:"+t,e)}else this.resetDirection();return e};var x=w;function E(e,t){this.nipples=[],this.idles=[],this.actives=[],this.ids=[],this.pressureIntervals={},this.manager=e,this.id=E.id,E.id+=1,this.defaults={zone:document.body,multitouch:!1,maxNumberOfNipples:10,mode:"dynamic",position:{top:0,left:0},catchDistance:200,size:100,threshold:.1,color:"white",fadeTime:250,dataOnly:!1,restJoystick:!0,restOpacity:.5,lockX:!1,lockY:!1,shape:"circle",dynamicPage:!1,follow:!1},this.config(t),"static"!==this.options.mode&&"semi"!==this.options.mode||(this.options.multitouch=!1),this.options.multitouch||(this.options.maxNumberOfNipples=1);e=getComputedStyle(this.options.zone.parentElement);return e&&"flex"===e.display&&(this.parentIsFlex=!0),this.updateBox(),this.prepareNipples(),this.bindings(),this.begin(),this.nipples}E.prototype=new m,(E.constructor=E).id=0,E.prototype.prepareNipples=function(){var i=this.nipples;i.on=this.on.bind(this),i.off=this.off.bind(this),i.options=this.options,i.destroy=this.destroy.bind(this),i.ids=this.ids,i.id=this.id,i.processOnMove=this.processOnMove.bind(this),i.processOnEnd=this.processOnEnd.bind(this),i.get=function(e){if(void 0===e)return i[0];for(var t=0,n=i.length;t<n;t+=1)if(i[t].identifier===e)return i[t];return!1}},E.prototype.bindings=function(){this.bindEvt(this.options.zone,"start"),this.options.zone.style.touchAction="none",this.options.zone.style.msTouchAction="none"},E.prototype.begin=function(){var e=this.options;"static"===e.mode&&((e=this.createNipple(e.position,this.manager.getIdentifier())).add(),this.idles.push(e))},E.prototype.createNipple=function(e,t){var n=this.manager.scroll,i={},o=this.options,s=this.parentIsFlex?n.x:n.x+this.box.left,a=this.parentIsFlex?n.y:n.y+this.box.top,s=(e.x&&e.y?i={x:e.x-s,y:e.y-a}:(e.top||e.right||e.bottom||e.left)&&((s=document.createElement("DIV")).style.display="hidden",s.style.top=e.top,s.style.right=e.right,s.style.bottom=e.bottom,s.style.left=e.left,s.style.position="absolute",o.zone.appendChild(s),a=s.getBoundingClientRect(),o.zone.removeChild(s),i=e,e={x:a.left+n.x,y:a.top+n.y}),new x(this,{color:o.color,size:o.size,threshold:o.threshold,fadeTime:o.fadeTime,dataOnly:o.dataOnly,restJoystick:o.restJoystick,restOpacity:o.restOpacity,mode:o.mode,identifier:t,position:e,zone:o.zone,frontPosition:{x:0,y:0},shape:o.shape}));return o.dataOnly||(l(s.ui.el,i),l(s.ui.front,s.frontPosition)),this.nipples.push(s),this.trigger("added "+s.identifier+":added",s),this.manager.trigger("added "+s.identifier+":added",s),this.bindNipple(s),s},E.prototype.updateBox=function(){this.box=this.options.zone.getBoundingClientRect()},E.prototype.bindNipple=function(e){function t(e,t){n=e.type+" "+t.id+":"+e.type,i.trigger(n,t)}var n,i=this;e.on("destroyed",i.onDestroyed.bind(i)),e.on("shown hidden rested dir plain",t),e.on("dir:up dir:right dir:down dir:left",t),e.on("plain:up plain:right plain:down plain:left",t)},E.prototype.pressureFn=function(t,n,e){var i=this,o=0;clearInterval(i.pressureIntervals[e]),i.pressureIntervals[e]=setInterval(function(){var e=t.force||t.pressure||t.webkitForce||0;e!==o&&(n.trigger("pressure",e),i.trigger("pressure "+n.identifier+":pressure",e),o=e)}.bind(i),100)},E.prototype.onstart=function(n){var i=this,t=i.options,o=n;return n=a(n),i.updateBox(),u(n,function(e){(i.actives.length<t.maxNumberOfNipples||o.type.match(/^touch/)&&(Object.keys(i.manager.ids).forEach(function(t){var e;Object.values(o.touches).findIndex(function(e){return e.identifier===t})<0&&((e=[n[0]]).identifier=t,i.processOnEnd(e))}),i.actives.length<t.maxNumberOfNipples))&&i.processOnStart(e)}),i.manager.bindDocument(),!1},E.prototype.processOnStart=function(t){function e(e){e.trigger("start",e),n.trigger("start "+e.id+":start",e),e.show(),0<s&&n.pressureFn(t,e,e.identifier),n.processOnMove(t)}var n=this,i=n.options,o=n.manager.getIdentifier(t),s=t.force||t.pressure||t.webkitForce||0,a={x:t.pageX,y:t.pageY},r=n.getOrCreate(o,a);r.identifier!==o&&n.manager.removeIdentifier(r.identifier),r.identifier=o;if(0<=(o=n.idles.indexOf(r))&&n.idles.splice(o,1),n.actives.push(r),n.ids.push(r.identifier),"semi"!==i.mode||_(a,r.position)<=i.catchDistance)return e(r),r;r.destroy(),n.processOnStart(t)},E.prototype.getOrCreate=function(e,t){var n,i=this.options;return/(semi|static)/.test(i.mode)?(n=this.idles[0])?(this.idles.splice(0,1),n):"semi"===i.mode?this.createNipple(t,e):(console.warn("Coudln't find the needed nipple."),!1):this.createNipple(t,e)},E.prototype.processOnMove=function(e){var t,n,i,o,s,a,r,l,c,h,d,u,p,f,m=this.options,y=this.manager.getIdentifier(e),g=this.nipples.get(y),v=this.manager.scroll;f=e,(isNaN(f.buttons)?0!==f.pressure:0!==f.buttons)?g?(m.dynamicPage&&(f=g.el.getBoundingClientRect(),g.position={x:v.x+f.left,y:v.y+f.top}),g.identifier=y,f=g.options.size/2,t={x:e.pageX,y:e.pageY},m.lockX&&(t.y=g.position.y),m.lockY&&(t.x=g.position.x),o=_(t,g.position),s=t,a=g.position,r=a.x-s.x,a=a.y-s.y,s=Math.atan2(a,r)*(180/Math.PI),a=T(s),r=o/f,l={distance:o,position:t},"circle"===g.options.shape?(n=Math.min(o,f),i=g.position,d=n,p={x:0,y:0},u=T(s),p.x=i.x-d*Math.cos(u),p.y=i.y-d*Math.sin(u),i=p):(d=t,u=g.position,p=f,i={x:Math.min(Math.max(d.x,u.x-p),u.x+p),y:Math.min(Math.max(d.y,u.y-p),u.y+p)},n=_(i,g.position)),m.follow?f<o&&(c=t.x-i.x,h=t.y-i.y,g.position.x+=c,g.position.y+=h,g.el.style.top=g.position.y-(this.box.top+v.y)+"px",g.el.style.left=g.position.x-(this.box.left+v.x)+"px",o=_(t,g.position)):(t=i,o=n),c=t.x-g.position.x,h=t.y-g.position.y,g.frontPosition={x:c,y:h},m.dataOnly||(g.ui.front.style.transform="translate("+c+"px,"+h+"px)"),v={identifier:g.identifier,position:t,force:r,pressure:e.force||e.pressure||e.webkitForce||0,distance:o,angle:{radian:a,degree:s},vector:{x:c/f,y:-h/f},raw:l,instance:g,lockX:m.lockX,lockY:m.lockY},(v=g.computeDirection(v)).angle={radian:T(180-s),degree:180-s},g.trigger("move",v),this.trigger("move "+g.id+":move",v)):(console.error("Found zombie joystick with ID "+y),this.manager.removeIdentifier(y)):this.processOnEnd(e)},E.prototype.processOnEnd=function(e){var t=this,n=t.options,e=t.manager.getIdentifier(e),i=t.nipples.get(e),e=t.manager.removeIdentifier(i.identifier);i&&(n.dataOnly||i.hide(function(){"dynamic"===n.mode&&(i.trigger("removed",i),t.trigger("removed "+i.id+":removed",i),t.manager.trigger("removed "+i.id+":removed",i),i.destroy())}),clearInterval(t.pressureIntervals[i.identifier]),i.resetDirection(),i.trigger("end",i),t.trigger("end "+i.id+":end",i),0<=t.ids.indexOf(i.identifier)&&t.ids.splice(t.ids.indexOf(i.identifier),1),0<=t.actives.indexOf(i)&&t.actives.splice(t.actives.indexOf(i),1),/(semi|static)/.test(n.mode)?t.idles.push(i):0<=t.nipples.indexOf(i)&&t.nipples.splice(t.nipples.indexOf(i),1),t.manager.unbindDocument(),/(semi|static)/.test(n.mode))&&(t.manager.ids[e.id]=e.identifier)},E.prototype.onDestroyed=function(e,t){0<=this.nipples.indexOf(t)&&this.nipples.splice(this.nipples.indexOf(t),1),0<=this.actives.indexOf(t)&&this.actives.splice(this.actives.indexOf(t),1),0<=this.idles.indexOf(t)&&this.idles.splice(this.idles.indexOf(t),1),0<=this.ids.indexOf(t.identifier)&&this.ids.splice(this.ids.indexOf(t.identifier),1),this.manager.removeIdentifier(t.identifier),this.manager.unbindDocument()},E.prototype.destroy=function(){for(var e in this.unbindEvt(this.options.zone,"start"),this.nipples.forEach(function(e){e.destroy()}),this.pressureIntervals)this.pressureIntervals.hasOwnProperty(e)&&clearInterval(this.pressureIntervals[e]);this.trigger("destroyed",this.nipples),this.manager.unbindDocument(),this.off()};var C=E;function S(e){function t(){var t;i.collections.forEach(function(e){e.forEach(function(e){t=e.el.getBoundingClientRect(),e.position={x:i.scroll.x+t.left,y:i.scroll.y+t.top}})})}function n(){i.scroll=r()}var i=this;i.ids={},i.index=0,i.collections=[],i.scroll=r(),i.config(e),i.prepareCollections(),s(window,"resize",function(){o(t)});return s(window,"scroll",function(){o(n)}),i.collections}S.prototype=new m,(S.constructor=S).prototype.prepareCollections=function(){var e=this;e.collections.create=e.create.bind(e),e.collections.on=e.on.bind(e),e.collections.off=e.off.bind(e),e.collections.destroy=e.destroy.bind(e),e.collections.get=function(t){var n;return e.collections.every(function(e){return!(n=e.get(t))}),n}},S.prototype.create=function(e){return this.createCollection(e)},S.prototype.createCollection=function(e){e=new C(this,e);return this.bindCollection(e),this.collections.push(e),e},S.prototype.bindCollection=function(e){function t(e,t){n=e.type+" "+t.id+":"+e.type,i.trigger(n,t)}var n,i=this;e.on("destroyed",i.onDestroyed.bind(i)),e.on("shown hidden rested dir plain",t),e.on("dir:up dir:right dir:down dir:left",t),e.on("plain:up plain:right plain:down plain:left",t)},S.prototype.bindDocument=function(){this.binded||(this.bindEvt(document,"move").bindEvt(document,"end"),this.binded=!0)},S.prototype.unbindDocument=function(e){Object.keys(this.ids).length&&!0!==e||(this.unbindEvt(document,"move").unbindEvt(document,"end"),this.binded=!1)},S.prototype.getIdentifier=function(e){var t;return e?void 0===(t=void 0===e.identifier?e.pointerId:e.identifier)&&(t=this.latest||0):t=this.index,void 0===this.ids[t]&&(this.ids[t]=this.index,this.index+=1),this.latest=t,this.ids[t]},S.prototype.removeIdentifier=function(e){var t,n={};for(t in this.ids)if(this.ids[t]===e){n.id=t,n.identifier=this.ids[t],delete this.ids[t];break}return n},S.prototype.onmove=function(e){return this.onAny("move",e),!1},S.prototype.onend=function(e){return this.onAny("end",e),!1},S.prototype.oncancel=function(e){return this.onAny("end",e),!1},S.prototype.onAny=function(e,t){var n,i=this,o="processOn"+e.charAt(0).toUpperCase()+e.slice(1);t=a(t);return u(t,function(e){n=i.getIdentifier(e),u(i.collections,function(e,t,n){0<=n.ids.indexOf(t)&&(n[o](e),e._found_=!0)}.bind(null,e,n)),e._found_||i.removeIdentifier(n)}),!1},S.prototype.destroy=function(){this.unbindDocument(!0),this.ids={},this.index=0,this.collections.forEach(function(e){e.destroy()}),this.off()},S.prototype.onDestroyed=function(e,t){if(this.collections.indexOf(t)<0)return!1;this.collections.splice(this.collections.indexOf(t),1)};var P=new S;t.default={create:function(e){return P.create(e)},factory:P}}],i={},o.m=n,o.c=i,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(t,e){if(1&e&&(t=o(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)o.d(n,i,function(e){return t[e]}.bind(null,i));return n},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=0).default;function o(e){var t;return(i[e]||(t=i[e]={i:e,l:!1,exports:{}},n[e].call(t.exports,t,t.exports,o),t.l=!0,t)).exports}var n,i}),window.EJS_SHADERS={"2xScaleHQ.glslp":'shaders = 1\n\nshader0 = "2xScaleHQ.glsl"\nfilter_linear0 = false\nscale_type_0 = source\n',"4xScaleHQ.glslp":'shaders = 1\n\nshader0 = "4xScaleHQ.glsl"\nfilter_linear0 = false\nscale_type_0 = source\n',"crt-easymode.glslp":"shaders = 1\n\nshader0 = crt-easymode.glsl\nfilter_linear0 = false\nscale_type_0 = source\n","crt-aperture.glslp":"shaders = 1\n\nshader0 = crt-aperture.glsl\nfilter_linear0 = false\n","crt-geom.glslp":"shaders = 1\n\nshader0 = crt-geom.glsl\nfilter_linear0 = false\nscale_type_0 = source\n","crt-mattias.glslp":"\nshaders = 1\nshader0 = crt-mattias.glsl\nfilter_linear0 = false\n","2xScaleHQ.glsl":"/*\n2xGLSLHqFilter shader\n\nCopyright (C) 2005 guest(r) - guest.r@gmail.com\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*/\n\n#if defined(VERTEX)\n\n#if __VERSION__ >= 130\n#define COMPAT_VARYING out\n#define COMPAT_ATTRIBUTE in\n#define COMPAT_TEXTURE texture\n#else\n#define COMPAT_VARYING varying \n#define COMPAT_ATTRIBUTE attribute \n#define COMPAT_TEXTURE texture2D\n#endif\n\n#ifdef GL_ES\n#define COMPAT_PRECISION mediump\n#else\n#define COMPAT_PRECISION\n#endif\n\nCOMPAT_ATTRIBUTE vec4 VertexCoord;\nCOMPAT_ATTRIBUTE vec4 COLOR;\nCOMPAT_ATTRIBUTE vec4 TexCoord;\nCOMPAT_VARYING vec4 COL0;\nCOMPAT_VARYING vec4 TEX0;\nCOMPAT_VARYING vec4 t1;\nCOMPAT_VARYING vec4 t2;\nCOMPAT_VARYING vec4 t3;\nCOMPAT_VARYING vec4 t4;\n\nvec4 _oPosition1; \nuniform mat4 MVPMatrix;\nuniform COMPAT_PRECISION int FrameDirection;\nuniform COMPAT_PRECISION int FrameCount;\nuniform COMPAT_PRECISION vec2 OutputSize;\nuniform COMPAT_PRECISION vec2 TextureSize;\nuniform COMPAT_PRECISION vec2 InputSize;\n\n// compatibility #defines\n#define vTexCoord TEX0.xy\n#define SourceSize vec4(TextureSize, 1.0 / TextureSize) //either TextureSize or InputSize\n#define OutSize vec4(OutputSize, 1.0 / OutputSize)\n\nvoid main()\n{\ngl_Position = MVPMatrix * VertexCoord;\nTEX0.xy = TexCoord.xy;\nfloat x = 0.5 * SourceSize.z;\nfloat y = 0.5 * SourceSize.w;\nvec2 dg1 = vec2( x, y);\nvec2 dg2 = vec2(-x, y);\nvec2 dx = vec2(x, 0.0);\nvec2 dy = vec2(0.0, y);\nt1 = vec4(vTexCoord - dg1, vTexCoord - dy);\nt2 = vec4(vTexCoord - dg2, vTexCoord + dx);\nt3 = vec4(vTexCoord + dg1, vTexCoord + dy);\nt4 = vec4(vTexCoord + dg2, vTexCoord - dx);\n}\n\n#elif defined(FRAGMENT)\n\n#if __VERSION__ >= 130\n#define COMPAT_VARYING in\n#define COMPAT_TEXTURE texture\nout vec4 FragColor;\n#else\n#define COMPAT_VARYING varying\n#define FragColor gl_FragColor\n#define COMPAT_TEXTURE texture2D\n#endif\n\n#ifdef GL_ES\n#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n#define COMPAT_PRECISION mediump\n#else\n#define COMPAT_PRECISION\n#endif\n\nuniform COMPAT_PRECISION int FrameDirection;\nuniform COMPAT_PRECISION int FrameCount;\nuniform COMPAT_PRECISION vec2 OutputSize;\nuniform COMPAT_PRECISION vec2 TextureSize;\nuniform COMPAT_PRECISION vec2 InputSize;\nuniform sampler2D Texture;\nCOMPAT_VARYING vec4 TEX0;\nCOMPAT_VARYING vec4 t1;\nCOMPAT_VARYING vec4 t2;\nCOMPAT_VARYING vec4 t3;\nCOMPAT_VARYING vec4 t4;\n\n// compatibility #defines\n#define Source Texture\n#define vTexCoord TEX0.xy\n\n#define SourceSize vec4(TextureSize, 1.0 / TextureSize) //either TextureSize or InputSize\n#define OutSize vec4(OutputSize, 1.0 / OutputSize)\n\nfloat mx = 0.325; // start smoothing wt.\nfloat k = -0.250; // wt. decrease factor\nfloat max_w = 0.25; // max filter weight\nfloat min_w =-0.05; // min filter weight\nfloat lum_add = 0.25; // affects smoothing\nvec3 dt = vec3(1.0);\n\nvoid main()\n{\nvec3 c00 = COMPAT_TEXTURE(Source, t1.xy).xyz; \nvec3 c10 = COMPAT_TEXTURE(Source, t1.zw).xyz; \nvec3 c20 = COMPAT_TEXTURE(Source, t2.xy).xyz; \nvec3 c01 = COMPAT_TEXTURE(Source, t4.zw).xyz; \nvec3 c11 = COMPAT_TEXTURE(Source, vTexCoord).xyz; \nvec3 c21 = COMPAT_TEXTURE(Source, t2.zw).xyz; \nvec3 c02 = COMPAT_TEXTURE(Source, t4.xy).xyz; \nvec3 c12 = COMPAT_TEXTURE(Source, t3.zw).xyz; \nvec3 c22 = COMPAT_TEXTURE(Source, t3.xy).xyz; \n\nfloat md1 = dot(abs(c00 - c22), dt);\nfloat md2 = dot(abs(c02 - c20), dt);\n\nfloat w1 = dot(abs(c22 - c11), dt) * md2;\nfloat w2 = dot(abs(c02 - c11), dt) * md1;\nfloat w3 = dot(abs(c00 - c11), dt) * md2;\nfloat w4 = dot(abs(c20 - c11), dt) * md1;\n\nfloat t1 = w1 + w3;\nfloat t2 = w2 + w4;\nfloat ww = max(t1, t2) + 0.0001;\n\nc11 = (w1 * c00 + w2 * c20 + w3 * c22 + w4 * c02 + ww * c11) / (t1 + t2 + ww);\n\nfloat lc1 = k / (0.12 * dot(c10 + c12 + c11, dt) + lum_add);\nfloat lc2 = k / (0.12 * dot(c01 + c21 + c11, dt) + lum_add);\n\nw1 = clamp(lc1 * dot(abs(c11 - c10), dt) + mx, min_w, max_w);\nw2 = clamp(lc2 * dot(abs(c11 - c21), dt) + mx, min_w, max_w);\nw3 = clamp(lc1 * dot(abs(c11 - c12), dt) + mx, min_w, max_w);\nw4 = clamp(lc2 * dot(abs(c11 - c01), dt) + mx, min_w, max_w);\nFragColor = vec4(w1 * c10 + w2 * c21 + w3 * c12 + w4 * c01 + (1.0 - w1 - w2 - w3 - w4) * c11, 1.0);\n} \n#endif\n","4xScaleHQ.glsl":"/*\n4xGLSLHqFilter shader\n\nCopyright (C) 2005 guest(r) - guest.r@gmail.com\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*/\n\n#if defined(VERTEX)\n\n#if __VERSION__ >= 130\n#define COMPAT_VARYING out\n#define COMPAT_ATTRIBUTE in\n#define COMPAT_TEXTURE texture\n#else\n#define COMPAT_VARYING varying \n#define COMPAT_ATTRIBUTE attribute \n#define COMPAT_TEXTURE texture2D\n#endif\n\n#ifdef GL_ES\n#define COMPAT_PRECISION mediump\n#else\n#define COMPAT_PRECISION\n#endif\n\nCOMPAT_ATTRIBUTE vec4 VertexCoord;\nCOMPAT_ATTRIBUTE vec4 COLOR;\nCOMPAT_ATTRIBUTE vec4 TexCoord;\nCOMPAT_VARYING vec4 COL0;\nCOMPAT_VARYING vec4 TEX0;\nCOMPAT_VARYING vec4 t1;\nCOMPAT_VARYING vec4 t2;\nCOMPAT_VARYING vec4 t3;\nCOMPAT_VARYING vec4 t4;\nCOMPAT_VARYING vec4 t5;\nCOMPAT_VARYING vec4 t6;\n\nvec4 _oPosition1; \nuniform mat4 MVPMatrix;\nuniform COMPAT_PRECISION int FrameDirection;\nuniform COMPAT_PRECISION int FrameCount;\nuniform COMPAT_PRECISION vec2 OutputSize;\nuniform COMPAT_PRECISION vec2 TextureSize;\nuniform COMPAT_PRECISION vec2 InputSize;\n\n// compatibility #defines\n#define vTexCoord TEX0.xy\n#define SourceSize vec4(TextureSize, 1.0 / TextureSize) //either TextureSize or InputSize\n#define OutSize vec4(OutputSize, 1.0 / OutputSize)\n\nvoid main()\n{\ngl_Position = MVPMatrix * VertexCoord;\nTEX0.xy = TexCoord.xy;\nfloat x = 0.5 * SourceSize.z;\nfloat y = 0.5 * SourceSize.w;\nvec2 dg1 = vec2( x, y);\nvec2 dg2 = vec2(-x, y);\nvec2 sd1 = dg1 * 0.5;\nvec2 sd2 = dg2 * 0.5;\nvec2 ddx = vec2(x, 0.0);\nvec2 ddy = vec2(0.0, y);\nt1 = vec4(vTexCoord - sd1, vTexCoord - ddy);\nt2 = vec4(vTexCoord - sd2, vTexCoord + ddx);\nt3 = vec4(vTexCoord + sd1, vTexCoord + ddy);\nt4 = vec4(vTexCoord + sd2, vTexCoord - ddx);\nt5 = vec4(vTexCoord - dg1, vTexCoord - dg2);\nt6 = vec4(vTexCoord + dg1, vTexCoord + dg2);\n}\n\n#elif defined(FRAGMENT)\n\n#if __VERSION__ >= 130\n#define COMPAT_VARYING in\n#define COMPAT_TEXTURE texture\nout vec4 FragColor;\n#else\n#define COMPAT_VARYING varying\n#define FragColor gl_FragColor\n#define COMPAT_TEXTURE texture2D\n#endif\n\n#ifdef GL_ES\n#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n#define COMPAT_PRECISION mediump\n#else\n#define COMPAT_PRECISION\n#endif\n\nuniform COMPAT_PRECISION int FrameDirection;\nuniform COMPAT_PRECISION int FrameCount;\nuniform COMPAT_PRECISION vec2 OutputSize;\nuniform COMPAT_PRECISION vec2 TextureSize;\nuniform COMPAT_PRECISION vec2 InputSize;\nuniform sampler2D Texture;\nCOMPAT_VARYING vec4 TEX0;\nCOMPAT_VARYING vec4 t1;\nCOMPAT_VARYING vec4 t2;\nCOMPAT_VARYING vec4 t3;\nCOMPAT_VARYING vec4 t4;\nCOMPAT_VARYING vec4 t5;\nCOMPAT_VARYING vec4 t6;\n\n// compatibility #defines\n#define Source Texture\n#define vTexCoord TEX0.xy\n\n#define SourceSize vec4(TextureSize, 1.0 / TextureSize) //either TextureSize or InputSize\n#define OutSize vec4(OutputSize, 1.0 / OutputSize)\n\nfloat mx = 1.0; // start smoothing wt.\nfloat k = -1.10; // wt. decrease factor\nfloat max_w = 0.75; // max filter weight\nfloat min_w = 0.03; // min filter weight\nfloat lum_add = 0.33; // affects smoothing\nvec3 dt = vec3(1.0);\n\nvoid main()\n{\nvec3 c = COMPAT_TEXTURE(Source, vTexCoord).xyz;\nvec3 i1 = COMPAT_TEXTURE(Source, t1.xy).xyz; \nvec3 i2 = COMPAT_TEXTURE(Source, t2.xy).xyz; \nvec3 i3 = COMPAT_TEXTURE(Source, t3.xy).xyz; \nvec3 i4 = COMPAT_TEXTURE(Source, t4.xy).xyz; \nvec3 o1 = COMPAT_TEXTURE(Source, t5.xy).xyz; \nvec3 o3 = COMPAT_TEXTURE(Source, t6.xy).xyz; \nvec3 o2 = COMPAT_TEXTURE(Source, t5.zw).xyz;\nvec3 o4 = COMPAT_TEXTURE(Source, t6.zw).xyz;\nvec3 s1 = COMPAT_TEXTURE(Source, t1.zw).xyz; \nvec3 s2 = COMPAT_TEXTURE(Source, t2.zw).xyz; \nvec3 s3 = COMPAT_TEXTURE(Source, t3.zw).xyz; \nvec3 s4 = COMPAT_TEXTURE(Source, t4.zw).xyz; \n\nfloat ko1=dot(abs(o1-c),dt);\nfloat ko2=dot(abs(o2-c),dt);\nfloat ko3=dot(abs(o3-c),dt);\nfloat ko4=dot(abs(o4-c),dt);\n\nfloat k1=min(dot(abs(i1-i3),dt),max(ko1,ko3));\nfloat k2=min(dot(abs(i2-i4),dt),max(ko2,ko4));\n\nfloat w1 = k2; if(ko3<ko1) w1*=ko3/ko1;\nfloat w2 = k1; if(ko4<ko2) w2*=ko4/ko2;\nfloat w3 = k2; if(ko1<ko3) w3*=ko1/ko3;\nfloat w4 = k1; if(ko2<ko4) w4*=ko2/ko4;\n\nc=(w1*o1+w2*o2+w3*o3+w4*o4+0.001*c)/(w1+w2+w3+w4+0.001);\nw1 = k*dot(abs(i1-c)+abs(i3-c),dt)/(0.125*dot(i1+i3,dt)+lum_add);\nw2 = k*dot(abs(i2-c)+abs(i4-c),dt)/(0.125*dot(i2+i4,dt)+lum_add);\nw3 = k*dot(abs(s1-c)+abs(s3-c),dt)/(0.125*dot(s1+s3,dt)+lum_add);\nw4 = k*dot(abs(s2-c)+abs(s4-c),dt)/(0.125*dot(s2+s4,dt)+lum_add);\n\nw1 = clamp(w1+mx,min_w,max_w); \nw2 = clamp(w2+mx,min_w,max_w);\nw3 = clamp(w3+mx,min_w,max_w); \nw4 = clamp(w4+mx,min_w,max_w);\n\nFragColor = vec4((w1*(i1+i3)+w2*(i2+i4)+w3*(s1+s3)+w4*(s2+s4)+c)/(2.0*(w1+w2+w3+w4)+1.0), 1.0);\n} \n#endif\n","crt-easymode.glsl":"#if defined(VERTEX)\n\n #if __VERSION__ >= 130\n #define COMPAT_VARYING out\n #define COMPAT_ATTRIBUTE in\n #define COMPAT_TEXTURE texture\n #else\n #define COMPAT_VARYING varying\n #define COMPAT_ATTRIBUTE attribute\n #define COMPAT_TEXTURE texture2D\n #endif\n \n #ifdef GL_ES\n #define COMPAT_PRECISION mediump\n #else\n #define COMPAT_PRECISION\n #endif\n COMPAT_VARYING float _frame_rotation;\n struct input_dummy {\n vec2 _video_size;\n vec2 _texture_size;\n vec2 _output_dummy_size;\n float _frame_count;\n float _frame_direction;\n float _frame_rotation;\n };\n vec4 _oPosition1;\n vec4 _r0005;\n COMPAT_ATTRIBUTE vec4 VertexCoord;\n COMPAT_ATTRIBUTE vec4 TexCoord;\n COMPAT_VARYING vec4 TEX0;\n \n uniform mat4 MVPMatrix;\n uniform int FrameDirection;\n uniform int FrameCount;\n uniform COMPAT_PRECISION vec2 OutputSize;\n uniform COMPAT_PRECISION vec2 TextureSize;\n uniform COMPAT_PRECISION vec2 InputSize;\n void main()\n {\n vec2 _oTex;\n _r0005 = VertexCoord.x*MVPMatrix[0];\n _r0005 = _r0005 + VertexCoord.y*MVPMatrix[1];\n _r0005 = _r0005 + VertexCoord.z*MVPMatrix[2];\n _r0005 = _r0005 + VertexCoord.w*MVPMatrix[3];\n _oPosition1 = _r0005;\n _oTex = TexCoord.xy;\n gl_Position = _r0005;\n TEX0.xy = TexCoord.xy;\n }\n #elif defined(FRAGMENT)\n \n #if __VERSION__ >= 130\n #define COMPAT_VARYING in\n #define COMPAT_TEXTURE texture\n out vec4 FragColor;\n #else\n #define COMPAT_VARYING varying\n #define FragColor gl_FragColor\n #define COMPAT_TEXTURE texture2D\n #endif\n \n #ifdef GL_ES\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n #else\n precision mediump float;\n #endif\n #define COMPAT_PRECISION mediump\n #else\n #define COMPAT_PRECISION\n #endif\n COMPAT_VARYING float _frame_rotation;\n struct input_dummy {\n vec2 _video_size;\n vec2 _texture_size;\n vec2 _output_dummy_size;\n float _frame_count;\n float _frame_direction;\n float _frame_rotation;\n };\n vec4 _ret_0;\n float _TMP30;\n float _TMP29;\n float _TMP28;\n float _TMP13;\n float _TMP32;\n float _TMP11;\n float _TMP10;\n float _TMP31;\n float _TMP9;\n float _TMP8;\n float _TMP15;\n float _TMP14;\n float _TMP33;\n vec4 _TMP34;\n vec4 _TMP27;\n vec4 _TMP25;\n vec4 _TMP23;\n vec4 _TMP21;\n vec4 _TMP26;\n vec4 _TMP24;\n vec4 _TMP22;\n vec4 _TMP20;\n float _TMP4;\n vec4 _TMP3;\n vec4 _TMP2;\n float _TMP19;\n float _TMP18;\n float _TMP17;\n float _TMP16;\n vec4 _TMP1;\n vec2 _TMP0;\n uniform sampler2D Texture;\n input_dummy _IN1;\n float _TMP43;\n float _x_step0044;\n float _curve0044;\n float _a0048;\n float _val0052;\n float _a0052;\n vec4 _TMP57;\n vec4 _x0072;\n vec2 _c0086;\n vec4 _x0088;\n vec4 _x0094;\n vec2 _c0098;\n vec4 _x0100;\n vec2 _c0104;\n vec4 _x0106;\n vec4 _sample_min0110;\n vec4 _sample_max0110;\n vec4 _r0112;\n vec4 _TMP117;\n vec2 _co0124;\n vec2 _c0126;\n vec4 _x0128;\n vec4 _x0134;\n vec2 _c0138;\n vec4 _x0140;\n vec2 _c0144;\n vec4 _x0146;\n vec4 _sample_min0150;\n vec4 _sample_max0150;\n vec4 _r0152;\n vec4 _TMP157;\n float _TMP163;\n float _x_step0164;\n float _curve0164;\n float _a0168;\n float _val0172;\n float _a0172;\n float _TMP183;\n float _TMP189;\n float _x0190;\n float _a0196;\n float _x0198;\n vec2 _x0200;\n float _x0208;\n COMPAT_VARYING vec4 TEX0;\n \n uniform COMPAT_PRECISION vec2 OutputSize;\n uniform COMPAT_PRECISION vec2 TextureSize;\n uniform COMPAT_PRECISION vec2 InputSize;\n void main()\n {\n vec2 _dx1;\n vec2 _dy;\n vec2 _pix_co;\n vec2 _tex_co;\n vec2 _dist;\n vec3 _col2;\n vec3 _col21;\n vec4 _coeffs1;\n float _luma;\n float _bright;\n float _scan_weight;\n vec2 _mod_fac;\n int _dot_no;\n vec3 _mask_weight;\n vec3 _TMP37;\n _dx1 = vec2(1.00000000E+00/TextureSize.x, 0.00000000E+00);\n _dy = vec2(0.00000000E+00, 1.00000000E+00/TextureSize.y);\n _pix_co = TEX0.xy*TextureSize - vec2( 5.00000000E-01, 5.00000000E-01);\n _TMP0 = floor(_pix_co);\n _tex_co = (_TMP0 + vec2( 5.00000000E-01, 5.00000000E-01))/TextureSize;\n _dist = fract(_pix_co);\n _x_step0044 = float((_dist.x >= 5.00000000E-01));\n _a0048 = 2.50000000E-01 - (_dist.x - _x_step0044)*(_dist.x - _x_step0044);\n _TMP33 = inversesqrt(_a0048);\n _TMP14 = 1.00000000E+00/_TMP33;\n _a0052 = 5.00000000E-01 - _dist.x;\n _val0052 = float((_a0052 > 0.00000000E+00));\n _TMP15 = _val0052 - float((_a0052 < 0.00000000E+00));\n _curve0044 = 5.00000000E-01 - _TMP14*_TMP15;\n _TMP43 = _dist.x + 2.50000000E-01*(_curve0044 - _dist.x);\n _coeffs1 = 3.14159274E+00*vec4(1.00000000E+00 + _TMP43, _TMP43, 1.00000000E+00 - _TMP43, 2.00000000E+00 - _TMP43);\n _TMP1 = abs(_coeffs1);\n _TMP57 = max(_TMP1, vec4( 9.99999975E-06, 9.99999975E-06, 9.99999975E-06, 9.99999975E-06));\n _TMP16 = sin(_TMP57.x);\n _TMP17 = sin(_TMP57.y);\n _TMP18 = sin(_TMP57.z);\n _TMP19 = sin(_TMP57.w);\n _TMP2 = vec4(_TMP16, _TMP17, _TMP18, _TMP19);\n _x0072 = _TMP57/2.00000000E+00;\n _TMP16 = sin(_x0072.x);\n _TMP17 = sin(_x0072.y);\n _TMP18 = sin(_x0072.z);\n _TMP19 = sin(_x0072.w);\n _TMP3 = vec4(_TMP16, _TMP17, _TMP18, _TMP19);\n _coeffs1 = ((2.00000000E+00*_TMP2)*_TMP3)/(_TMP57*_TMP57);\n _TMP4 = dot(_coeffs1, vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _coeffs1 = _coeffs1/_TMP4;\n _c0086 = _tex_co - _dx1;\n _TMP20 = COMPAT_TEXTURE(Texture, _c0086);\n _x0088 = vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00) + (_TMP20 - vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _TMP21 = _TMP20*_x0088;\n _TMP22 = COMPAT_TEXTURE(Texture, _tex_co);\n _x0094 = vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00) + (_TMP22 - vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _TMP23 = _TMP22*_x0094;\n _c0098 = _tex_co + _dx1;\n _TMP24 = COMPAT_TEXTURE(Texture, _c0098);\n _x0100 = vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00) + (_TMP24 - vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _TMP25 = _TMP24*_x0100;\n _c0104 = _tex_co + 2.00000000E+00*_dx1;\n _TMP26 = COMPAT_TEXTURE(Texture, _c0104);\n _x0106 = vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00) + (_TMP26 - vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _TMP27 = _TMP26*_x0106;\n _r0112 = _coeffs1.x*_TMP21;\n _r0112 = _r0112 + _coeffs1.y*_TMP23;\n _r0112 = _r0112 + _coeffs1.z*_TMP25;\n _r0112 = _r0112 + _coeffs1.w*_TMP27;\n _sample_min0110 = min(_TMP23, _TMP25);\n _sample_max0110 = max(_TMP23, _TMP25);\n _TMP34 = min(_sample_max0110, _r0112);\n _TMP117 = max(_sample_min0110, _TMP34);\n _co0124 = _tex_co + _dy;\n _c0126 = _co0124 - _dx1;\n _TMP20 = COMPAT_TEXTURE(Texture, _c0126);\n _x0128 = vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00) + (_TMP20 - vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _TMP21 = _TMP20*_x0128;\n _TMP22 = COMPAT_TEXTURE(Texture, _co0124);\n _x0134 = vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00) + (_TMP22 - vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _TMP23 = _TMP22*_x0134;\n _c0138 = _co0124 + _dx1;\n _TMP24 = COMPAT_TEXTURE(Texture, _c0138);\n _x0140 = vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00) + (_TMP24 - vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _TMP25 = _TMP24*_x0140;\n _c0144 = _co0124 + 2.00000000E+00*_dx1;\n _TMP26 = COMPAT_TEXTURE(Texture, _c0144);\n _x0146 = vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00) + (_TMP26 - vec4( 1.00000000E+00, 1.00000000E+00, 1.00000000E+00, 1.00000000E+00));\n _TMP27 = _TMP26*_x0146;\n _r0152 = _coeffs1.x*_TMP21;\n _r0152 = _r0152 + _coeffs1.y*_TMP23;\n _r0152 = _r0152 + _coeffs1.z*_TMP25;\n _r0152 = _r0152 + _coeffs1.w*_TMP27;\n _sample_min0150 = min(_TMP23, _TMP25);\n _sample_max0150 = max(_TMP23, _TMP25);\n _TMP34 = min(_sample_max0150, _r0152);\n _TMP157 = max(_sample_min0150, _TMP34);\n _x_step0164 = float((_dist.y >= 5.00000000E-01));\n _a0168 = 2.50000000E-01 - (_dist.y - _x_step0164)*(_dist.y - _x_step0164);\n _TMP33 = inversesqrt(_a0168);\n _TMP14 = 1.00000000E+00/_TMP33;\n _a0172 = 5.00000000E-01 - _dist.y;\n _val0172 = float((_a0172 > 0.00000000E+00));\n _TMP15 = _val0172 - float((_a0172 < 0.00000000E+00));\n _curve0164 = 5.00000000E-01 - _TMP14*_TMP15;\n _TMP163 = _dist.y + (_curve0164 - _dist.y);\n _col2 = _TMP117.xyz + _TMP163*(_TMP157.xyz - _TMP117.xyz);\n _luma = dot(vec3( 2.12599993E-01, 7.15200007E-01, 7.22000003E-02), _col2);\n _TMP8 = max(_col2.y, _col2.z);\n _TMP9 = max(_col2.x, _TMP8);\n _bright = (_TMP9 + _luma)/2.00000000E+00;\n _TMP31 = min(6.49999976E-01, _bright);\n _TMP183 = max(3.49999994E-01, _TMP31);\n _x0190 = _bright*1.50000000E+00;\n _TMP31 = min(1.50000000E+00, _x0190);\n _TMP189 = max(1.50000000E+00, _TMP31);\n _a0196 = TEX0.y*2.00000000E+00*3.14159274E+00*TextureSize.y;\n _TMP10 = cos(_a0196);\n _x0198 = _TMP10*5.00000000E-01 + 5.00000000E-01;\n _TMP11 = pow(_x0198, _TMP189);\n _scan_weight = 1.00000000E+00 - _TMP11;\n _x0200 = (TEX0.xy*OutputSize*TextureSize)/InputSize;\n _mod_fac = floor(_x0200);\n _x0208 = _mod_fac.x/3.00000000E+00;\n _TMP32 = floor(_x0208);\n _TMP13 = _mod_fac.x - 3.00000000E+00*_TMP32;\n _dot_no = int(_TMP13);\n if (_dot_no == 0) {\n _mask_weight = vec3( 1.00000000E+00, 6.99999988E-01, 6.99999988E-01);\n } else {\n if (_dot_no == 1) {\n _mask_weight = vec3( 6.99999988E-01, 1.00000000E+00, 6.99999988E-01);\n } else {\n _mask_weight = vec3( 6.99999988E-01, 6.99999988E-01, 1.00000000E+00);\n }\n }\n if (InputSize.y >= 4.00000000E+02) {\n _scan_weight = 1.00000000E+00;\n }\n _col21 = _col2.xyz;\n _col2 = _col2*vec3(_scan_weight, _scan_weight, _scan_weight);\n _col2 = _col2 + _TMP183*(_col21 - _col2);\n _col2 = _col2*_mask_weight;\n _TMP28 = pow(_col2.x, 5.55555582E-01);\n _TMP29 = pow(_col2.y, 5.55555582E-01);\n _TMP30 = pow(_col2.z, 5.55555582E-01);\n _col2 = vec3(_TMP28, _TMP29, _TMP30);\n _TMP37 = _col2*1.20000005E+00;\n _ret_0 = vec4(_TMP37.x, _TMP37.y, _TMP37.z, 1.00000000E+00);\n FragColor = _ret_0;\n return;\n }\n #endif\n","crt-aperture.glsl":'\n/*\nCRT Shader by EasyMode\nLicense: GPL\n*/\n/*\n#pragma parameter SHARPNESS_IMAGE "Sharpness Image" 1.0 1.0 5.0 1.0\n#pragma parameter SHARPNESS_EDGES "Sharpness Edges" 3.0 1.0 5.0 1.0\n#pragma parameter GLOW_WIDTH "Glow Width" 0.5 0.05 0.65 0.05\n#pragma parameter GLOW_HEIGHT "Glow Height" 0.5 0.05 0.65 0.05\n#pragma parameter GLOW_HALATION "Glow Halation" 0.1 0.0 1.0 0.01\n#pragma parameter GLOW_DIFFUSION "Glow Diffusion" 0.05 0.0 1.0 0.01\n#pragma parameter MASK_COLORS "Mask Colors" 2.0 2.0 3.0 1.0\n#pragma parameter MASK_STRENGTH "Mask Strength" 0.3 0.0 1.0 0.05\n#pragma parameter MASK_SIZE "Mask Size" 1.0 1.0 9.0 1.0\n#pragma parameter SCANLINE_SIZE_MIN "Scanline Size Min." 0.5 0.5 1.5 0.05\n#pragma parameter SCANLINE_SIZE_MAX "Scanline Size Max." 1.5 0.5 1.5 0.05\n#pragma parameter GAMMA_INPUT "Gamma Input" 2.4 1.0 5.0 0.1\n#pragma parameter GAMMA_OUTPUT "Gamma Output" 2.4 1.0 5.0 0.1\n#pragma parameter BRIGHTNESS "Brightness" 1.5 0.0 2.0 0.05\n* */\n\n#define Coord TEX0\n\n#if defined(VERTEX)\n\n#if __VERSION__ >= 130\n#define OUT out\n#define IN in\n#define tex2D texture\n#else\n#define OUT varying \n#define IN attribute \n#define tex2D texture2D\n#endif\n\n#ifdef GL_ES\n#define PRECISION mediump\n#else\n#define PRECISION\n#endif\n\nIN vec4 VertexCoord;\nIN vec4 Color;\nIN vec2 TexCoord;\nOUT vec4 color;\nOUT vec2 Coord;\n\nuniform mat4 MVPMatrix;\nuniform PRECISION int FrameDirection;\nuniform PRECISION int FrameCount;\nuniform PRECISION vec2 OutputSize;\nuniform PRECISION vec2 TextureSize;\nuniform PRECISION vec2 InputSize;\n\nvoid main()\n{\ngl_Position = MVPMatrix * VertexCoord;\ncolor = Color;\nCoord = TexCoord;\n}\n\n#elif defined(FRAGMENT)\n\n#if __VERSION__ >= 130\n#define IN in\n#define tex2D texture\nout vec4 FragColor;\n#else\n#define IN varying\n#define FragColor gl_FragColor\n#define tex2D texture2D\n#endif\n\n#ifdef GL_ES\n#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n#define PRECISION mediump\n#else\n#define PRECISION\n#endif\n\nuniform PRECISION int FrameDirection;\nuniform PRECISION int FrameCount;\nuniform PRECISION vec2 OutputSize;\nuniform PRECISION vec2 TextureSize;\nuniform PRECISION vec2 InputSize;\nuniform sampler2D Texture;\nIN vec2 Coord;\n\n#ifdef PARAMETER_UNIFORM\nuniform PRECISION float SHARPNESS_IMAGE;\nuniform PRECISION float SHARPNESS_EDGES;\nuniform PRECISION float GLOW_WIDTH;\nuniform PRECISION float GLOW_HEIGHT;\nuniform PRECISION float GLOW_HALATION;\nuniform PRECISION float GLOW_DIFFUSION;\nuniform PRECISION float MASK_COLORS;\nuniform PRECISION float MASK_STRENGTH;\nuniform PRECISION float MASK_SIZE;\nuniform PRECISION float SCANLINE_SIZE_MIN;\nuniform PRECISION float SCANLINE_SIZE_MAX;\nuniform PRECISION float GAMMA_INPUT;\nuniform PRECISION float GAMMA_OUTPUT;\nuniform PRECISION float BRIGHTNESS;\n#else\n#define SHARPNESS_IMAGE 1.0\n#define SHARPNESS_EDGES 3.0\n#define GLOW_WIDTH 0.5\n#define GLOW_HEIGHT 0.5\n#define GLOW_HALATION 0.1\n#define GLOW_DIFFUSION 0.05\n#define MASK_COLORS 2.0\n#define MASK_STRENGTH 0.3\n#define MASK_SIZE 1.0\n#define SCANLINE_SIZE_MIN 0.5\n#define SCANLINE_SIZE_MAX 1.5\n#define GAMMA_INPUT 2.4\n#define GAMMA_OUTPUT 2.4\n#define BRIGHTNESS 1.5\n#endif\n\n#define FIX(c) max(abs(c), 1e-5)\n#define PI 3.141592653589\n#define saturate(c) clamp(c, 0.0, 1.0)\n#define TEX2D(c) pow(tex2D(tex, c).rgb, vec3(GAMMA_INPUT))\n\nmat3 get_color_matrix(sampler2D tex, vec2 co, vec2 dx)\n{\nreturn mat3(TEX2D(co - dx), TEX2D(co), TEX2D(co + dx));\n}\n\nvec3 blur(mat3 m, float dist, float rad)\n{\nvec3 x = vec3(dist - 1.0, dist, dist + 1.0) / rad;\nvec3 w = exp2(x * x * -1.0);\n\nreturn (m[0] * w.x + m[1] * w.y + m[2] * w.z) / (w.x + w.y + w.z);\n}\n\nvec3 filter_gaussian(sampler2D tex, vec2 co, vec2 tex_size)\n{\nvec2 dx = vec2(1.0 / tex_size.x, 0.0);\nvec2 dy = vec2(0.0, 1.0 / tex_size.y);\nvec2 pix_co = co * tex_size;\nvec2 tex_co = (floor(pix_co) + 0.5) / tex_size;\nvec2 dist = (fract(pix_co) - 0.5) * -1.0;\n\nmat3 line0 = get_color_matrix(tex, tex_co - dy, dx);\nmat3 line1 = get_color_matrix(tex, tex_co, dx);\nmat3 line2 = get_color_matrix(tex, tex_co + dy, dx);\nmat3 column = mat3(blur(line0, dist.x, GLOW_WIDTH),\n blur(line1, dist.x, GLOW_WIDTH),\n blur(line2, dist.x, GLOW_WIDTH));\n\nreturn blur(column, dist.y, GLOW_HEIGHT);\n}\n\nvec3 filter_lanczos(sampler2D tex, vec2 co, vec2 tex_size, float sharp)\n{\ntex_size.x *= sharp;\n\nvec2 dx = vec2(1.0 / tex_size.x, 0.0);\nvec2 pix_co = co * tex_size - vec2(0.5, 0.0);\nvec2 tex_co = (floor(pix_co) + vec2(0.5, 0.0)) / tex_size;\nvec2 dist = fract(pix_co);\nvec4 coef = PI * vec4(dist.x + 1.0, dist.x, dist.x - 1.0, dist.x - 2.0);\n\ncoef = FIX(coef);\ncoef = 2.0 * sin(coef) * sin(coef / 2.0) / (coef * coef);\ncoef /= dot(coef, vec4(1.0));\n\nvec4 col1 = vec4(TEX2D(tex_co), 1.0);\nvec4 col2 = vec4(TEX2D(tex_co + dx), 1.0);\n\nreturn (mat4(col1, col1, col2, col2) * coef).rgb;\n}\n\nvec3 get_scanline_weight(float x, vec3 col)\n{\nvec3 beam = mix(vec3(SCANLINE_SIZE_MIN), vec3(SCANLINE_SIZE_MAX), col);\nvec3 x_mul = 2.0 / beam;\nvec3 x_offset = x_mul * 0.5;\n\nreturn smoothstep(0.0, 1.0, 1.0 - abs(x * x_mul - x_offset)) * x_offset;\n}\n\nvec3 get_mask_weight(float x)\n{\nfloat i = mod(floor(x * OutputSize.x * TextureSize.x / (InputSize.x * MASK_SIZE)), MASK_COLORS);\n\nif (i == 0.0) return mix(vec3(1.0, 0.0, 1.0), vec3(1.0, 0.0, 0.0), MASK_COLORS - 2.0);\nelse if (i == 1.0) return vec3(0.0, 1.0, 0.0);\nelse return vec3(0.0, 0.0, 1.0);\n}\n\nvoid main()\n{\nvec3 col_glow = filter_gaussian(Texture, Coord, TextureSize);\nvec3 col_soft = filter_lanczos(Texture, Coord, TextureSize, SHARPNESS_IMAGE);\nvec3 col_sharp = filter_lanczos(Texture, Coord, TextureSize, SHARPNESS_EDGES);\nvec3 col = sqrt(col_sharp * col_soft);\n\ncol *= get_scanline_weight(fract(Coord.y * TextureSize.y), col_soft);\ncol_glow = saturate(col_glow - col);\ncol += col_glow * col_glow * GLOW_HALATION;\ncol = mix(col, col * get_mask_weight(Coord.x) * MASK_COLORS, MASK_STRENGTH);\ncol += col_glow * GLOW_DIFFUSION;\ncol = pow(col * BRIGHTNESS, vec3(1.0 / GAMMA_OUTPUT));\n\nFragColor = vec4(col, 1.0);\n}\n\n#endif\n',"crt-geom.glsl":'\n/*\nCRT-interlaced\n\nCopyright (C) 2010-2012 cgwg, Themaister and DOLLS\n\nThis program is free software; you can redistribute it and/or modify it\nunder the terms of the GNU General Public License as published by the Free\nSoftware Foundation; either version 2 of the License, or (at your option)\nany later version.\n\n(cgwg gave their consent to have the original version of this shader\ndistributed under the GPL in this message:\n\nhttp://board.byuu.org/viewtopic.php?p=26075#p26075\n\n"Feel free to distribute my shaders under the GPL. After all, the\nbarrel distortion code was taken from the Curvature shader, which is\nunder the GPL."\n)\nThis shader variant is pre-configured with screen curvature\n*/\n/*\n#pragma parameter CRTgamma "CRTGeom Target Gamma" 2.4 0.1 5.0 0.1\n#pragma parameter monitorgamma "CRTGeom Monitor Gamma" 2.2 0.1 5.0 0.1\n#pragma parameter d "CRTGeom Distance" 1.6 0.1 3.0 0.1\n#pragma parameter CURVATURE "CRTGeom Curvature Toggle" 1.0 0.0 1.0 1.0\n#pragma parameter R "CRTGeom Curvature Radius" 2.0 0.1 10.0 0.1\n#pragma parameter cornersize "CRTGeom Corner Size" 0.03 0.001 1.0 0.005\n#pragma parameter cornersmooth "CRTGeom Corner Smoothness" 1000.0 80.0 2000.0 100.0\n#pragma parameter x_tilt "CRTGeom Horizontal Tilt" 0.0 -0.5 0.5 0.05\n#pragma parameter y_tilt "CRTGeom Vertical Tilt" 0.0 -0.5 0.5 0.05\n#pragma parameter overscan_x "CRTGeom Horiz. Overscan %" 100.0 -125.0 125.0 1.0\n#pragma parameter overscan_y "CRTGeom Vert. Overscan %" 100.0 -125.0 125.0 1.0\n#pragma parameter DOTMASK "CRTGeom Dot Mask Toggle" 0.3 0.0 0.3 0.3\n#pragma parameter SHARPER "CRTGeom Sharpness" 1.0 1.0 3.0 1.0\n#pragma parameter scanline_weight "CRTGeom Scanline Weight" 0.3 0.1 0.5 0.05\n*/\n\n#ifndef PARAMETER_UNIFORM\n#define CRTgamma 2.4\n#define monitorgamma 2.2\n#define d 1.6\n#define CURVATURE 1.0\n#define R 2.0\n#define cornersize 0.03\n#define cornersmooth 1000.0\n#define x_tilt 0.0\n#define y_tilt 0.0\n#define overscan_x 100.0\n#define overscan_y 100.0\n#define DOTMASK 0.3\n#define SHARPER 1.0\n#define scanline_weight 0.3\n#endif\n\n#if defined(VERTEX)\n\n#if __VERSION__ >= 130\n#define COMPAT_VARYING out\n#define COMPAT_ATTRIBUTE in\n#define COMPAT_TEXTURE texture\n#else\n#define COMPAT_VARYING varying \n#define COMPAT_ATTRIBUTE attribute \n#define COMPAT_TEXTURE texture2D\n#endif\n\n#ifdef GL_ES\n#define COMPAT_PRECISION mediump\n#else\n#define COMPAT_PRECISION\n#endif\n\nCOMPAT_ATTRIBUTE vec4 VertexCoord;\nCOMPAT_ATTRIBUTE vec4 COLOR;\nCOMPAT_ATTRIBUTE vec4 TexCoord;\nCOMPAT_VARYING vec4 COL0;\nCOMPAT_VARYING vec4 TEX0;\n\nvec4 _oPosition1; \nuniform mat4 MVPMatrix;\nuniform COMPAT_PRECISION int FrameDirection;\nuniform COMPAT_PRECISION int FrameCount;\nuniform COMPAT_PRECISION vec2 OutputSize;\nuniform COMPAT_PRECISION vec2 TextureSize;\nuniform COMPAT_PRECISION vec2 InputSize;\n\nCOMPAT_VARYING vec2 overscan;\nCOMPAT_VARYING vec2 aspect;\nCOMPAT_VARYING vec3 stretch;\nCOMPAT_VARYING vec2 sinangle;\nCOMPAT_VARYING vec2 cosangle;\nCOMPAT_VARYING vec2 one;\nCOMPAT_VARYING float mod_factor;\nCOMPAT_VARYING vec2 ilfac;\n\n#ifdef PARAMETER_UNIFORM\nuniform COMPAT_PRECISION float CRTgamma;\nuniform COMPAT_PRECISION float monitorgamma;\nuniform COMPAT_PRECISION float d;\nuniform COMPAT_PRECISION float CURVATURE;\nuniform COMPAT_PRECISION float R;\nuniform COMPAT_PRECISION float cornersize;\nuniform COMPAT_PRECISION float cornersmooth;\nuniform COMPAT_PRECISION float x_tilt;\nuniform COMPAT_PRECISION float y_tilt;\nuniform COMPAT_PRECISION float overscan_x;\nuniform COMPAT_PRECISION float overscan_y;\nuniform COMPAT_PRECISION float DOTMASK;\nuniform COMPAT_PRECISION float SHARPER;\nuniform COMPAT_PRECISION float scanline_weight;\n#endif\n\n#define FIX(c) max(abs(c), 1e-5);\n\nfloat intersect(vec2 xy)\n{\nfloat A = dot(xy,xy)+d*d;\nfloat B = 2.0*(R*(dot(xy,sinangle)-d*cosangle.x*cosangle.y)-d*d);\nfloat C = d*d + 2.0*R*d*cosangle.x*cosangle.y;\nreturn (-B-sqrt(B*B-4.0*A*C))/(2.0*A);\n}\n\nvec2 bkwtrans(vec2 xy)\n{\nfloat c = intersect(xy);\nvec2 point = vec2(c)*xy;\npoint -= vec2(-R)*sinangle;\npoint /= vec2(R);\nvec2 tang = sinangle/cosangle;\nvec2 poc = point/cosangle;\nfloat A = dot(tang,tang)+1.0;\nfloat B = -2.0*dot(poc,tang);\nfloat C = dot(poc,poc)-1.0;\nfloat a = (-B+sqrt(B*B-4.0*A*C))/(2.0*A);\nvec2 uv = (point-a*sinangle)/cosangle;\nfloat r = R*acos(a);\nreturn uv*r/sin(r/R);\n}\n\nvec2 fwtrans(vec2 uv)\n{\nfloat r = FIX(sqrt(dot(uv,uv)));\nuv *= sin(r/R)/r;\nfloat x = 1.0-cos(r/R);\nfloat D = d/R + x*cosangle.x*cosangle.y+dot(uv,sinangle);\nreturn d*(uv*cosangle-x*sinangle)/D;\n}\n\nvec3 maxscale()\n{\nvec2 c = bkwtrans(-R * sinangle / (1.0 + R/d*cosangle.x*cosangle.y));\nvec2 a = vec2(0.5,0.5)*aspect;\nvec2 lo = vec2(fwtrans(vec2(-a.x,c.y)).x, fwtrans(vec2(c.x,-a.y)).y)/aspect;\nvec2 hi = vec2(fwtrans(vec2(+a.x,c.y)).x, fwtrans(vec2(c.x,+a.y)).y)/aspect;\nreturn vec3((hi+lo)*aspect*0.5,max(hi.x-lo.x,hi.y-lo.y));\n}\n\nvoid main()\n{\n// START of parameters\n\n// gamma of simulated CRT\n//\tCRTgamma = 1.8;\n// gamma of display monitor (typically 2.2 is correct)\n//\tmonitorgamma = 2.2;\n// overscan (e.g. 1.02 for 2% overscan)\noverscan = vec2(1.00,1.00);\n// aspect ratio\naspect = vec2(1.0, 0.75);\n// lengths are measured in units of (approximately) the width\n// of the monitor simulated distance from viewer to monitor\n//\td = 2.0;\n// radius of curvature\n//\tR = 1.5;\n// tilt angle in radians\n// (behavior might be a bit wrong if both components are\n// nonzero)\nconst vec2 angle = vec2(0.0,0.0);\n// size of curved corners\n//\tcornersize = 0.03;\n// border smoothness parameter\n// decrease if borders are too aliased\n//\tcornersmooth = 1000.0;\n\n// END of parameters\n\nvec4 _oColor;\nvec2 _otexCoord;\ngl_Position = VertexCoord.x * MVPMatrix[0] + VertexCoord.y * MVPMatrix[1] + VertexCoord.z * MVPMatrix[2] + VertexCoord.w * MVPMatrix[3];\n_oPosition1 = gl_Position;\n_oColor = COLOR;\n_otexCoord = TexCoord.xy;\nCOL0 = COLOR;\nTEX0.xy = TexCoord.xy;\n\n// Precalculate a bunch of useful values we\'ll need in the fragment\n// shader.\nsinangle = sin(vec2(x_tilt, y_tilt)) + vec2(0.001);//sin(vec2(max(abs(x_tilt), 1e-3), max(abs(y_tilt), 1e-3)));\ncosangle = cos(vec2(x_tilt, y_tilt)) + vec2(0.001);//cos(vec2(max(abs(x_tilt), 1e-3), max(abs(y_tilt), 1e-3)));\nstretch = maxscale();\n\nilfac = vec2(1.0,clamp(floor(InputSize.y/200.0), 1.0, 2.0));\n\n// The size of one texel, in texture-coordinates.\nvec2 sharpTextureSize = vec2(SHARPER * TextureSize.x, TextureSize.y);\none = ilfac / sharpTextureSize;\n\n// Resulting X pixel-coordinate of the pixel we\'re drawing.\nmod_factor = TexCoord.x * TextureSize.x * OutputSize.x / InputSize.x;\n\n}\n\n#elif defined(FRAGMENT)\n\n#if __VERSION__ >= 130\n#define COMPAT_VARYING in\n#define COMPAT_TEXTURE texture\nout vec4 FragColor;\n#else\n#define COMPAT_VARYING varying\n#define FragColor gl_FragColor\n#define COMPAT_TEXTURE texture2D\n#endif\n\n#ifdef GL_ES\n#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n#define COMPAT_PRECISION mediump\n#else\n#define COMPAT_PRECISION\n#endif\n\nstruct output_dummy {\nvec4 _color;\n};\n\nuniform COMPAT_PRECISION int FrameDirection;\nuniform COMPAT_PRECISION int FrameCount;\nuniform COMPAT_PRECISION vec2 OutputSize;\nuniform COMPAT_PRECISION vec2 TextureSize;\nuniform COMPAT_PRECISION vec2 InputSize;\nuniform sampler2D Texture;\nCOMPAT_VARYING vec4 TEX0;\n\n// Comment the next line to disable interpolation in linear gamma (and\n// gain speed).\n#define LINEAR_PROCESSING\n\n// Enable screen curvature.\n// #define CURVATURE\n\n// Enable 3x oversampling of the beam profile\n#define OVERSAMPLE\n\n// Use the older, purely gaussian beam profile\n//#define USEGAUSSIAN\n\n// Macros.\n#define FIX(c) max(abs(c), 1e-5);\n#define PI 3.141592653589\n\n#ifdef LINEAR_PROCESSING\n# define TEX2D(c) pow(COMPAT_TEXTURE(Texture, (c)), vec4(CRTgamma))\n#else\n# define TEX2D(c) COMPAT_TEXTURE(Texture, (c))\n#endif\n\nCOMPAT_VARYING vec2 one;\nCOMPAT_VARYING float mod_factor;\nCOMPAT_VARYING vec2 ilfac;\nCOMPAT_VARYING vec2 overscan;\nCOMPAT_VARYING vec2 aspect;\nCOMPAT_VARYING vec3 stretch;\nCOMPAT_VARYING vec2 sinangle;\nCOMPAT_VARYING vec2 cosangle;\n\n#ifdef PARAMETER_UNIFORM\nuniform COMPAT_PRECISION float CRTgamma;\nuniform COMPAT_PRECISION float monitorgamma;\nuniform COMPAT_PRECISION float d;\nuniform COMPAT_PRECISION float CURVATURE;\nuniform COMPAT_PRECISION float R;\nuniform COMPAT_PRECISION float cornersize;\nuniform COMPAT_PRECISION float cornersmooth;\nuniform COMPAT_PRECISION float x_tilt;\nuniform COMPAT_PRECISION float y_tilt;\nuniform COMPAT_PRECISION float overscan_x;\nuniform COMPAT_PRECISION float overscan_y;\nuniform COMPAT_PRECISION float DOTMASK;\nuniform COMPAT_PRECISION float SHARPER;\nuniform COMPAT_PRECISION float scanline_weight;\n#endif\n\nfloat intersect(vec2 xy)\n{\nfloat A = dot(xy,xy)+d*d;\nfloat B = 2.0*(R*(dot(xy,sinangle)-d*cosangle.x*cosangle.y)-d*d);\nfloat C = d*d + 2.0*R*d*cosangle.x*cosangle.y;\nreturn (-B-sqrt(B*B-4.0*A*C))/(2.0*A);\n}\n\nvec2 bkwtrans(vec2 xy)\n{\nfloat c = intersect(xy);\nvec2 point = vec2(c)*xy;\npoint -= vec2(-R)*sinangle;\npoint /= vec2(R);\nvec2 tang = sinangle/cosangle;\nvec2 poc = point/cosangle;\nfloat A = dot(tang,tang)+1.0;\nfloat B = -2.0*dot(poc,tang);\nfloat C = dot(poc,poc)-1.0;\nfloat a = (-B+sqrt(B*B-4.0*A*C))/(2.0*A);\nvec2 uv = (point-a*sinangle)/cosangle;\nfloat r = FIX(R*acos(a));\nreturn uv*r/sin(r/R);\n}\n\nvec2 transform(vec2 coord)\n{\ncoord *= TextureSize / InputSize;\ncoord = (coord-vec2(0.5))*aspect*stretch.z+stretch.xy;\nreturn (bkwtrans(coord)/vec2(overscan_x / 100.0, overscan_y / 100.0)/aspect+vec2(0.5)) * InputSize / TextureSize;\n}\n\nfloat corner(vec2 coord)\n{\ncoord *= TextureSize / InputSize;\ncoord = (coord - vec2(0.5)) * vec2(overscan_x / 100.0, overscan_y / 100.0) + vec2(0.5);\ncoord = min(coord, vec2(1.0)-coord) * aspect;\nvec2 cdist = vec2(cornersize);\ncoord = (cdist - min(coord,cdist));\nfloat dist = sqrt(dot(coord,coord));\nreturn clamp((cdist.x-dist)*cornersmooth,0.0, 1.0);\n}\n\n// Calculate the influence of a scanline on the current pixel.\n//\n// \'distance\' is the distance in texture coordinates from the current\n// pixel to the scanline in question.\n// \'color\' is the colour of the scanline at the horizontal location of\n// the current pixel.\nvec4 scanlineWeights(float distance, vec4 color)\n{\n// "wid" controls the width of the scanline beam, for each RGB\n// channel The "weights" lines basically specify the formula\n// that gives you the profile of the beam, i.e. the intensity as\n// a function of distance from the vertical center of the\n// scanline. In this case, it is gaussian if width=2, and\n// becomes nongaussian for larger widths. Ideally this should\n// be normalized so that the integral across the beam is\n// independent of its width. That is, for a narrower beam\n// "weights" should have a higher peak at the center of the\n// scanline than for a wider beam.\n#ifdef USEGAUSSIAN\nvec4 wid = 0.3 + 0.1 * pow(color, vec4(3.0));\nvec4 weights = vec4(distance / wid);\nreturn 0.4 * exp(-weights * weights) / wid;\n#else\nvec4 wid = 2.0 + 2.0 * pow(color, vec4(4.0));\nvec4 weights = vec4(distance / scanline_weight);\nreturn 1.4 * exp(-pow(weights * inversesqrt(0.5 * wid), wid)) / (0.6 + 0.2 * wid);\n#endif\n}\n\nvoid main()\n{\n// Here\'s a helpful diagram to keep in mind while trying to\n// understand the code:\n//\n// | | | | |\n// -------------------------------\n// | | | | |\n// | 01 | 11 | 21 | 31 | <-- current scanline\n// | | @ | | |\n// -------------------------------\n// | | | | |\n// | 02 | 12 | 22 | 32 | <-- next scanline\n// | | | | |\n// -------------------------------\n// | | | | |\n//\n// Each character-cell represents a pixel on the output\n// surface, "@" represents the current pixel (always somewhere\n// in the bottom half of the current scan-line, or the top-half\n// of the next scanline). The grid of lines represents the\n// edges of the texels of the underlying texture.\n\n// Texture coordinates of the texel containing the active pixel.\nvec2 xy = (CURVATURE > 0.5) ? transform(TEX0.xy) : TEX0.xy;\n\nfloat cval = corner(xy);\n\n// Of all the pixels that are mapped onto the texel we are\n// currently rendering, which pixel are we currently rendering?\nvec2 ilvec = vec2(0.0,ilfac.y > 1.5 ? mod(float(FrameCount),2.0) : 0.0);\nvec2 ratio_scale = (xy * TextureSize - vec2(0.5) + ilvec)/ilfac;\n#ifdef OVERSAMPLE\nfloat filter_ = InputSize.y/OutputSize.y;//fwidth(ratio_scale.y);\n#endif\nvec2 uv_ratio = fract(ratio_scale);\n\n// Snap to the center of the underlying texel.\nxy = (floor(ratio_scale)*ilfac + vec2(0.5) - ilvec) / TextureSize;\n\n// Calculate Lanczos scaling coefficients describing the effect\n// of various neighbour texels in a scanline on the current\n// pixel.\nvec4 coeffs = PI * vec4(1.0 + uv_ratio.x, uv_ratio.x, 1.0 - uv_ratio.x, 2.0 - uv_ratio.x);\n\n// Prevent division by zero.\ncoeffs = FIX(coeffs);\n\n// Lanczos2 kernel.\ncoeffs = 2.0 * sin(coeffs) * sin(coeffs / 2.0) / (coeffs * coeffs);\n\n// Normalize.\ncoeffs /= dot(coeffs, vec4(1.0));\n\n// Calculate the effective colour of the current and next\n// scanlines at the horizontal location of the current pixel,\n// using the Lanczos coefficients above.\nvec4 col = clamp(mat4(\n TEX2D(xy + vec2(-one.x, 0.0)),\n TEX2D(xy),\n TEX2D(xy + vec2(one.x, 0.0)),\n TEX2D(xy + vec2(2.0 * one.x, 0.0))) * coeffs,\n 0.0, 1.0);\nvec4 col2 = clamp(mat4(\n TEX2D(xy + vec2(-one.x, one.y)),\n TEX2D(xy + vec2(0.0, one.y)),\n TEX2D(xy + one),\n TEX2D(xy + vec2(2.0 * one.x, one.y))) * coeffs,\n 0.0, 1.0);\n\n#ifndef LINEAR_PROCESSING\ncol = pow(col , vec4(CRTgamma));\ncol2 = pow(col2, vec4(CRTgamma));\n#endif\n\n// Calculate the influence of the current and next scanlines on\n// the current pixel.\nvec4 weights = scanlineWeights(uv_ratio.y, col);\nvec4 weights2 = scanlineWeights(1.0 - uv_ratio.y, col2);\n#ifdef OVERSAMPLE\nuv_ratio.y =uv_ratio.y+1.0/3.0*filter_;\nweights = (weights+scanlineWeights(uv_ratio.y, col))/3.0;\nweights2=(weights2+scanlineWeights(abs(1.0-uv_ratio.y), col2))/3.0;\nuv_ratio.y =uv_ratio.y-2.0/3.0*filter_;\nweights=weights+scanlineWeights(abs(uv_ratio.y), col)/3.0;\nweights2=weights2+scanlineWeights(abs(1.0-uv_ratio.y), col2)/3.0;\n#endif\n\nvec3 mul_res = (col * weights + col2 * weights2).rgb * vec3(cval);\n\n// dot-mask emulation:\n// Output pixels are alternately tinted green and magenta.\nvec3 dotMaskWeights = mix(\nvec3(1.0, 1.0 - DOTMASK, 1.0),\nvec3(1.0 - DOTMASK, 1.0, 1.0 - DOTMASK),\nfloor(mod(mod_factor, 2.0))\n);\n\nmul_res *= dotMaskWeights;\n\n// Convert the image gamma for display on our output device.\nmul_res = pow(mul_res, vec3(1.0 / monitorgamma));\n\n// Color the texel.\noutput_dummy _OUT;\n_OUT._color = vec4(mul_res, 1.0);\nFragColor = _OUT._color;\nreturn;\n} \n#endif\n\n',"crt-mattias.glsl":'\n#pragma parameter CURVATURE "Curvature" 0.5 0.0 1.0 0.05\n#pragma parameter SCANSPEED "Scanline Crawl Speed" 1.0 0.0 10.0 0.5\n#if defined(VERTEX)\n#if __VERSION__ >= 130\n#define COMPAT_VARYING out\n#define COMPAT_ATTRIBUTE in\n#define COMPAT_TEXTURE texture\n#else\n#define COMPAT_VARYING varying \n#define COMPAT_ATTRIBUTE attribute \n#define COMPAT_TEXTURE texture2D\n#endif\n\n#ifdef GL_ES\n#define COMPAT_PRECISION mediump\n#else\n#define COMPAT_PRECISION\n#endif\n\nCOMPAT_ATTRIBUTE vec4 VertexCoord;\nCOMPAT_ATTRIBUTE vec4 COLOR;\nCOMPAT_ATTRIBUTE vec4 TexCoord;\nCOMPAT_VARYING vec4 COL0;\nCOMPAT_VARYING vec4 TEX0;\n\nvec4 _oPosition1; \nuniform mat4 MVPMatrix;\nuniform COMPAT_PRECISION int FrameDirection;\nuniform COMPAT_PRECISION int FrameCount;\nuniform COMPAT_PRECISION vec2 OutputSize;\nuniform COMPAT_PRECISION vec2 TextureSize;\nuniform COMPAT_PRECISION vec2 InputSize;\n\n#define vTexCoord TEX0.xy\n#define SourceSize vec4(TextureSize, 1.0 / TextureSize) //either TextureSize or InputSize\n#define OutSize vec4(OutputSize, 1.0 / OutputSize)\n\nvoid main()\n{\n gl_Position = MVPMatrix * VertexCoord;\n TEX0.xy = TexCoord.xy;\n}\n\n#elif defined(FRAGMENT)\n\n#ifdef GL_ES\n#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n#define COMPAT_PRECISION mediump\n#else\n#define COMPAT_PRECISION\n#endif\n\n#if __VERSION__ >= 130\n#define COMPAT_VARYING in\n#define COMPAT_TEXTURE texture\nout COMPAT_PRECISION vec4 FragColor;\n#else\n#define COMPAT_VARYING varying\n#define FragColor gl_FragColor\n#define COMPAT_TEXTURE texture2D\n#endif\n\nuniform COMPAT_PRECISION int FrameDirection;\nuniform COMPAT_PRECISION int FrameCount;\nuniform COMPAT_PRECISION vec2 OutputSize;\nuniform COMPAT_PRECISION vec2 TextureSize;\nuniform COMPAT_PRECISION vec2 InputSize;\nuniform sampler2D Texture;\nCOMPAT_VARYING vec4 TEX0;\n\n// compatibility #defines\n#define Source Texture\n#define vTexCoord TEX0.xy\n\n#define SourceSize vec4(TextureSize, 1.0 / TextureSize) //either TextureSize or InputSize\n#define OutSize vec4(OutputSize, 1.0 / OutputSize)\n\n#ifdef PARAMETER_UNIFORM\nuniform COMPAT_PRECISION float CURVATURE, SCANSPEED;\n#else\n#define CURVATURE 0.5\n#define SCANSPEED 1.0\n#endif\n\n#define iChannel0 Texture\n#define iTime (float(FrameCount) / 60.0)\n#define iResolution OutputSize.xy\n#define fragCoord gl_FragCoord.xy\n\nvec3 sample_( sampler2D tex, vec2 tc )\n{\n vec3 s = pow(COMPAT_TEXTURE(tex,tc).rgb, vec3(2.2));\n return s;\n}\n\nvec3 blur(sampler2D tex, vec2 tc, float offs)\n{\n vec4 xoffs = offs * vec4(-2.0, -1.0, 1.0, 2.0) / (iResolution.x * TextureSize.x / InputSize.x);\n vec4 yoffs = offs * vec4(-2.0, -1.0, 1.0, 2.0) / (iResolution.y * TextureSize.y / InputSize.y);\n tc = tc * InputSize / TextureSize;\n \n vec3 color = vec3(0.0, 0.0, 0.0);\n color += sample_(tex,tc + vec2(xoffs.x, yoffs.x)) * 0.00366;\n color += sample_(tex,tc + vec2(xoffs.y, yoffs.x)) * 0.01465;\n color += sample_(tex,tc + vec2( 0.0, yoffs.x)) * 0.02564;\n color += sample_(tex,tc + vec2(xoffs.z, yoffs.x)) * 0.01465;\n color += sample_(tex,tc + vec2(xoffs.w, yoffs.x)) * 0.00366;\n \n color += sample_(tex,tc + vec2(xoffs.x, yoffs.y)) * 0.01465;\n color += sample_(tex,tc + vec2(xoffs.y, yoffs.y)) * 0.05861;\n color += sample_(tex,tc + vec2( 0.0, yoffs.y)) * 0.09524;\n color += sample_(tex,tc + vec2(xoffs.z, yoffs.y)) * 0.05861;\n color += sample_(tex,tc + vec2(xoffs.w, yoffs.y)) * 0.01465;\n \n color += sample_(tex,tc + vec2(xoffs.x, 0.0)) * 0.02564;\n color += sample_(tex,tc + vec2(xoffs.y, 0.0)) * 0.09524;\n color += sample_(tex,tc + vec2( 0.0, 0.0)) * 0.15018;\n color += sample_(tex,tc + vec2(xoffs.z, 0.0)) * 0.09524;\n color += sample_(tex,tc + vec2(xoffs.w, 0.0)) * 0.02564;\n \n color += sample_(tex,tc + vec2(xoffs.x, yoffs.z)) * 0.01465;\n color += sample_(tex,tc + vec2(xoffs.y, yoffs.z)) * 0.05861;\n color += sample_(tex,tc + vec2( 0.0, yoffs.z)) * 0.09524;\n color += sample_(tex,tc + vec2(xoffs.z, yoffs.z)) * 0.05861;\n color += sample_(tex,tc + vec2(xoffs.w, yoffs.z)) * 0.01465;\n \n color += sample_(tex,tc + vec2(xoffs.x, yoffs.w)) * 0.00366;\n color += sample_(tex,tc + vec2(xoffs.y, yoffs.w)) * 0.01465;\n color += sample_(tex,tc + vec2( 0.0, yoffs.w)) * 0.02564;\n color += sample_(tex,tc + vec2(xoffs.z, yoffs.w)) * 0.01465;\n color += sample_(tex,tc + vec2(xoffs.w, yoffs.w)) * 0.00366;\n\n return color;\n}\n\nfloat rand(vec2 co)\n{\n float a = 12.9898;\n float b = 78.233;\n float c = 43758.5453;\n float dt= dot(co.xy ,vec2(a,b));\n float sn= mod(dt,3.14);\n return fract(sin(sn) * c);\n}\n\nvec2 curve(vec2 uv)\n{\n uv = (uv - 0.5) * 2.0;\n uv *= 1.1;\t\n uv.x *= 1.0 + pow((abs(uv.y) / 5.0), 2.0);\n uv.y *= 1.0 + pow((abs(uv.x) / 4.0), 2.0);\n uv = (uv / 2.0) + 0.5;\n uv = uv *0.92 + 0.04;\n return uv;\n}\n\nvoid main()\n{\n vec2 q = (vTexCoord.xy * TextureSize.xy / InputSize.xy);//fragCoord.xy / iResolution.xy;\n vec2 uv = q;\n uv = mix( uv, curve( uv ), CURVATURE ) * InputSize.xy / TextureSize.xy;\n vec3 col;\n float x = sin(0.1*iTime+uv.y*21.0)*sin(0.23*iTime+uv.y*29.0)*sin(0.3+0.11*iTime+uv.y*31.0)*0.0017;\n float o =2.0*mod(fragCoord.y,2.0)/iResolution.x;\n x+=o;\n uv = uv * TextureSize / InputSize;\n col.r = 1.0*blur(iChannel0,vec2(uv.x+0.0009,uv.y+0.0009),1.2).x+0.005;\n col.g = 1.0*blur(iChannel0,vec2(uv.x+0.000,uv.y-0.0015),1.2).y+0.005;\n col.b = 1.0*blur(iChannel0,vec2(uv.x-0.0015,uv.y+0.000),1.2).z+0.005;\n col.r += 0.2*blur(iChannel0,vec2(uv.x+0.0009,uv.y+0.0009),2.25).x-0.005;\n col.g += 0.2*blur(iChannel0,vec2(uv.x+0.000,uv.y-0.0015),1.75).y-0.005;\n col.b += 0.2*blur(iChannel0,vec2(uv.x-0.0015,uv.y+0.000),1.25).z-0.005;\n float ghs = 0.05;\n col.r += ghs*(1.0-0.299)*blur(iChannel0,0.75*vec2(0.01, -0.027)+vec2(uv.x+0.001,uv.y+0.001),7.0).x;\n col.g += ghs*(1.0-0.587)*blur(iChannel0,0.75*vec2(-0.022, -0.02)+vec2(uv.x+0.000,uv.y-0.002),5.0).y;\n col.b += ghs*(1.0-0.114)*blur(iChannel0,0.75*vec2(-0.02, -0.0)+vec2(uv.x-0.002,uv.y+0.000),3.0).z;\n \n \n\n col = clamp(col*0.4+0.6*col*col*1.0,0.0,1.0);\n float vig = (0.0 + 1.0*16.0*uv.x*uv.y*(1.0-uv.x)*(1.0-uv.y));\n vig = pow(vig,0.3);\n col *= vec3(vig);\n\n col *= vec3(0.95,1.05,0.95);\n col = mix( col, col * col, 0.3) * 3.8;\n\n float scans = clamp( 0.35+0.15*sin(3.5*(iTime * SCANSPEED)+uv.y*iResolution.y*1.5), 0.0, 1.0);\n \n float s = pow(scans,0.9);\n col = col*vec3( s) ;\n\n col *= 1.0+0.0015*sin(300.0*iTime);\n \n col*=1.0-0.15*vec3(clamp((mod(fragCoord.x+o, 2.0)-1.0)*2.0,0.0,1.0));\n col *= vec3( 1.0 ) - 0.25*vec3( rand( uv+0.0001*iTime), rand( uv+0.0001*iTime + 0.3 ), rand( uv+0.0001*iTime+ 0.5 ) );\n col = pow(col, vec3(0.45));\n\n if (uv.x < 0.0 || uv.x > 1.0)\n col *= 0.0;\n if (uv.y < 0.0 || uv.y > 1.0)\n col *= 0.0;\n \n\n float comp = smoothstep( 0.1, 0.9, sin(iTime) );\n\n FragColor = vec4(col,1.0);\n} \n#endif\n'};class EJS_STORAGE{constructor(e,t){this.dbName=e,this.storeName=t}addFileToDB(n,i){(async()=>{if("?EJS_KEYS!"!==n){let e=await this.get("?EJS_KEYS!");var t;e=e||[],i?e.includes(n)||e.push(n):-1!==(t=e.indexOf(n))&&e.splice(t,1),this.put("?EJS_KEYS!",e)}})()}get(o){return new Promise((n,e)=>{if(!window.indexedDB)return n();let i=indexedDB.open(this.dbName,1);i.onerror=()=>n(),i.onsuccess=()=>{let t=i.result.transaction([this.storeName],"readwrite").objectStore(this.storeName).get(o);t.onsuccess=e=>{n(t.result)},t.onerror=()=>n()},i.onupgradeneeded=()=>{var e=i.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)}})}put(i,o){return new Promise((t,e)=>{if(!window.indexedDB)return t();let n=indexedDB.open(this.dbName,1);n.onerror=()=>{},n.onsuccess=()=>{var e=n.result.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(o,i);e.onerror=()=>t(),e.onsuccess=()=>{this.addFileToDB(i,!0),t()}},n.onupgradeneeded=()=>{var e=n.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)}})}remove(i){return new Promise((t,e)=>{if(!window.indexedDB)return t();let n=indexedDB.open(this.dbName,1);n.onerror=()=>{},n.onsuccess=()=>{var e=n.result.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(i);this.addFileToDB(i,!1),e.onsuccess=()=>t(),e.onerror=()=>{}},n.onupgradeneeded=()=>{var e=n.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)}})}getSizes(){return new Promise(async(e,t)=>{window.indexedDB||e({});var n=await this.get("?EJS_KEYS!");if(!n)return e({});var i={};for(let e=0;e<n.length;e++){var o=await this.get(n[e]);o&&o.data&&"number"==typeof o.data.byteLength&&(i[n[e]]=o.data.byteLength)}e(i)})}}window.EJS_STORAGE=EJS_STORAGE;class GamepadHandler{gamepads;timeout;listeners;constructor(){this.gamepads=[],this.listeners={},this.timeout=null,this.loop()}terminate(){window.clearTimeout(this.timeout)}getGamepads(){return navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[]}loop(){this.updateGamepadState(),this.timeout=setTimeout(this.loop.bind(this),10)}updateGamepadState(){let i=this.getGamepads();if(i){if(!Array.isArray(i)&&i.length){var t=[];for(let e=0;e<i.length;e++)t.push(i[e]);i=t}else if(!Array.isArray(i))return;i.forEach((a,e)=>{if(a){let t=!1;this.gamepads.forEach((o,e)=>{if(o.index===a.index){const s={axes:[],buttons:{},index:o.index};t=!0,o.axes.forEach((e,t)=>{if(a.axes[t]!==e){const e=["LEFT_STICK_X","LEFT_STICK_Y","RIGHT_STICK_X","RIGHT_STICK_Y"][t];if(!e)return;this.dispatchEvent("axischanged",{axis:e,value:a.axes[t],index:a.index,gamepadIndex:a.index})}s.axes[t]=e}),a.buttons.forEach((e,t)=>{let n=1===o.buttons[t],i=("object"==typeof o.buttons[t]&&(n=o.buttons[t].pressed),1===e);"object"==typeof e&&(i=e.pressed),s.buttons[t]={pressed:i},n!==i&&(i?this.dispatchEvent("buttondown",{index:t,gamepadIndex:a.index}):this.dispatchEvent("buttonup",{index:t,gamepadIndex:a.index}))}),this.gamepads[e]=s}}),t||(this.gamepads.push(i[e]),this.dispatchEvent("connected",{gamepadIndex:a.index}))}});for(let n=0;n<this.gamepads.length;n++)if(this.gamepads[n]){let t=!1;for(let e=0;e<i.length;e++)if(i[e]&&this.gamepads[n].index===i[e].index){t=!0;break}t||(this.dispatchEvent("disconnected",{gamepadIndex:this.gamepads[n].index}),this.gamepads.splice(n,1),n--)}}}dispatchEvent(e,t){"function"==typeof this.listeners[e]&&((t=t||{}).type=e,this.listeners[e](t))}on(e,t){this.listeners[e.toLowerCase()]=t}}window.GamepadHandler=GamepadHandler;class EJS_GameManager{constructor(e,t){this.EJS=t,this.Module=e,this.FS=this.Module.FS,this.functions={restart:this.Module.cwrap("system_restart","",[]),getStateInfo:this.Module.cwrap("get_state_info","string",[]),saveStateInfo:this.Module.cwrap("save_state_info","null",[]),loadState:this.Module.cwrap("load_state","number",["string","number"]),screenshot:this.Module.cwrap("cmd_take_screenshot","",[]),simulateInput:this.Module.cwrap("simulate_input","null",["number","number","number"]),toggleMainLoop:this.Module.cwrap("toggleMainLoop","null",["number"]),getCoreOptions:this.Module.cwrap("get_core_options","string",[]),setVariable:this.Module.cwrap("set_variable","null",["string","string"]),setCheat:this.Module.cwrap("set_cheat","null",["number","number","string"]),resetCheat:this.Module.cwrap("reset_cheat","null",[]),toggleShader:this.Module.cwrap("shader_enable","null",["number"]),getDiskCount:this.Module.cwrap("get_disk_count","number",[]),getCurrentDisk:this.Module.cwrap("get_current_disk","number",[]),setCurrentDisk:this.Module.cwrap("set_current_disk","null",["number"]),getSaveFilePath:this.Module.cwrap("save_file_path","string",[]),saveSaveFiles:this.Module.cwrap("cmd_savefiles","",[]),supportsStates:this.Module.cwrap("supports_states","number",[]),loadSaveFiles:this.Module.cwrap("refresh_save_files","null",[]),setVolume:this.Module.cwrap("set_volume","null",["number"])},this.mkdir("/home"),this.mkdir("/home/web_user"),this.mkdir("/home/web_user/retroarch"),this.mkdir("/home/web_user/retroarch/userdata"),this.mkdir("/home/web_user/retroarch/userdata/config"),this.mkdir("/home/web_user/retroarch/userdata/config/Beetle PSX HW"),this.FS.writeFile("/home/web_user/retroarch/userdata/config/Beetle PSX HW/Beetle PSX HW.opt",'beetle_psx_hw_renderer = "software"\n'),this.mkdir("/data"),this.mkdir("/data/saves"),this.FS.writeFile("/home/web_user/retroarch/userdata/retroarch.cfg",this.getRetroArchCfg()),this.FS.mount(IDBFS,{},"/data/saves"),this.FS.syncfs(!0,()=>{}),this.initShaders(),this.EJS.addEventListener(window,"beforeunload",()=>{this.saveSaveFiles(),this.FS.syncfs(()=>{})})}mkdir(e){try{this.FS.mkdir(e)}catch(e){}}getRetroArchCfg(){return'autosave_interval = 60\nscreenshot_directory = "/"\nblock_sram_overwrite = false\nvideo_gpu_screenshot = false\naudio_latency = 64\nvideo_top_portrait_viewport = true\nvideo_vsync = true\nvideo_smooth = false\nsavefile_directory = "/data/saves"\n'}initShaders(){if(window.EJS_SHADERS){this.mkdir("/shader");for(const e in window.EJS_SHADERS)this.FS.writeFile("/shader/"+e,window.EJS_SHADERS[e])}}restart(){this.functions.restart()}getState(){return new Promise(async(e,t)=>{var n=(await this.getStateInfo()).split("|");let i;var o=n[0]>>0;if(0<o){i=new Uint8Array(o);var s=n[1]>>0;for(let e=0;e<o;e++)i[e]=this.Module.getValue(s+e)}e(i)})}getStateInfo(){return this.functions.saveStateInfo(),new Promise((e,t)=>{let n,i=setInterval(()=>{(n=this.functions.getStateInfo())&&(clearInterval(i),e(n))},50)})}loadState(e){try{this.FS.unlink("game.state")}catch(e){}this.FS.writeFile("/game.state",e),this.functions.loadState("game.state",0),setTimeout(()=>{try{this.FS.unlink("game.state")}catch(e){}},5e3)}screenshot(){return this.functions.screenshot(),this.FS.readFile("screenshot.png")}quickSave(n){n=n||1,(async()=>{var e=n+"-quick.state";try{this.FS.unlink(e)}catch(e){}var t=await this.getState();this.FS.writeFile("/"+e,t)})()}quickLoad(t){t=t||1,(async()=>{var e=t+"-quick.state";this.functions.loadState(e,0)})()}simulateInput(e,t,n){var i;if(this.EJS.isNetplay)this.EJS.netplay.simulateInput(e,t,n);else if([24,25,26].includes(t)){if(24===t&&1===n&&(i=this.EJS.settings["save-state-slot"]||"1",this.quickSave(i),this.EJS.displayMessage(this.EJS.localization("SAVED STATE TO SLOT")+" "+i)),25===t&&1===n&&(i=this.EJS.settings["save-state-slot"]||"1",this.quickLoad(i),this.EJS.displayMessage(this.EJS.localization("LOADED STATE FROM SLOT")+" "+i)),26===t&&1===n){let t;try{t=parseFloat(this.EJS.settings["save-state-slot"]||"1")+1}catch(e){t=1}9<t&&(t=1),this.EJS.displayMessage(this.EJS.localization("SET SAVE STATE SLOT TO")+" "+t),this.EJS.changeSettingOption("save-state-slot",t.toString())}}else this.functions.simulateInput(e,t,n)}createCueFile(n){try{1<n.length&&(n=(n=n.filter(e=>["toc","ccd","exe","pbp","chd","img","bin","iso"].includes(e.split(".").pop().toLowerCase()))).sort((e,t)=>{if(isNaN(e.charAt())||isNaN(t.charAt()))throw new Error("Incorrect file name format");return parseInt(e.charAt())>parseInt(t.charAt())?1:-1}))}catch(e){if(console.log(e,n),1<n.length)return console.warn("Could not auto-create cue file(s)."),null}for(let e=0;e<n.length;e++)if("ccd"===n[e].split(".").pop().toLowerCase())return console.warn("Did not auto-create cue file(s). Found a ccd."),null;if(0===n.length)return console.warn("Could not auto-create cue file(s)."),null;console.log(n);let i=n[0].split("/").pop();i.includes(".")&&(i=i.substring(0,i.length-i.split(".").pop().length-1),console.log(i));for(let e=0;e<n.length;e++){var t=' FILE "'+n[e]+'" BINARY\n TRACK 01 MODE1/2352\n INDEX 01 00:00:00';FS.writeFile("/"+i+"-"+e+".cue",t)}if(1<n.length){let t="";for(let e=0;e<n.length;e++)t+="/"+i+"-"+e+".cue\n";FS.writeFile("/"+i+".m3u",t)}return 1===n.length?i+"-0.cue":i+".m3u"}toggleMainLoop(e){this.functions.toggleMainLoop(e)}getCoreOptions(){return this.functions.getCoreOptions()}setVariable(e,t){this.functions.setVariable(e,t)}setCheat(e,t,n){this.functions.setCheat(e,t,n)}resetCheat(){this.functions.resetCheat()}toggleShader(e){this.functions.toggleShader(e)}getDiskCount(){return this.functions.getDiskCount()}getCurrentDisk(){return this.functions.getCurrentDisk()}setCurrentDisk(e){this.functions.setCurrentDisk(e)}getSaveFilePath(){return this.functions.getSaveFilePath()}saveSaveFiles(){this.functions.saveSaveFiles(),this.FS.syncfs(!1,()=>{})}supportsStates(){return!!this.functions.supportsStates()}getSaveFile(){return this.saveSaveFiles(),FS.analyzePath(this.getSaveFilePath()).exists?FS.readFile(this.getSaveFilePath()):null}loadSaveFiles(){this.functions.loadSaveFiles()}}window.EJS_GameManager=EJS_GameManager,function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).io=t()}(this,function(){"use strict";function l(e){return(l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function z(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function e(e,t,n){return t&&z(e.prototype,t),n&&z(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function r(){return(r=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n,i=arguments[t];for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e}).apply(this,arguments)}function t(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&a(e,t)}function s(e){return(s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function a(e,t){return(a=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function G(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function F(e,t,n){return(F=G()?Reflect.construct.bind():function(e,t,n){var i=[null],t=(i.push.apply(i,t),new(Function.bind.apply(e,i)));return n&&a(t,n.prototype),t}).apply(null,arguments)}function U(e){var n="function"==typeof Map?new Map:void 0;return function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return F(e,arguments,s(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),a(t,e)}(e)}function c(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function n(n){var i=G();return function(){var e,t=s(n),t=(e=i?(e=s(this).constructor,Reflect.construct(t,arguments,e)):t.apply(this,arguments),this);if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return c(t)}}function i(){return(i="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var i=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=s(e)););return e}(e,t);if(i)return(i=Object.getOwnPropertyDescriptor(i,t)).get?i.get.call(arguments.length<3?e:n):i.value}).apply(this,arguments)}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}function j(e,t){var n,i,o,s,a="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(a)return o=!(i=!0),{s:function(){a=a.call(e)},n:function(){var e=a.next();return i=e.done,e},e:function(e){o=!0,n=e},f:function(){try{i||null==a.return||a.return()}finally{if(o)throw n}}};if(Array.isArray(e)||(a=function(e){var t;if(e)return"string"==typeof e?D(e,void 0):"Map"===(t="Object"===(t=Object.prototype.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:t)||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?D(e,void 0):void 0}(e))||t&&e&&"number"==typeof e.length)return a&&(e=a),s=0,{s:t=function(){},n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var h=Object.create(null),d=(h.open="0",h.close="1",h.ping="2",h.pong="3",h.message="4",h.upgrade="5",h.noop="6",Object.create(null));Object.keys(h).forEach(function(e){d[h[e]]=e});function B(e){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer}function V(e,t,n){var i=e.type,e=e.data;q&&e instanceof Blob?t?n(e):H(e,n):W&&(e instanceof ArrayBuffer||B(e))?t?n(e):H(new Blob([e]),n):n(h[i]+(e||""))}function H(e,t){var n=new FileReader;return n.onload=function(){var e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)}var Y,X={type:"error",data:"parser error"},q="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),W="function"==typeof ArrayBuffer;function J(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}for(var K="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u="undefined"==typeof Uint8Array?[]:new Uint8Array(256),p=0;p<K.length;p++)u[K.charCodeAt(p)]=p;function Q(e,t){var n;return"string"!=typeof e?{type:"message",data:ee(e,t)}:"b"===(n=e.charAt(0))?{type:"message",data:function(e,t){if($){var n=function(e){var t,n,i,o,s,a=.75*e.length,r=e.length,l=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var c=new ArrayBuffer(a),h=new Uint8Array(c);for(t=0;t<r;t+=4)n=u[e.charCodeAt(t)],i=u[e.charCodeAt(t+1)],o=u[e.charCodeAt(t+2)],s=u[e.charCodeAt(t+3)],h[l++]=n<<2|i>>4,h[l++]=(15&i)<<4|o>>2,h[l++]=(3&o)<<6|63&s;return c}(e);return ee(n,t)}return{base64:!0,data:e}}(e.substring(1),t)}:d[n]?1<e.length?{type:d[n],data:e.substring(1)}:{type:d[n]}:X}var Z,$="function"==typeof ArrayBuffer,ee=function(e,t){return"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer},te=String.fromCharCode(30);function f(e){if(e){var t,n=e;for(t in f.prototype)n[t]=f.prototype[t];return n}}f.prototype.on=f.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},f.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},f.prototype.off=f.prototype.removeListener=f.prototype.removeAllListeners=f.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)this._callbacks={};else{var n,i=this._callbacks["$"+e];if(i)if(1==arguments.length)delete this._callbacks["$"+e];else{for(var o=0;o<i.length;o++)if((n=i[o])===t||n.fn===t){i.splice(o,1);break}0===i.length&&delete this._callbacks["$"+e]}}return this},f.prototype.emitReserved=f.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(n)for(var i=0,o=(n=n.slice(0)).length;i<o;++i)n[i].apply(this,t);return this},f.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},f.prototype.hasListeners=function(e){return!!this.listeners(e).length};var m="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function ne(n){for(var e=arguments.length,t=new Array(1<e?e-1:0),i=1;i<e;i++)t[i-1]=arguments[i];return t.reduce(function(e,t){return n.hasOwnProperty(t)&&(e[t]=n[t]),e},{})}var ie=m.setTimeout,oe=m.clearTimeout;function y(e,t){t.useNativeTimers?(e.setTimeoutFn=ie.bind(m),e.clearTimeoutFn=oe.bind(m)):(e.setTimeoutFn=m.setTimeout.bind(m),e.clearTimeoutFn=m.clearTimeout.bind(m))}t(T,U(Error)),re=n(T);var se,ae,re,le=e(T),g=(t(_,f),ae=n(_),e(_,[{key:"onError",value:function(e,t,n){return i(s(_.prototype),"emitReserved",this).call(this,"error",new le(e,t,n)),this}},{key:"open",value:function(){return this.readyState="opening",this.doOpen(),this}},{key:"close",value:function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}},{key:"send",value:function(e){"open"===this.readyState&&this.write(e)}},{key:"onOpen",value:function(){this.readyState="open",this.writable=!0,i(s(_.prototype),"emitReserved",this).call(this,"open")}},{key:"onData",value:function(e){e=Q(e,this.socket.binaryType);this.onPacket(e)}},{key:"onPacket",value:function(e){i(s(_.prototype),"emitReserved",this).call(this,"packet",e)}},{key:"onClose",value:function(e){this.readyState="closed",i(s(_.prototype),"emitReserved",this).call(this,"close",e)}},{key:"pause",value:function(e){}},{key:"createUri",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}},{key:"_hostname",value:function(){var e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}},{key:"_port",value:function(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}},{key:"_query",value:function(e){e=function(e){var t,n="";for(t in e)e.hasOwnProperty(t)&&(n.length&&(n+="&"),n+=encodeURIComponent(t)+"="+encodeURIComponent(e[t]));return n}(e);return e.length?"?"+e:""}}]),_),ce="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),he=0,v=0;function _(e){var t;return o(this,_),(t=ae.call(this)).writable=!1,y(c(t),e),t.opts=e,t.query=e.query,t.socket=e.socket,t}function T(e,t,n){return o(this,T),(e=re.call(this,e)).description=t,e.context=n,e.type="TransportError",e}function de(e){for(var t="";t=ce[e%64]+t,0<(e=Math.floor(e/64)););return t}function ue(){var e=de(+new Date);return e!==se?(he=0,se=e):e+"."+de(he++)}for(;v<64;v++)ce[v],v;var b=!1;try{b="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(l){}var pe=b;function fe(e){var t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||pe))return new XMLHttpRequest}catch(e){}if(!t)try{return new m[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(e){}}function me(){}var ye,ge,ve=null!=new fe({xdomain:!1}).responseType,b=(t(E,g),ge=n(E),e(E,[{key:"name",get:function(){return"polling"}},{key:"doOpen",value:function(){this.poll()}},{key:"pause",value:function(e){function t(){i.readyState="paused",e()}var n,i=this;this.readyState="pausing";this.polling||!this.writable?(n=0,this.polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))):t()}},{key:"poll",value:function(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}},{key:"onData",value:function(e){var t=this;(function(e,t){for(var n=e.split(te),i=[],o=0;o<n.length;o++){var s=Q(n[o],t);if(i.push(s),"error"===s.type)break}return i})(e,this.socket.binaryType).forEach(function(e){if("opening"===t.readyState&&"open"===e.type&&t.onOpen(),"close"===e.type)return t.onClose({description:"transport closed by the server"}),!1;t.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState)&&this.poll()}},{key:"doClose",value:function(){function e(){t.write([{type:"close"}])}var t=this;"open"===this.readyState?e():this.once("open",e)}},{key:"write",value:function(e){var n,i,o,s=this;this.writable=!1,n=(e=e).length,i=new Array(n),o=0,e.forEach(function(e,t){V(e,!1,function(e){i[t]=e,++o===n&&(e=i.join(te),s.doWrite(e,function(){s.writable=!0,s.emitReserved("drain")}))})})}},{key:"uri",value:function(){var e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ue()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}},{key:"request",value:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return r(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new w(this.uri(),e)}},{key:"doWrite",value:function(e,t){var n=this,e=this.request({method:"POST",data:e});e.on("success",t),e.on("error",function(e,t){n.onError("xhr post error",e,t)})}},{key:"doPoll",value:function(){var n=this,e=this.request();e.on("data",this.onData.bind(this)),e.on("error",function(e,t){n.onError("xhr poll error",e,t)}),this.pollXhr=e}}]),E),w=(t(x,f),ye=n(x),e(x,[{key:"create",value:function(){var e,t=this,n=ne(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref"),i=(n.xdomain=!!this.opts.xd,this.xhr=new fe(n));try{i.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders)for(var o in i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0),this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&i.setRequestHeader(o,this.opts.extraHeaders[o])}catch(e){}if("POST"===this.method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{i.setRequestHeader("Accept","*/*")}catch(e){}null!=(e=this.opts.cookieJar)&&e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(i.timeout=this.opts.requestTimeout),i.onreadystatechange=function(){var e;3===i.readyState&&null!=(e=t.opts.cookieJar)&&e.parseCookies(i),4===i.readyState&&(200===i.status||1223===i.status?t.onLoad():t.setTimeoutFn(function(){t.onError("number"==typeof i.status?i.status:0)},0))},i.send(this.data)}catch(e){return void this.setTimeoutFn(function(){t.onError(e)},0)}"undefined"!=typeof document&&(this.index=x.requestsCount++,x.requests[this.index]=this)}},{key:"onError",value:function(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}},{key:"cleanup",value:function(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=me,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete x.requests[this.index],this.xhr=null}}},{key:"onLoad",value:function(){var e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}},{key:"abort",value:function(){this.cleanup()}}]),x);function x(e,t){var n;return o(this,x),y(c(n=ye.call(this)),t),n.opts=t,n.method=t.method||"GET",n.uri=e,n.data=void 0!==t.data?t.data:null,n.create(),n}function E(e){o(this,E),(t=ge.call(this,e)).polling=!1,"undefined"!=typeof location&&(n=(n=location.port)||("https:"===location.protocol?"443":"80"),t.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port);var t,n=e&&e.forceBase64;return t.supportsBinary=ve&&!n,t.opts.withCredentials&&(t.cookieJar=void 0),t}function _e(){for(var e in w.requests)w.requests.hasOwnProperty(e)&&w.requests[e].abort()}w.requestsCount=0,w.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",_e):"function"==typeof addEventListener&&addEventListener("onpagehide"in m?"pagehide":"unload",_e,!1));var Te,be="function"==typeof Promise&&"function"==typeof Promise.resolve?function(e){return Promise.resolve().then(e)}:function(e,t){return t(e,0)},we=m.WebSocket||m.MozWebSocket,xe="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),C=(t(S,g),Te=n(S),e(S,[{key:"name",get:function(){return"websocket"}},{key:"doOpen",value:function(){if(this.check()){var e=this.uri(),t=this.opts.protocols,n=xe?{}:ne(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=xe?new we(e,t,n):t?new we(e,t):new we(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}}},{key:"addEventListeners",value:function(){var t=this;this.ws.onopen=function(){t.opts.autoUnref&&t.ws._socket.unref(),t.onOpen()},this.ws.onclose=function(e){return t.onClose({description:"websocket connection closed",context:e})},this.ws.onmessage=function(e){return t.onData(e.data)},this.ws.onerror=function(e){return t.onError("websocket error",e)}}},{key:"write",value:function(i){var o=this;this.writable=!1;for(var e=0;e<i.length;e++)!function(e){var t=i[e],n=e===i.length-1;V(t,o.supportsBinary,function(e){try{o.ws.send(e)}catch(e){}n&&be(function(){o.writable=!0,o.emitReserved("drain")},o.setTimeoutFn)})}(e)}},{key:"doClose",value:function(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}},{key:"uri",value:function(){var e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ue()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},{key:"check",value:function(){return!!we}}]),S);function S(e){var t;return o(this,S),(t=Te.call(this,e)).supportsBinary=!e.forceBase64,t}t(P,g),Ee=n(P),e(P,[{key:"name",get:function(){return"webtransport"}},{key:"doOpen",value:function(){var o=this;"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(function(){return o.onClose()}),this.transport.ready.then(function(){o.transport.createBidirectionalStream().then(function(e){var i,t=e.readable.getReader(),e=(o.writer=e.writable.getWriter(),!function n(){t.read().then(function(e){var t=e.done,e=e.value;t||(i=!i&&1===e.byteLength&&54===e[0]||(o.onPacket(function(e,t){Z=Z||new TextDecoder;t=t||e[0]<48||54<e[0];return Q(t?e:Z.decode(e),"arraybuffer")}(e,i)),!1),n())})}(),o.query.sid?'0{"sid":"'.concat(o.query.sid,'"}'):"0");o.writer.write((new TextEncoder).encode(e)).then(function(){return o.onOpen()})})}))}},{key:"write",value:function(o){var s=this;this.writable=!1;for(var e=0;e<o.length;e++)!function(e){var t,n=o[e],i=e===o.length-1;e=n,t=function(e){"message"===n.type&&"string"!=typeof n.data&&48<=e[0]&&e[0]<=54&&s.writer.write(Uint8Array.of(54)),s.writer.write(e).then(function(){i&&be(function(){s.writable=!0,s.emitReserved("drain")},s.setTimeoutFn)})},q&&e.data instanceof Blob?e.data.arrayBuffer().then(J).then(t):W&&(e.data instanceof ArrayBuffer||B(e.data))?t(J(e.data)):V(e,!1,function(e){Y=Y||new TextEncoder,t(Y.encode(e))})}(e)}},{key:"doClose",value:function(){var e;null!=(e=this.transport)&&e.close()}}]);var Ee,Ce={websocket:C,webtransport:P,polling:b},Se=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Pe=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function P(){return o(this,P),Ee.apply(this,arguments)}function Ae(e){var t=e,n=e.indexOf("["),i=e.indexOf("]");-1!=n&&-1!=i&&(e=e.substring(0,n)+e.substring(n,i).replace(/:/g,";")+e.substring(i,e.length));for(var o,s=Se.exec(e||""),a={},r=14;r--;)a[Pe[r]]=s[r]||"";return-1!=n&&-1!=i&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=(n=(e=a.path).replace(/\/{2,9}/g,"/").split("/"),"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1),"/"==e.slice(-1)&&n.splice(n.length-1,1),n),a.queryKey=(o={},a.query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(o[t]=n)}),o),a}t(A,f),Oe=n(A),e(A,[{key:"createTransport",value:function(e){var t=r({},this.opts.query),t=(t.EIO=4,t.transport=e,this.id&&(t.sid=this.id),r({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port}));return new Ce[e](t)}},{key:"open",value:function(){var e,t=this;if(this.opts.rememberUpgrade&&A.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(function(){t.emitReserved("error","No transports available")},0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}},{key:"setTransport",value:function(e){var t=this;this.transport&&this.transport.removeAllListeners(),(this.transport=e).on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",function(e){return t.onClose("transport close",e)})}},{key:"probe",value:function(e){var t=this,n=this.createTransport(e),i=!1,o=(A.priorWebsocketSuccess=!1,function(){i||(n.send([{type:"ping",data:"probe"}]),n.once("packet",function(e){i||("pong"===e.type&&"probe"===e.data?(t.upgrading=!0,t.emitReserved("upgrading",n),n&&(A.priorWebsocketSuccess="websocket"===n.name,t.transport.pause(function(){i||"closed"!==t.readyState&&(h(),t.setTransport(n),n.send([{type:"upgrade"}]),t.emitReserved("upgrade",n),n=null,t.upgrading=!1,t.flush())}))):((e=new Error("probe error")).transport=n.name,t.emitReserved("upgradeError",e)))}))});function s(){i||(i=!0,h(),n.close(),n=null)}var a=function(e){e=new Error("probe error: "+e);e.transport=n.name,s(),t.emitReserved("upgradeError",e)};function r(){a("transport closed")}function l(){a("socket closed")}function c(e){n&&e.name!==n.name&&s()}var h=function(){n.removeListener("open",o),n.removeListener("error",a),n.removeListener("close",r),t.off("close",l),t.off("upgrading",c)};n.once("open",o),n.once("error",a),n.once("close",r),this.once("close",l),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(function(){i||n.open()},200):n.open()}},{key:"onOpen",value:function(){if(this.readyState="open",A.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(var e=0,t=this.upgrades.length;e<t;e++)this.probe(this.upgrades[e])}},{key:"onPacket",value:function(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":var t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}},{key:"onHandshake",value:function(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}},{key:"resetPingTimeout",value:function(){var e=this;this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(function(){e.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}},{key:"onDrain",value:function(){this.writeBuffer.splice(0,this.prevBufferLen),(this.prevBufferLen=0)===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}},{key:"flush",value:function(){var e;"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(e=this.getWritablePackets(),this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush"))}},{key:"getWritablePackets",value:function(){if(this.maxPayload&&"polling"===this.transport.name&&1<this.writeBuffer.length)for(var e=1,t=0;t<this.writeBuffer.length;t++){var n=this.writeBuffer[t].data;if(n&&(e+="string"==typeof(n=n)?function(e){for(var t,n=0,i=0,o=e.length;i<o;i++)(t=e.charCodeAt(i))<128?n+=1:t<2048?n+=2:t<55296||57344<=t?n+=3:(i++,n+=4);return n}(n):Math.ceil(1.33*(n.byteLength||n.size))),0<t&&e>this.maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}},{key:"write",value:function(e,t,n){return this.sendPacket("message",e,t,n),this}},{key:"send",value:function(e,t,n){return this.sendPacket("message",e,t,n),this}},{key:"sendPacket",value:function(e,t,n,i){"function"==typeof t&&(i=t,t=void 0),"function"==typeof n&&(i=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState&&((n=n||{}).compress=!1!==n.compress,this.emitReserved("packetCreate",e={type:e,data:t,options:n}),this.writeBuffer.push(e),i&&this.once("flush",i),this.flush())}},{key:"close",value:function(){function e(){n.off("upgrade",e),n.off("upgradeError",e),i()}function t(){n.once("upgrade",e),n.once("upgradeError",e)}var n=this,i=function(){n.onClose("forced close"),n.transport.close()};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",function(){(n.upgrading?t:i)()}):(this.upgrading?t:i)()),this}},{key:"onError",value:function(e){A.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}},{key:"onClose",value:function(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}},{key:"filterUpgrades",value:function(e){for(var t=[],n=0,i=e.length;n<i;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}]);var Oe,Me=A;function A(e){var t,n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return o(this,A),(t=Oe.call(this)).writeBuffer=[],e&&"object"===l(e)&&(n=e,e=null),e?(e=Ae(e),n.hostname=e.host,n.secure="https"===e.protocol||"wss"===e.protocol,n.port=e.port,e.query&&(n.query=e.query)):n.host&&(n.hostname=Ae(n.host).host),y(c(t),n),t.secure=null!=n.secure?n.secure:"undefined"!=typeof location&&"https:"===location.protocol,n.hostname&&!n.port&&(n.port=t.secure?"443":"80"),t.hostname=n.hostname||("undefined"!=typeof location?location.hostname:"localhost"),t.port=n.port||("undefined"!=typeof location&&location.port?location.port:t.secure?"443":"80"),t.transports=n.transports||["polling","websocket","webtransport"],t.writeBuffer=[],t.prevBufferLen=0,t.opts=r({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},n),t.opts.path=t.opts.path.replace(/\/$/,"")+(t.opts.addTrailingSlash?"/":""),"string"==typeof t.opts.query&&(t.opts.query=function(e){for(var t={},n=e.split("&"),i=0,o=n.length;i<o;i++){var s=n[i].split("=");t[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return t}(t.opts.query)),t.id=null,t.upgrades=null,t.pingInterval=null,t.pingTimeout=null,t.pingTimeoutTimer=null,"function"==typeof addEventListener&&(t.opts.closeOnBeforeunload&&(t.beforeunloadEventListener=function(){t.transport&&(t.transport.removeAllListeners(),t.transport.close())},addEventListener("beforeunload",t.beforeunloadEventListener,!1)),"localhost"!==t.hostname)&&(t.offlineEventListener=function(){t.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",t.offlineEventListener,!1)),t.open(),t}Me.protocol=4,Me.protocol;var Ie="function"==typeof ArrayBuffer,g=Object.prototype.toString,ke="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===g.call(Blob),Re="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===g.call(File);function Le(e){return Ie&&(e instanceof ArrayBuffer||(t=e,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer))||ke&&e instanceof Blob||Re&&e instanceof File;var t}function Ne(e){var t=[],n=e.data;return e.data=function e(t,n){if(!t)return t;{var i;if(Le(t))return i={_placeholder:!0,num:n.length},n.push(t),i}if(Array.isArray(t)){for(var o=new Array(t.length),s=0;s<t.length;s++)o[s]=e(t[s],n);return o}if("object"===l(t)&&!(t instanceof Date)){var a,r={};for(a in t)Object.prototype.hasOwnProperty.call(t,a)&&(r[a]=e(t[a],n));return r}return t}(n,t),e.attachments=t.length,{packet:e,buffers:t}}function ze(e,t){return e.data=function e(t,n){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&0<=t.num&&t.num<n.length)return n[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(var i=0;i<t.length;i++)t[i]=e(t[i],n);else if("object"===l(t))for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(t[o]=e(t[o],n));return t}(e.data,t),delete e.attachments,e}var O,Ge=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],b=((C=O=O||{})[C.CONNECT=0]="CONNECT",C[C.DISCONNECT=1]="DISCONNECT",C[C.EVENT=2]="EVENT",C[C.ACK=3]="ACK",C[C.CONNECT_ERROR=4]="CONNECT_ERROR",C[C.BINARY_EVENT=5]="BINARY_EVENT",C[C.BINARY_ACK=6]="BINARY_ACK",e(Fe,[{key:"encode",value:function(e){return e.type!==O.EVENT&&e.type!==O.ACK||!function e(t){if(t&&"object"===l(t))if(Array.isArray(t)){for(var n=0,i=t.length;n<i;n++)if(e(t[n]))return!0}else{if(Le(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return e(t.toJSON(),!0);for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o)&&e(t[o]))return!0}return!1}(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===O.EVENT?O.BINARY_EVENT:O.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}},{key:"encodeAsString",value:function(e){var t=""+e.type;return e.type!==O.BINARY_EVENT&&e.type!==O.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}},{key:"encodeAsBinary",value:function(e){var e=Ne(e),t=this.encodeAsString(e.packet),e=e.buffers;return e.unshift(t),e}}]),Fe);function Fe(e){o(this,Fe),this.replacer=e}function Ue(e){return"[object Object]"===Object.prototype.toString.call(e)}t(M,f),De=n(M),e(M,[{key:"add",value:function(e){var t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");var n=(t=this.decodeString(e)).type===O.BINARY_EVENT;(n||t.type===O.BINARY_ACK)&&(t.type=n?O.EVENT:O.ACK,this.reconstructor=new je(t),0!==t.attachments)||i(s(M.prototype),"emitReserved",this).call(this,"decoded",t)}else{if(!Le(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(t=this.reconstructor.takeBinaryData(e))&&(this.reconstructor=null,i(s(M.prototype),"emitReserved",this).call(this,"decoded",t))}}},{key:"decodeString",value:function(e){var t=0,n={type:Number(e.charAt(0))};if(void 0===O[n.type])throw new Error("unknown packet type "+n.type);if(n.type===O.BINARY_EVENT||n.type===O.BINARY_ACK){for(var i=t+1;"-"!==e.charAt(++t)&&t!=e.length;);i=e.substring(i,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===e.charAt(t+1)){for(i=t+1;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(i,t)}else n.nsp="/";i=e.charAt(t+1);if(""!==i&&Number(i)==i){for(i=t+1;++t;){var o=e.charAt(t);if(null==o||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){i=this.tryParse(e.substr(t));if(!M.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}},{key:"tryParse",value:function(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}},{key:"destroy",value:function(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}],[{key:"isPayloadValid",value:function(e,t){switch(e){case O.CONNECT:return Ue(t);case O.DISCONNECT:return void 0===t;case O.CONNECT_ERROR:return"string"==typeof t||Ue(t);case O.EVENT:case O.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ge.indexOf(t[0]));case O.ACK:case O.BINARY_ACK:return Array.isArray(t)}}}]);var De,g=M,je=(e(Ve,[{key:"takeBinaryData",value:function(e){return this.buffers.push(e),this.buffers.length===this.reconPack.attachments?(e=ze(this.reconPack,this.buffers),this.finishedReconstruction(),e):null}},{key:"finishedReconstruction",value:function(){this.reconPack=null,this.buffers=[]}}]),Ve),Be=Object.freeze({__proto__:null,protocol:5,get PacketType(){return O},Encoder:b,Decoder:g});function Ve(e){o(this,Ve),this.packet=e,this.buffers=[],this.reconPack=e}function M(e){var t;return o(this,M),(t=De.call(this)).reviver=e,t}function I(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var He,Ye=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Xe=(t(k,f),He=n(k),e(k,[{key:"disconnected",get:function(){return!this.connected}},{key:"subEvents",value:function(){var e;this.subs||(e=this.io,this.subs=[I(e,"open",this.onopen.bind(this)),I(e,"packet",this.onpacket.bind(this)),I(e,"error",this.onerror.bind(this)),I(e,"close",this.onclose.bind(this))])}},{key:"active",get:function(){return!!this.subs}},{key:"connect",value:function(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}},{key:"open",value:function(){return this.connect()}},{key:"send",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.unshift("message"),this.emit.apply(this,t),this}},{key:"emit",value:function(e){if(Ye.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');for(var t,n,i=arguments.length,o=new Array(1<i?i-1:0),s=1;s<i;s++)o[s-1]=arguments[s];return(o.unshift(e),!this._opts.retries||this.flags.fromQueue||this.flags.volatile)?(n=((e={type:O.EVENT,data:o,options:{}}).options.compress=!1!==this.flags.compress,"function"==typeof o[o.length-1]&&(t=this.ids++,n=o.pop(),this._registerAckCallback(t,n),e.id=t),this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable),(!this.flags.volatile||n&&this.connected)&&(this.connected?(this.notifyOutgoingListeners(e),this.packet(e)):this.sendBuffer.push(e)),this.flags={}):this._addToQueue(o),this}},{key:"_registerAckCallback",value:function(t,i){var o,s=this,e=null!=(e=this.flags.timeout)?e:this._opts.ackTimeout;void 0!==e?(o=this.io.setTimeoutFn(function(){delete s.acks[t];for(var e=0;e<s.sendBuffer.length;e++)s.sendBuffer[e].id===t&&s.sendBuffer.splice(e,1);i.call(s,new Error("operation has timed out"))},e),this.acks[t]=function(){s.io.clearTimeoutFn(o);for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];i.apply(s,[null].concat(t))}):this.acks[t]=i}},{key:"emitWithAck",value:function(e){for(var t=this,n=arguments.length,o=new Array(1<n?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];var s=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(function(n,i){o.push(function(e,t){return s?e?i(e):n(t):n(e)}),t.emit.apply(t,[e].concat(o))})}},{key:"_addToQueue",value:function(e){var o,s=this,a=("function"==typeof e[e.length-1]&&(o=e.pop()),{id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:r({fromQueue:!0},this.flags)});e.push(function(e){if(a===s._queue[0]){if(null!==e)a.tryCount>s._opts.retries&&(s._queue.shift(),o)&&o(e);else if(s._queue.shift(),o){for(var t=arguments.length,n=new Array(1<t?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];o.apply(void 0,[null].concat(n))}return a.pending=!1,s._drainQueue()}}),this._queue.push(a),this._drainQueue()}},{key:"_drainQueue",value:function(){var e;this.connected&&0!==this._queue.length&&(!(e=this._queue[0]).pending||0<arguments.length&&void 0!==arguments[0]&&arguments[0])&&(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}},{key:"packet",value:function(e){e.nsp=this.nsp,this.io._packet(e)}},{key:"onopen",value:function(){var t=this;"function"==typeof this.auth?this.auth(function(e){t._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}},{key:"_sendConnectPacket",value:function(e){this.packet({type:O.CONNECT,data:this._pid?r({pid:this._pid,offset:this._lastOffset},e):e})}},{key:"onerror",value:function(e){this.connected||this.emitReserved("connect_error",e)}},{key:"onclose",value:function(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}},{key:"onpacket",value:function(e){if(e.nsp===this.nsp)switch(e.type){case O.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case O.EVENT:case O.BINARY_EVENT:this.onevent(e);break;case O.ACK:case O.BINARY_ACK:this.onack(e);break;case O.DISCONNECT:this.ondisconnect();break;case O.CONNECT_ERROR:this.destroy();var t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}},{key:"onevent",value:function(e){var t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}},{key:"emitEvent",value:function(e){if(this._anyListeners&&this._anyListeners.length){var t,n=j(this._anyListeners.slice());try{for(n.s();!(t=n.n()).done;)t.value.apply(this,e)}catch(e){n.e(e)}finally{n.f()}}i(s(k.prototype),"emit",this).apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}},{key:"ack",value:function(i){var o=this,s=!1;return function(){if(!s){s=!0;for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.packet({type:O.ACK,id:i,data:t})}}}},{key:"onack",value:function(e){var t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}},{key:"onconnect",value:function(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}},{key:"emitBuffered",value:function(){var t=this;this.receiveBuffer.forEach(function(e){return t.emitEvent(e)}),this.receiveBuffer=[],this.sendBuffer.forEach(function(e){t.notifyOutgoingListeners(e),t.packet(e)}),this.sendBuffer=[]}},{key:"ondisconnect",value:function(){this.destroy(),this.onclose("io server disconnect")}},{key:"destroy",value:function(){this.subs&&(this.subs.forEach(function(e){return e()}),this.subs=void 0),this.io._destroy(this)}},{key:"disconnect",value:function(){return this.connected&&this.packet({type:O.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}},{key:"close",value:function(){return this.disconnect()}},{key:"compress",value:function(e){return this.flags.compress=e,this}},{key:"volatile",get:function(){return this.flags.volatile=!0,this}},{key:"timeout",value:function(e){return this.flags.timeout=e,this}},{key:"onAny",value:function(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}},{key:"prependAny",value:function(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}},{key:"offAny",value:function(e){if(this._anyListeners)if(e){for(var t=this._anyListeners,n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}},{key:"listenersAny",value:function(){return this._anyListeners||[]}},{key:"onAnyOutgoing",value:function(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}},{key:"prependAnyOutgoing",value:function(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}},{key:"offAnyOutgoing",value:function(e){if(this._anyOutgoingListeners)if(e){for(var t=this._anyOutgoingListeners,n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}},{key:"listenersAnyOutgoing",value:function(){return this._anyOutgoingListeners||[]}},{key:"notifyOutgoingListeners",value:function(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){var t,n=j(this._anyOutgoingListeners.slice());try{for(n.s();!(t=n.n()).done;)t.value.apply(this,e.data)}catch(e){n.e(e)}finally{n.f()}}}}]),k);function k(e,t,n){var i;return o(this,k),(i=He.call(this)).connected=!1,i.recovered=!1,i.receiveBuffer=[],i.sendBuffer=[],i._queue=[],i._queueSeq=0,i.ids=0,i.acks={},i.flags={},i.io=e,i.nsp=t,n&&n.auth&&(i.auth=n.auth),i._opts=r({},n),i.io._autoConnect&&i.open(),i}function R(e){this.ms=(e=e||{}).min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=0<e.jitter&&e.jitter<=1?e.jitter:0,this.attempts=0}R.prototype.duration=function(){var e,t,n=this.ms*Math.pow(this.factor,this.attempts++);return this.jitter&&(e=Math.random(),t=Math.floor(e*this.jitter*n),n=0==(1&Math.floor(10*e))?n-t:n+t),0|Math.min(n,this.max)},R.prototype.reset=function(){this.attempts=0},R.prototype.setMin=function(e){this.ms=e},R.prototype.setMax=function(e){this.max=e},R.prototype.setJitter=function(e){this.jitter=e};t(N,f),qe=n(N),e(N,[{key:"reconnection",value:function(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}},{key:"reconnectionAttempts",value:function(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}},{key:"reconnectionDelay",value:function(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null!=(t=this.backoff)&&t.setMin(e),this)}},{key:"randomizationFactor",value:function(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null!=(t=this.backoff)&&t.setJitter(e),this)}},{key:"reconnectionDelayMax",value:function(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null!=(t=this.backoff)&&t.setMax(e),this)}},{key:"timeout",value:function(e){return arguments.length?(this._timeout=e,this):this._timeout}},{key:"maybeReconnectOnOpen",value:function(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}},{key:"open",value:function(t){var e,n,i,o,s,a,r,l=this;return~this._readyState.indexOf("open")||(this.engine=new Me(this.uri,this.opts),e=this.engine,(n=this)._readyState="opening",this.skipReconnect=!1,i=I(e,"open",function(){n.onopen(),t&&t()}),s=I(e,"error",o=function(e){l.cleanup(),l._readyState="closed",l.emitReserved("error",e),t?t(e):l.maybeReconnectOnOpen()}),!1!==this._timeout&&(a=this._timeout,r=this.setTimeoutFn(function(){i(),o(new Error("timeout")),e.close()},a),this.opts.autoUnref&&r.unref(),this.subs.push(function(){l.clearTimeoutFn(r)})),this.subs.push(i),this.subs.push(s)),this}},{key:"connect",value:function(e){return this.open(e)}},{key:"onopen",value:function(){this.cleanup(),this._readyState="open",this.emitReserved("open");var e=this.engine;this.subs.push(I(e,"ping",this.onping.bind(this)),I(e,"data",this.ondata.bind(this)),I(e,"error",this.onerror.bind(this)),I(e,"close",this.onclose.bind(this)),I(this.decoder,"decoded",this.ondecoded.bind(this)))}},{key:"onping",value:function(){this.emitReserved("ping")}},{key:"ondata",value:function(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}},{key:"ondecoded",value:function(e){var t=this;be(function(){t.emitReserved("packet",e)},this.setTimeoutFn)}},{key:"onerror",value:function(e){this.emitReserved("error",e)}},{key:"socket",value:function(e,t){var n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Xe(this,e,t),this.nsps[e]=n),n}},{key:"_destroy",value:function(e){for(var t=0,n=Object.keys(this.nsps);t<n.length;t++){var i=n[t];if(this.nsps[i].active)return}this._close()}},{key:"_packet",value:function(e){for(var t=this.encoder.encode(e),n=0;n<t.length;n++)this.engine.write(t[n],e.options)}},{key:"cleanup",value:function(){this.subs.forEach(function(e){return e()}),this.subs.length=0,this.decoder.destroy()}},{key:"_close",value:function(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}},{key:"disconnect",value:function(){return this._close()}},{key:"onclose",value:function(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}},{key:"reconnect",value:function(){var t=this;if(this._reconnecting||this.skipReconnect)return this;var e,n,i=this;this.backoff.attempts>=this._reconnectionAttempts?(this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1):(e=this.backoff.duration(),this._reconnecting=!0,n=this.setTimeoutFn(function(){i.skipReconnect||(t.emitReserved("reconnect_attempt",i.backoff.attempts),i.skipReconnect)||i.open(function(e){e?(i._reconnecting=!1,i.reconnect(),t.emitReserved("reconnect_error",e)):i.onreconnect()})},e),this.opts.autoUnref&&n.unref(),this.subs.push(function(){t.clearTimeoutFn(n)}))}},{key:"onreconnect",value:function(){var e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}]);var qe,We=N,L={};function N(e,t){o(this,N),(n=qe.call(this)).nsps={},n.subs=[],e&&"object"===l(e)&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",n.opts=t,y(c(n),t),n.reconnection(!1!==t.reconnection),n.reconnectionAttempts(t.reconnectionAttempts||1/0),n.reconnectionDelay(t.reconnectionDelay||1e3),n.reconnectionDelayMax(t.reconnectionDelayMax||5e3),n.randomizationFactor(null!=(i=t.randomizationFactor)?i:.5),n.backoff=new R({min:n.reconnectionDelay(),max:n.reconnectionDelayMax(),jitter:n.randomizationFactor()}),n.timeout(null==t.timeout?2e4:t.timeout),n._readyState="closed",n.uri=e;var n,i=t.parser||Be;return n.encoder=new i.Encoder,n.decoder=new i.Decoder,n._autoConnect=!1!==t.autoConnect,n._autoConnect&&n.open(),n}function Je(e,t){"object"===l(e)&&(t=e,e=void 0);var e=function(e,t,n){var t=1<arguments.length&&void 0!==t?t:"",i=e,n=(2<arguments.length?n:void 0)||"undefined"!=typeof location&&location,e=("string"==typeof(e=null==e?n.protocol+"//"+n.host:e)&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),i=Ae(e=/^(https?|wss?):\/\//.test(e)?e:n.protocol+"//"+e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/",-1!==i.host.indexOf(":")?"["+i.host+"]":i.host);return i.id=i.protocol+"://"+e+":"+i.port+t,i.href=i.protocol+"://"+e+(n&&n.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),n=e.source,i=e.id,o=e.path,o=L[i]&&o in L[i].nsps,o=t.forceNew||t["force new connection"]||!1===t.multiplex||o?new We(n,t):(L[i]||(L[i]=new We(n,t)),L[i]);return e.query&&!t.query&&(t.query=e.queryKey),o.socket(e.path,t)}return r(Je,{Manager:We,Socket:Xe,io:Je,connect:Je}),Je});class EmulatorJS{version=2;getCore(e){var t=this.config.system;if(e){const n={virtualjaguar:"jaguar",handy:"lynx",yabause:"segaSaturn",genesis_plus_gx:"sega",fceumm:"nes",snes9x:"snes",a5200:"atari5200",gambatte:"gb",mgba:"gba",beetle_vb:"vb",mupen64plus_next:"n64",desmume2015:"nds",mame2003:"mame2003",fbalpha2012_cps1:"arcade",fbalpha2012_cps2:"arcade",mednafen_psx_hw:"psx",melonds:"nds",nestopia:"nes",opera:"3do",prosystem:"atari7800",stella2014:"atari2600"};return n[t]||t}const n={jaguar:"virtualjaguar",lynx:"handy",segaSaturn:"yabause",segaMS:"genesis_plus_gx",segaMD:"genesis_plus_gx",segaGG:"genesis_plus_gx",segaCD:"genesis_plus_gx",atari2600:"stella2014",atari7800:"prosystem",nes:"fceumm",snes:"snes9x",atari5200:"a5200",gb:"gambatte",gba:"mgba",vb:"beetle_vb",n64:"mupen64plus_next",nds:"melonds",mame2003:"mame2003",arcade:"fbalpha2012_cps1",psx:"mednafen_psx_hw","3do":"opera"};return n[t]||t}extensions={fceumm:["fds","nes","unif","unf"],snes9x:["smc","sfc","swc","fig","bs","st"],a5200:["a52","bin"],gambatte:["gb","gbc","dmg"],mgba:["gb","gbc","gba"],beetle_vb:["vb","vboy","bin"],mupen64plus_next:["n64","v64","z64","bin","u1","ndd","gb"],fbalpha2012_cps1:["zip"],fbalpha2012_cps2:["zip"],mame2003:["zip"],desmume2015:["nds","bin"],melonds:["nds"],mednafen_psx:["cue","toc","m3u","ccd","exe","pbp","chd"],mednafen_psx_hw:["cue","toc","m3u","ccd","exe","pbp","chd"],nestopia:["fds","nes","unif","unf"],opera:["iso","bin","chd","cue"]};createElement(e){return document.createElement(e)}addEventListener(t,e,n){var i=e.split(" "),o=[];for(let e=0;e<i.length;e++){t.addEventListener(i[e],n);var s={cb:n,elem:t,listener:i[e]};o.push(s),this.listeners.push(s)}return o}removeEventListener(t){for(let e=0;e<t.length;e++)t[e].elem.removeEventListener(t[e].listener,t[e].cb)}downloadFile(t,n,i,e,o){var s=e?"":this.config.dataPath;t=s+t,!e&&this.config.filePaths&&"string"==typeof this.config.filePaths[t.split("/").pop()]&&(t=this.config.filePaths[t.split("/").pop()]);let a;try{a=new URL(t)}catch(e){}if(a&&["http:","https:"].includes(a.protocol)||!a){const r=new XMLHttpRequest;i instanceof Function&&r.addEventListener("progress",e=>{e=e.total?" "+Math.floor(e.loaded/e.total*100).toString()+"%":" "+(e.loaded/1048576).toFixed(2)+"MB";i(e)}),r.onload=function(){if(r.readyState===r.DONE){let e=r.response;if(r.status.toString().startsWith("4")||r.status.toString().startsWith("5"))n(-1);else{try{e=JSON.parse(e)}catch(e){}n({data:e,headers:{"content-length":r.getResponseHeader("content-length")}})}}},o.responseType&&(r.responseType=o.responseType),r.onerror=()=>n(-1),r.open(o.method,t,!0),r.send()}else(async()=>{if("HEAD"===o.method)n({headers:{}});else{let e;try{if(e=await fetch(t),o.type&&"arraybuffer"===o.type.toLowerCase()||!o.type)e=await e.arrayBuffer();else{e=await e.text();try{e=JSON.parse(e)}catch(e){}}}catch(e){n(-1)}t.startsWith("blob:")&&URL.revokeObjectURL(t),n({data:e,headers:{}})}})()}checkForUpdates(){fetch("https://raw.githack.com/EmulatorJS/EmulatorJS/main/data/version.json").then(e=>{e.ok&&e.text().then(e=>{e=JSON.parse(e);this.ejs_num_version<e.current_version&&console.log("Using emulatorjs version "+this.ejs_num_version+" but the newest version is "+e.current_version+"\nopen https://github.com/EmulatorJS/EmulatorJS to update")})})}constructor(e,t){if(this.ejs_version="4.0.4",this.ejs_num_version=40.4,this.debug=!0===window.EJS_DEBUG_XX,(this.debug||window.location&&["localhost","127.0.0.1"].includes(location.hostname))&&this.checkForUpdates(),this.netplayEnabled=!1,this.debug||(this.netplayEnabled=!1),this.config=t,this.currentPopup=null,this.touch=!1,this.cheats=[],this.started=!1,this.volume="number"==typeof this.config.volume?this.config.volume:.5,this.config.defaultControllers&&(this.defaultControllers=this.config.defaultControllers),this.muted=!1,this.paused=!0,this.listeners=[],this.setElements(e),this.setColor(this.config.color||""),this.config.adUrl&&this.setupAds(this.config.adUrl),this.canvas=this.createElement("canvas"),this.canvas.classList.add("ejs_canvas"),this.bindListeners(),this.config.netplayUrl=this.config.netplayUrl||"https://netplay.emulatorjs.org",this.fullscreen=!1,this.isMobile=function(){let e=!1;var t;return t=navigator.userAgent||navigator.vendor||window.opera,e=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))?!0:e}(),this.storage={rom:new window.EJS_STORAGE("EmulatorJS-roms","rom"),bios:new window.EJS_STORAGE("EmulatorJS-bios","bios"),core:new window.EJS_STORAGE("EmulatorJS-core","core"),states:new window.EJS_STORAGE("EmulatorJS-states","states")},this.game.classList.add("ejs_game"),"string"==typeof this.config.backgroundImg&&(this.game.style["background-image"]="url('"+this.config.backgroundImg+"')",this.game.style["background-size"]="contain",this.game.style["background-position"]="center",this.game.style["background-repeat"]="no-repeat",this.on("start",()=>{this.game.style["background-image"]="",this.game.style["background-size"]="",this.game.style["background-position"]="",this.game.style["background-repeat"]=""})),Array.isArray(this.config.cheats))for(let e=0;e<this.config.cheats.length;e++){var n=this.config.cheats[e];Array.isArray(n)&&n[0]&&n[1]&&this.cheats.push({desc:n[0],checked:!1,code:n[1]})}this.createStartButton()}setColor(e){function t(n){if((n=n.toLowerCase())&&/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(n)){if(4===n.length){let t="#";for(let e=1;e<4;e++)t+=n.slice(e,e+1)+n.slice(e,e+1);n=t}var t=[];for(let e=1;e<7;e+=2)t.push(parseInt("0x"+n.slice(e,e+2),16));return t.join(", ")}return null}(e="string"!=typeof e?"":e)&&null!==t(e)?this.elements.parent.setAttribute("style","--ejs-primary-color:"+t(e)+";"):this.elements.parent.setAttribute("style","--ejs-primary-color: 26,175,255;")}setupAds(e){const t=this.createElement("div");t.classList.add("ejs_ad_iframe");var n=this.createElement("iframe");n.src=e,n.setAttribute("scrolling","no"),n.setAttribute("frameborder","no"),n.style.width="300px",n.style.height="250px";const i=this.createElement("div");i.classList.add("ejs_ad_close");e=this.createElement("a");i.appendChild(e),i.setAttribute("hidden",""),t.appendChild(i),t.appendChild(n),this.elements.parent.appendChild(t),this.addEventListener(e,"click",()=>{t.remove()}),this.on("start",()=>{i.removeAttribute("hidden");var e="number"==typeof this.config.adTimer&&0<this.config.adTimer?this.config.adTimer:1e4;0!==this.config.adTimer&&setTimeout(()=>{t.remove()},e)})}functions={};on(e,t){Array.isArray(this.functions[e])||(this.functions[e]=[]),this.functions[e].push(t)}callEvent(e,t){return Array.isArray(this.functions[e])?(this.functions[e].forEach(e=>e(t)),this.functions[e].length):0}setElements(e){var t=this.createElement("div"),e=document.querySelector(e);e.innerHTML="",e.appendChild(t),this.game=t,this.elements={main:this.game,parent:e},this.elements.parent.classList.add("ejs_parent"),this.elements.parent.setAttribute("tabindex",-1)}createStartButton(){var e=this.createElement("div");e.classList.add("ejs_start_button"),e.innerText=this.localization("Start Game"),this.elements.parent.appendChild(e),this.addEventListener(e,"touchstart",()=>{this.touch=!0}),this.addEventListener(e,"click",this.startButtonClicked.bind(this)),!0===this.config.startOnLoad&&this.startButtonClicked(e)}startButtonClicked(e){"touch"===e.pointerType&&(this.touch=!0),(e.preventDefault?(e.preventDefault(),e.target):e).remove(),this.createText(),this.downloadGameCore()}createText(){this.textElem=this.createElement("div"),this.textElem.classList.add("ejs_loading_text"),this.textElem.innerText=this.localization("Loading..."),this.elements.parent.appendChild(this.textElem)}localization(e){return isNaN(e)&&this.config.langJson&&(this.config.langJson[e]||console.log("Translation not found for '"+e+"'. Language set to '"+this.config.language+"'"),this.config.langJson[e])||e}checkCompression(t,a,r){a&&(this.textElem.innerText=a);const s=n=>new Promise((t,e)=>{this.downloadFile(n,e=>{-1===e?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):(e=new Blob([e.data],{type:"application/javascript"}),e=window.URL.createObjectURL(e),t(new Worker(e)))},null,!1,{responseType:"arraybuffer",method:"GET"})});var e=o=>new Promise((n,e)=>{const i={},t=e=>{if(e.data){if(4===e.data.t&&a){var t=e.data,t=Math.floor(t.current/t.total*100);if(isNaN(t))return;t=" "+t.toString()+"%";this.textElem.innerText=a+t}2===e.data.t&&("function"==typeof r?(r(e.data.file,e.data.data),i[e.data.file]=!0):i[e.data.file]=e.data.data),1===e.data.t&&n(i)}};s("compression/extract7z.js").then(e=>{e.onmessage=t,e.postMessage(o)})}),n=s=>new Promise((n,e)=>{const i={},o=e=>{if(e.data){if(4===e.data.t&&a){var t=e.data,t=Math.floor(t.current/t.total*100);if(isNaN(t))return;t=" "+t.toString()+"%";this.textElem.innerText=a+t}2===e.data.t&&("function"==typeof r?(r(e.data.file,e.data.data),i[e.data.file]=!0):i[e.data.file]=e.data.data),1===e.data.t&&n(i)}};this.downloadFile("compression/libunrar.js",t=>{this.downloadFile("compression/libunrar.js.mem",e=>{-1===t||-1===e?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):(e="\nlet dataToPass = [];\nModule = {\n monitorRunDependencies: function(left) {\n if (left == 0) {\n setTimeout(function() {\n unrar(dataToPass, null);\n }, 100);\n }\n },\n onRuntimeInitialized: function() {\n },\n locateFile: function(file) {\n return '"+URL.createObjectURL(new Blob([e]))+"';\n }\n};\n"+t.data+'\nlet unrar = function(data, password) {\n let cb = function(fileName, fileSize, progress) {\n postMessage({"t":4,"current":progress,"total":fileSize, "name": fileName});\n };\n\n let rarContent = readRARContent(data.map(function(d) {\n return {\n name: d.name,\n content: new Uint8Array(d.content)\n }\n }), password, cb)\n let rec = function(entry) {\n if (entry.type === \'file\') {\n postMessage({"t":2,"file":entry.fullFileName,"size":entry.fileSize,"data":entry.fileContent});\n } else if (entry.type === \'dir\') {\n Object.keys(entry.ls).forEach(function(k) {\n rec(entry.ls[k]);\n })\n } else {\n throw "Unknown type";\n }\n }\n rec(rarContent);\n postMessage({"t":1});\n return rarContent;\n};\nonmessage = function(data) {\n dataToPass.push({name: \'test.rar\', content: data.data});\n};\n ',e=new Blob([e],{type:"application/javascript"}),e=window.URL.createObjectURL(e),(e=new Worker(e)).onmessage=o,e.postMessage(s))},null,!1,{responseType:"text",method:"GET"})},null,!1,{responseType:"text",method:"GET"})}),i=o=>new Promise((n,e)=>{const i={},t=e=>{if(e.data){if(4===e.data.t&&a){var t=e.data,t=Math.floor(t.current/t.total*100);if(isNaN(t))return;t=" "+t.toString()+"%";this.textElem.innerText=a+t}2===e.data.t&&("function"==typeof r?(r(e.data.file,e.data.data),i[e.data.file]=!0):i[e.data.file]=e.data.data),1===e.data.t&&n(i)}};s("compression/extractzip.js").then(e=>{e.onmessage=t,e.postMessage(o)})}),o=80===(o=t.slice(0,10))[0]&&75===o[1]&&(3===o[2]&&4===o[3]||5===o[2]&&6===o[3]||7===o[2]&&8===o[3])?"zip":55===o[0]&&122===o[1]&&188===o[2]&&175===o[3]&&39===o[4]&&28===o[5]?"7z":82===o[0]&&97===o[1]&&114===o[2]&&33===o[3]&&26===o[4]&&7===o[5]&&(0===o[6]||1===o[6]&&0==o[7])?"rar":void 0;return o?"7z"===o?e(t):"zip"===o?i(t):"rar"===o?n(t):void 0:"function"==typeof r?(r("!!notCompressedData",t),new Promise(e=>e({"!!notCompressedData":!0}))):new Promise(e=>e({"!!notCompressedData":t}))}downloadGameCore(){this.textElem.innerText=this.localization("Download Game Core");const t=e=>{this.checkCompression(new Uint8Array(e),this.localization("Decompress Game Core")).then(e=>{let t,n;for(var i in e)i.endsWith(".wasm")?n=e[i]:i.endsWith(".js")&&(t=e[i]);this.initGameCore(t,n)})};this.storage.core.get(this.getCore()+"-wasm.data").then(e=>{e&&e.version===this.version&&!this.debug?t(e.data):this.downloadFile("cores/"+this.getCore()+"-wasm.data",e=>{-1===e?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):(t(e.data),this.storage.core.put(this.getCore()+"-wasm.data",{version:this.version,data:e.data}))},e=>{this.textElem.innerText=this.localization("Download Game Core")+e},!1,{responseType:"arraybuffer",method:"GET"})})}initGameCore(e,t){this.initModule(t);t=this.createElement("script");t.src=URL.createObjectURL(new Blob([e],{type:"application/javascript"})),document.body.appendChild(t)}getBaseFileName(){if(!this.started)return null;if("string"==typeof this.config.gameName){var e=this.config.gameName.replace(/[#<$+%>!`&*'|{}/\\?"=@:^\r\n]/gi,"").trim();if(e)return e}e=this.fileName.split(".");return e.splice(e.length-1,1),e.join(".")}saveInBrowserSupported(){return!(!window.indexedDB||"string"!=typeof this.config.gameName&&this.config.gameUrl.startsWith("blob:"))}displayMessage(e){this.msgElem||(this.msgElem=this.createElement("div"),this.msgElem.classList.add("ejs_message"),this.elements.parent.appendChild(this.msgElem)),clearTimeout(this.msgTimeout),this.msgTimeout=setTimeout(()=>{this.msgElem.innerText=""},3e3),this.msgElem.innerText=e}downloadStartState(){return new Promise((t,e)=>{"string"!=typeof this.config.loadState?t():(this.textElem.innerText=this.localization("Download Game State"),this.downloadFile(this.config.loadState,e=>{-1===e?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):(this.on("start",()=>{setTimeout(()=>{this.gameManager.loadState(new Uint8Array(e.data))},10)}),t())},e=>{this.textElem.innerText=this.localization("Download Game State")+e},!0,{responseType:"arraybuffer",method:"GET"}))})}downloadGamePatch(){return new Promise((n,e)=>{if("string"==typeof this.config.gamePatchUrl&&this.config.gamePatchUrl.trim()){this.textElem.innerText=this.localization("Download Game Patch");const i=e=>{this.checkCompression(new Uint8Array(e),this.localization("Decompress Game Patch")).then(e=>{for(const t in e){if("!!notCompressedData"===t){FS.writeFile(this.config.gamePatchUrl.split("/").pop().split("#")[0].split("?")[0],e[t]);break}t.endsWith("/")||FS.writeFile("/"+t.split("/").pop(),e[t])}n()})};this.downloadFile(this.config.gamePatchUrl,t=>{this.storage.rom.get(this.config.gamePatchUrl.split("/").pop()).then(e=>{e&&e["content-length"]===t.headers["content-length"]&&!this.debug?i(e.data):this.downloadFile(this.config.gamePatchUrl,e=>{var t;-1===e?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):(i(e.data),t="number"==typeof this.config.cacheLimit?this.config.cacheLimit:1073741824,parseFloat(e.headers["content-length"])<t&&this.saveInBrowserSupported()&&this.storage.rom.put(this.config.gamePatchUrl.split("/").pop(),{"content-length":e.headers["content-length"],data:e.data}))},e=>{this.textElem.innerText=this.localization("Download Game Patch")+e},!0,{responseType:"arraybuffer",method:"GET"})})},null,!0,{method:"HEAD"})}else n()})}downloadGameParent(){return new Promise((n,e)=>{if("string"==typeof this.config.gameParentUrl&&this.config.gameParentUrl.trim()){this.textElem.innerText=this.localization("Download Game Parent");const i=e=>{this.checkCompression(new Uint8Array(e),this.localization("Decompress Game Parent")).then(e=>{for(const t in e){if("!!notCompressedData"===t){FS.writeFile(this.config.gameParentUrl.split("/").pop().split("#")[0].split("?")[0],e[t]);break}t.endsWith("/")||FS.writeFile("/"+t.split("/").pop(),e[t])}n()})};this.downloadFile(this.config.gameParentUrl,t=>{this.storage.rom.get(this.config.gameParentUrl.split("/").pop()).then(e=>{e&&e["content-length"]===t.headers["content-length"]&&!this.debug?i(e.data):this.downloadFile(this.config.gameParentUrl,e=>{var t;-1===e?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):(i(e.data),t="number"==typeof this.config.cacheLimit?this.config.cacheLimit:1073741824,parseFloat(e.headers["content-length"])<t&&this.saveInBrowserSupported()&&this.storage.rom.put(this.config.gameParentUrl.split("/").pop(),{"content-length":e.headers["content-length"],data:e.data}))},e=>{this.textElem.innerText=this.localization("Download Game Parent")+e},!0,{responseType:"arraybuffer",method:"GET"})})},null,!0,{method:"HEAD"})}else n()})}downloadBios(){return new Promise((n,e)=>{if("string"==typeof this.config.biosUrl&&this.config.biosUrl.trim()){this.textElem.innerText=this.localization("Download Game BIOS");const i=e=>{this.checkCompression(new Uint8Array(e),this.localization("Decompress Game BIOS")).then(e=>{for(const t in e){if("!!notCompressedData"===t){FS.writeFile(this.config.biosUrl.split("/").pop().split("#")[0].split("?")[0],e[t]);break}t.endsWith("/")||FS.writeFile("/"+t.split("/").pop(),e[t])}n()})};this.downloadFile(this.config.biosUrl,t=>{-1===t?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):this.storage.bios.get(this.config.biosUrl.split("/").pop()).then(e=>{e&&e["content-length"]===t.headers["content-length"]&&!this.debug?i(e.data):this.downloadFile(this.config.biosUrl,e=>{-1===e?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):(i(e.data),this.saveInBrowserSupported()&&this.storage.bios.put(this.config.biosUrl.split("/").pop(),{"content-length":e.headers["content-length"],data:e.data}))},e=>{this.textElem.innerText=this.localization("Download Game BIOS")+e},!0,{responseType:"arraybuffer",method:"GET"})})},null,!0,{method:"HEAD"})}else n()})}downloadRom(){return new Promise((s,e)=>{this.gameManager=new window.EJS_GameManager(this.Module,this),this.textElem.innerText=this.localization("Download Game Data");const n=e=>{if(["arcade","mame2003"].includes(this.getCore(!0)))this.fileName=this.config.gameUrl.split("/").pop().split("#")[0].split("?")[0],FS.writeFile(this.fileName,new Uint8Array(e)),s();else{let i={};const o=this.config.gameUrl.startsWith("blob:")?this.config.gameName||"game":this.config.gameUrl.split("/").pop().split("#")[0].split("?")[0];this.checkCompression(new Uint8Array(e),this.localization("Decompress Game Data"),(e,t)=>{if(console.log(e),e.includes("/")){var n=e.split("/");let t="";for(let e=0;e<n.length-1;e++)""===n[e]||(t+="/"+n[e],FS.analyzePath(t).exists)||FS.mkdir(t)}e.endsWith("/")?FS.mkdir(e):("psx"===this.getCore(!0)&&["m3u","cue"].includes(e.split(".").pop().toLowerCase())?i[e]=t:"psx"===this.getCore(!0)&&"!!notCompressedData"!==e&&(i[e]=!0),"!!notCompressedData"===e?(FS.writeFile(o,t),i[o]=!0):FS.writeFile("/"+e,t))}).then(()=>{var e=(()=>{var e=[];for(const t in i)e.push(t);return e})();1===e.length&&(e[0]=o);let t=null;"psx"===this.getCore(!0)&&(t=this.gameManager.createCueFile(e));for(const n in i){if("!!notCompressedData"===n){"psx"===this.getCore(!0)&&null!==t?this.fileName=t:this.fileName=o;break}this.fileName&&(!(this.extensions[this.getCore()]||[]).includes(n.split(".").pop())||"psx"===this.getCore(!0)&&["m3u","ccd"].includes(this.fileName.split(".").pop()))||(this.fileName=n),"psx"===this.getCore(!0)&&null===t&&["m3u","cue"].includes(n.split(".").pop().toLowerCase())&&(console.log(n,i[n]),FS.writeFile("/"+n,i[n]))}"psx"===this.getCore(!0)&&null!==t&&(this.fileName=t),s()})}};this.downloadFile(this.config.gameUrl,t=>{-1===t?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):this.storage.rom.get(this.config.gameUrl.split("/").pop()).then(e=>{e&&e["content-length"]===t.headers["content-length"]&&!this.debug?n(e.data):this.downloadFile(this.config.gameUrl,e=>{var t;-1===e?(this.textElem.innerText=this.localization("Network Error"),this.textElem.style.color="red"):(n(e.data),t="number"==typeof this.config.cacheLimit?this.config.cacheLimit:1073741824,parseFloat(e.headers["content-length"])<t&&this.saveInBrowserSupported()&&this.storage.rom.put(this.config.gameUrl.split("/").pop(),{"content-length":e.headers["content-length"],data:e.data}))},e=>{this.textElem.innerText=this.localization("Download Game Data")+e},!0,{responseType:"arraybuffer",method:"GET"})})},null,!0,{method:"HEAD"})})}downloadFiles(){(async()=>{await this.downloadRom(),await this.downloadBios(),await this.downloadStartState(),await this.downloadGameParent(),await this.downloadGamePatch(),this.startGame()})()}initModule(t){window.Module={noInitialRun:!0,onRuntimeInitialized:this.downloadFiles.bind(this),arguments:[],preRun:[],postRun:[],canvas:this.canvas,print:e=>{this.debug&&console.log(e)},printErr:e=>{this.debug&&console.log(e)},totalDependencies:0,monitorRunDependencies:()=>{},locateFile:function(e){if(this.debug&&console.log(e),e.endsWith(".wasm"))return URL.createObjectURL(new Blob([t],{type:"application/wasm"}))}},this.Module=window.Module}startGame(){try{var e=[];this.debug&&e.push("-v"),e.push("/"+this.fileName),this.debug&&console.log(e),this.Module.callMain(e),this.Module.resumeMainLoop(),this.touch&&(this.virtualGamepad.style.display=""),this.checkSupportedOpts(),this.setupSettingsMenu(),this.loadSettings(),this.updateCheatUI(),this.updateGamepadLabels(),this.muted||this.setVolume(this.volume),this.elements.parent.focus(),this.textElem.remove(),this.textElem=null,this.game.classList.remove("ejs_game"),this.game.appendChild(this.canvas),this.handleResize(),this.started=!0,this.paused=!1}catch(e){return console.warn("failed to start game",e),this.textElem.innerText=this.localization("Failed to start game"),void(this.textElem.style.color="red")}this.callEvent("start")}bindListeners(){this.createContextMenu(),this.createBottomMenuBar(),this.createControlSettingMenu(),this.createCheatsMenu(),this.createNetplayMenu(),this.setVirtualGamepad(),this.addEventListener(this.elements.parent,"keydown keyup",this.keyChange.bind(this)),this.addEventListener(this.elements.parent,"mousedown touchstart",e=>{document.activeElement!==this.elements.parent&&this.elements.parent.focus()}),this.addEventListener(window,"resize",this.handleResize.bind(this)),this.gamepad=new GamepadHandler,this.gamepad.on("connected",e=>{this.gamepadLabels&&this.updateGamepadLabels()}),this.gamepad.on("disconnected",e=>{setTimeout(this.updateGamepadLabels.bind(this),10)}),this.gamepad.on("axischanged",this.gamepadEvent.bind(this)),this.gamepad.on("buttondown",this.gamepadEvent.bind(this)),this.gamepad.on("buttonup",this.gamepadEvent.bind(this))}checkSupportedOpts(){this.gameManager.supportsStates()||(this.elements.bottomBar.saveState[0].style.display="none",this.elements.bottomBar.loadState[0].style.display="none",this.elements.bottomBar.netplay[0].style.display="none",this.elements.contextMenu.save.style.display="none",this.elements.contextMenu.load.style.display="none"),"number"==typeof this.config.gameId&&this.config.netplayUrl&&!1!==this.netplayEnabled||(this.elements.bottomBar.netplay[0].style.display="none")}updateGamepadLabels(){for(let e=0;e<this.gamepadLabels.length;e++)this.gamepad.gamepads[e]?this.gamepadLabels[e].innerText=this.gamepad.gamepads[e].id:this.gamepadLabels[e].innerText="n/a"}createContextMenu(){this.elements.contextmenu=this.createElement("div"),this.elements.contextmenu.classList.add("ejs_context_menu"),this.addEventListener(this.game,"contextmenu",e=>{this.started&&(this.elements.contextmenu.style.display="block",this.elements.contextmenu.style.left=e.offsetX+"px",this.elements.contextmenu.style.top=e.offsetY+"px"),e.preventDefault()});const h=()=>{this.elements.contextmenu.style.display="none"},o=(this.addEventListener(this.elements.contextmenu,"contextmenu",e=>e.preventDefault()),this.addEventListener(this.elements.parent,"contextmenu",e=>e.preventDefault()),this.addEventListener(this.game,"mousedown",h),this.createElement("ul"));var e=(e,t,n)=>{var i=this.createElement("li"),t=(t&&(i.hidden=!0),this.createElement("a"));return n instanceof Function&&this.addEventListener(i,"click",e=>{e.preventDefault(),n()}),t.href="#",t.onclick="return false",t.innerText=e,i.appendChild(t),o.appendChild(i),h(),i};let n;var t=e("Take Screenshot",!1,()=>{n&&URL.revokeObjectURL(n);var e=this.gameManager.screenshot(),e=new Blob([e]),e=(n=URL.createObjectURL(e),this.createElement("a")),t=(e.href=n,new Date);e.download=this.getBaseFileName()+"-"+t.getMonth()+"-"+t.getDate()+"-"+t.getFullYear()+".png",e.click(),h()}),i=e("Quick Save",!1,()=>{var e=this.settings["save-state-slot"]||"1";this.gameManager.quickSave(e),this.displayMessage(this.localization("SAVED STATE TO SLOT")+" "+e),h()}),s=e("Quick Load",!1,()=>{var e=this.settings["save-state-slot"]||"1";this.gameManager.quickLoad(e),this.displayMessage(this.localization("LOADED STATE FROM SLOT")+" "+e),h()});this.elements.contextMenu={screenshot:t,save:i,load:s},e("EmulatorJS v"+this.ejs_version,!1,()=>{h();var e=this.createPopup("EmulatorJS",{Close:()=>{this.closePopup()}}),t=this.createElement("div");t.classList.add("ejs_list_selector");const o=this.createElement("ul");var n=(e,t,n)=>{var i=this.createElement("li"),t=(t&&(i.hidden=!0),this.createElement("a"));return n instanceof Function&&this.addEventListener(i,"click",e=>{e.preventDefault(),n()}),t.href="#",t.onclick="return false",t.innerText=e,i.appendChild(t),o.appendChild(i),h(),i};const i=this.createElement("div"),s=this.createElement("div"),a=(s.style.display="none",this.createElement("div"));a.style.display="none",e.appendChild(i),e.appendChild(s),e.appendChild(a);let r=i;i.innerText="EmulatorJS v"+this.ejs_version,i.appendChild(this.createElement("br")),i.appendChild(this.createElement("br"));var l=this.createElement("a"),l=(l.href="https://github.com/EmulatorJS/EmulatorJS",l.target="_blank",l.innerText=this.localization("View on GitHub"),i.appendChild(l),i.appendChild(this.createElement("br")),this.createElement("a"));l.href="https://discord.gg/6akryGkETU",l.target="_blank",l.innerText=this.localization("Join the discord"),i.appendChild(l),i.appendChild(this.createElement("br")),t.appendChild(o),e.appendChild(t);const c=e=>{r!==e&&(r&&(r.style.display="none"),(r=e).style.display="")};n("Home",!1,()=>{c(i)}),n("EmulatorJS License",!1,()=>{c(s)}),n("RetroArch License",!1,()=>{c(a)}),a.innerText="This project is powered by ";l=this.createElement("a"),l.href="https://github.com/libretro/RetroArch",l.target="_blank",l.innerText="RetroArch",a.appendChild(l),e=this.createElement("a");e.target="_blank",e.href="https://github.com/libretro/RetroArch/blob/master/COPYING",e.innerText="View the RetroArch license here.",l.appendChild(this.createElement("br")),l.appendChild(e),s.style["text-align"]="center",s.style.padding="10px",s.innerText=' GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users. We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors. You can apply it to\nyour programs, too.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\n Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n For the developers\' and authors\' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users\' and\nauthors\' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so. This is fundamentally incompatible with the aim of\nprotecting users\' freedom to change the software. The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable. Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts. If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary. To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n TERMS AND CONDITIONS\n\n 0. Definitions.\n\n "This License" refers to version 3 of the GNU General Public License.\n\n "Copyright" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n "The Program" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as "you". "Licensees" and\n"recipients" may be individuals or organizations.\n\n To "modify" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a "modified version" of the\nearlier work or a work "based on" the earlier work.\n\n A "covered work" means either the unmodified Program or a work based\non the Program.\n\n To "propagate" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n To "convey" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n An interactive user interface displays "Appropriate Legal Notices"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n 1. Source Code.\n\n The "source code" for a work means the preferred form of the work\nfor making modifications to it. "Object code" means any non-source\nform of a work.\n\n A "Standard Interface" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n The "System Libraries" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n"Major Component", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n The "Corresponding Source" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work\'s\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n The Corresponding Source for a work in source code form is that\nsame work.\n\n 2. Basic Permissions.\n\n All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n Conveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n 3. Protecting Users\' Legal Rights From Anti-Circumvention Law.\n\n No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work\'s\nusers, your or third parties\' legal rights to forbid circumvention of\ntechnological measures.\n\n 4. Conveying Verbatim Copies.\n\n You may convey verbatim copies of the Program\'s source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n 5. Conveying Modified Source Versions.\n\n You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n a) The work must carry prominent notices stating that you modified\n it, and giving a relevant date.\n\n b) The work must carry prominent notices stating that it is\n released under this License and any conditions added under section\n 7. This requirement modifies the requirement in section 4 to\n "keep intact all notices".\n\n c) You must license the entire work, as a whole, under this\n License to anyone who comes into possession of a copy. This\n License will therefore apply, along with any applicable section 7\n additional terms, to the whole of the work, and all its parts,\n regardless of how they are packaged. This License gives no\n permission to license the work in any other way, but it does not\n invalidate such permission if you have separately received it.\n\n d) If the work has interactive user interfaces, each must display\n Appropriate Legal Notices; however, if the Program has interactive\n interfaces that do not display Appropriate Legal Notices, your\n work need not make them do so.\n\n A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n"aggregate" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation\'s users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n 6. Conveying Non-Source Forms.\n\n You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n a) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by the\n Corresponding Source fixed on a durable physical medium\n customarily used for software interchange.\n\n b) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by a\n written offer, valid for at least three years and valid for as\n long as you offer spare parts or customer support for that product\n model, to give anyone who possesses the object code either (1) a\n copy of the Corresponding Source for all the software in the\n product that is covered by this License, on a durable physical\n medium customarily used for software interchange, for a price no\n more than your reasonable cost of physically performing this\n conveying of source, or (2) access to copy the\n Corresponding Source from a network server at no charge.\n\n c) Convey individual copies of the object code with a copy of the\n written offer to provide the Corresponding Source. This\n alternative is allowed only occasionally and noncommercially, and\n only if you received the object code with such an offer, in accord\n with subsection 6b.\n\n d) Convey the object code by offering access from a designated\n place (gratis or for a charge), and offer equivalent access to the\n Corresponding Source in the same way through the same place at no\n further charge. You need not require recipients to copy the\n Corresponding Source along with the object code. If the place to\n copy the object code is a network server, the Corresponding Source\n may be on a different server (operated by you or a third party)\n that supports equivalent copying facilities, provided you maintain\n clear directions next to the object code saying where to find the\n Corresponding Source. Regardless of what server hosts the\n Corresponding Source, you remain obligated to ensure that it is\n available for as long as needed to satisfy these requirements.\n\n e) Convey the object code using peer-to-peer transmission, provided\n you inform other peers where the object code and Corresponding\n Source of the work are being offered to the general public at no\n charge under subsection 6d.\n\n A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n A "User Product" is either (1) a "consumer product", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, "normally used" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n "Installation Information" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n 7. Additional Terms.\n\n "Additional permissions" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n a) Disclaiming warranty or limiting liability differently from the\n terms of sections 15 and 16 of this License; or\n\n b) Requiring preservation of specified reasonable legal notices or\n author attributions in that material or in the Appropriate Legal\n Notices displayed by works containing it; or\n\n c) Prohibiting misrepresentation of the origin of that material, or\n requiring that modified versions of such material be marked in\n reasonable ways as different from the original version; or\n\n d) Limiting the use for publicity purposes of names of licensors or\n authors of the material; or\n\n e) Declining to grant rights under trademark law for use of some\n trade names, trademarks, or service marks; or\n\n f) Requiring indemnification of licensors and authors of that\n material by anyone who conveys the material (or modified versions of\n it) with contractual assumptions of liability to the recipient, for\n any liability that these contractual assumptions directly impose on\n those licensors and authors.\n\n All other non-permissive additional terms are considered "further\nrestrictions" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n 8. Termination.\n\n You may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n 9. Acceptance Not Required for Having Copies.\n\n You are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n 10. Automatic Licensing of Downstream Recipients.\n\n Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\n An "entity transaction" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party\'s predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n 11. Patents.\n\n A "contributor" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor\'s "contributor version".\n\n A contributor\'s "essential patent claims" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, "control" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor\'s essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n In the following three paragraphs, a "patent license" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To "grant" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. "Knowingly relying" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient\'s use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n A patent license is "discriminatory" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n 12. No Surrender of Others\' Freedom.\n\n If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n 13. Use with the GNU Affero General Public License.\n\n Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n 14. Revised Versions of this License.\n\n The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time. Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n Each version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License "or any later version" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy\'s\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n Later license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n 15. Disclaimer of Warranty.\n\n THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n 16. Limitation of Liability.\n\n IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n 17. Interpretation of Sections 15 and 16.\n\n If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n END OF TERMS AND CONDITIONS\n\n How to Apply These Terms to Your New Programs\n\n If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n To do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe "copyright" line and a pointer to where the full notice is found.\n\n EmulatorJS: RetroArch on the web\n Copyright (C) 2023 Ethan O\'Brien\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n EmulatorJS Copyright (C) 2023 Ethan O\'Brien\n This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.\n This is free software, and you are welcome to redistribute it\n under certain conditions; type `show c\' for details.\n\nThe hypothetical commands `show w\' and `show c\' should show the appropriate\nparts of the General Public License. Of course, your program\'s commands\nmight be different; for a GUI interface, you would use an "about box".\n\n You should also get your employer (if you work as a programmer) or school,\nif any, to sign a "copyright disclaimer" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n The GNU General Public License does not permit incorporating your program\ninto proprietary programs. If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library. If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License. But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n'}),this.config.buttonOpts&&(!1===this.config.buttonOpts.screenshot&&t.setAttribute("hidden",""),!1===this.config.buttonOpts.quickSave&&i.setAttribute("hidden",""),!1===this.config.buttonOpts.quickLoad)&&s.setAttribute("hidden",""),this.elements.contextmenu.appendChild(o),this.elements.parent.appendChild(this.elements.contextmenu)}closePopup(){if(null!==this.currentPopup){try{this.currentPopup.remove()}catch(e){}this.currentPopup=null}}createPopup(e,n,t){t||this.closePopup();var i=this.createElement("div"),o=(i.classList.add("ejs_popup_container"),this.elements.parent.appendChild(i),this.createElement("h4")),e=(o.innerText=this.localization(e),this.createElement("div"));e.classList.add("ejs_popup_body"),i.appendChild(o),i.appendChild(e);for(let t in n){var s=this.createElement("a");n[t]instanceof Function&&s.addEventListener("click",e=>{n[t](),e.preventDefault()}),s.classList.add("ejs_button"),s.innerText=this.localization(t),i.appendChild(s)}return t?i.style.display="none":this.currentPopup=i,e}selectFile(){return new Promise((t,e)=>{var n=this.createElement("input");n.type="file",this.addEventListener(n,"change",e=>{t(e.target.files[0])}),n.click()})}isPopupOpen(){return"none"!==this.cheatMenu.style.display||"none"!==this.netplayMenu.style.display||"none"!==this.controlMenu.style.display||null!==this.currentPopup}isChild(e,t){var n;return!(!e||!t)&&(n=9===e.nodeType?e.documentElement:e,e===t||(n.contains?n.contains(t):e.compareDocumentPosition&&16&e.compareDocumentPosition(t)))}createBottomMenuBar(){this.elements.menu=this.createElement("div"),this.elements.menu.classList.add("ejs_menu_bar"),this.elements.menu.classList.add("ejs_menu_bar_hidden");let t=null,n=!1;const i=()=>{this.paused||this.settingsMenuOpen||this.elements.menu.classList.add("ejs_menu_bar_hidden")};this.addEventListener(this.elements.parent,"mousemove click",e=>{"touch"===e.pointerType||!this.started||n||document.pointerLockElement===this.canvas||this.isPopupOpen()||(clearTimeout(t),t=setTimeout(i,3e3),this.elements.menu.classList.remove("ejs_menu_bar_hidden"))}),this.addEventListener(this.elements.menu,"touchstart touchend",e=>{!this.started||this.isPopupOpen()||(clearTimeout(t),t=setTimeout(i,3e3),this.elements.menu.classList.remove("ejs_menu_bar_hidden"))}),this.menu={close:()=>{this.started&&(clearTimeout(t),this.elements.menu.classList.add("ejs_menu_bar_hidden"))},open:()=>{this.started&&(clearTimeout(t),t=setTimeout(i,3e3),this.elements.menu.classList.remove("ejs_menu_bar_hidden"))},toggle:()=>{this.started&&(clearTimeout(t),this.elements.menu.classList.contains("ejs_menu_bar_hidden")&&(t=setTimeout(i,3e3)),this.elements.menu.classList.toggle("ejs_menu_bar_hidden"))}},this.elements.parent.appendChild(this.elements.menu);let o;this.addEventListener(this.elements.parent,"mousedown touchstart",e=>{this.isChild(this.elements.menu,e.target)||this.isChild(this.elements.menuToggle,e.target)||!this.started||this.elements.menu.classList.contains("ejs_menu_bar_hidden")||this.isPopupOpen()||575<this.elements.parent.getBoundingClientRect().width||(clearTimeout(o),o=setTimeout(()=>{n=!1},2e3),n=!0,this.menu.close())});var e=(e,t,n,i,o)=>{var s=this.createElement("button"),a=(s.type="button",document.createElementNS("http://www.w3.org/2000/svg","svg")),t=(a.setAttribute("role","presentation"),a.setAttribute("focusable","false"),a.innerHTML=t,this.createElement("span"));return t.innerText=this.localization(e),t.classList.add("ejs_menu_text"),s.classList.add("ejs_menu_button"),s.appendChild(a),s.appendChild(t),(i||this.elements.menu).appendChild(s),n instanceof Function&&this.addEventListener(s,"click",n),o?[s,a,t]:s},s=e("Restart",'<svg viewBox="0 0 512 512"><path d="M496 48V192c0 17.69-14.31 32-32 32H320c-17.69 0-32-14.31-32-32s14.31-32 32-32h63.39c-29.97-39.7-77.25-63.78-127.6-63.78C167.7 96.22 96 167.9 96 256s71.69 159.8 159.8 159.8c34.88 0 68.03-11.03 95.88-31.94c14.22-10.53 34.22-7.75 44.81 6.375c10.59 14.16 7.75 34.22-6.375 44.81c-39.03 29.28-85.36 44.86-134.2 44.86C132.5 479.9 32 379.4 32 256s100.5-223.9 223.9-223.9c69.15 0 134 32.47 176.1 86.12V48c0-17.69 14.31-32 32-32S496 30.31 496 48z"/></svg>',()=>{this.isNetplay&&this.netplay.owner?(this.gameManager.saveSaveFiles(),this.gameManager.restart(),this.netplay.sendMessage({restart:!0}),this.netplay.current_frame=0,this.play()):this.isNetplay||(this.gameManager.saveSaveFiles(),this.gameManager.restart())});const a=e("Pause",'<svg viewBox="0 0 320 512"><path d="M272 63.1l-32 0c-26.51 0-48 21.49-48 47.1v288c0 26.51 21.49 48 48 48L272 448c26.51 0 48-21.49 48-48v-288C320 85.49 298.5 63.1 272 63.1zM80 63.1l-32 0c-26.51 0-48 21.49-48 48v288C0 426.5 21.49 448 48 448l32 0c26.51 0 48-21.49 48-48v-288C128 85.49 106.5 63.1 80 63.1z"/></svg>',()=>{this.isNetplay&&this.netplay.owner?(this.pause(),this.netplay.sendMessage({pause:!0})):this.isNetplay||this.pause()}),r=e("Play",'<svg viewBox="0 0 320 512"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z"/></svg>',()=>{this.isNetplay&&this.netplay.owner?(this.play(),this.netplay.sendMessage({play:!0})):this.isNetplay||this.play()});r.style.display="none",this.togglePlaying=e=>{this.paused=!this.paused,e||(this.paused?(a.style.display="none",r.style.display=""):(a.style.display="",r.style.display="none")),this.gameManager.toggleMainLoop(this.paused?0:1),"nds"===this.getCore(!0)&&(this.canvas.exitPointerLock?this.canvas.exitPointerLock():this.canvas.mozExitPointerLock&&this.canvas.mozExitPointerLock())},this.play=e=>{this.paused&&this.togglePlaying(e)},this.pause=e=>{this.paused||this.togglePlaying(e)};let l;var c=e("Save State",'<svg viewBox="0 0 448 512"><path fill="currentColor" d="M433.941 129.941l-83.882-83.882A48 48 0 0 0 316.118 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V163.882a48 48 0 0 0-14.059-33.941zM224 416c-35.346 0-64-28.654-64-64 0-35.346 28.654-64 64-64s64 28.654 64 64c0 35.346-28.654 64-64 64zm96-304.52V212c0 6.627-5.373 12-12 12H76c-6.627 0-12-5.373-12-12V108c0-6.627 5.373-12 12-12h228.52c3.183 0 6.235 1.264 8.485 3.515l3.48 3.48A11.996 11.996 0 0 1 320 111.48z"/></svg>',async()=>{var e=await this.gameManager.getState();0<this.callEvent("save",{screenshot:this.gameManager.screenshot(),state:e})||(l&&URL.revokeObjectURL(l),"browser"===this.settings["save-state-location"]&&this.saveInBrowserSupported()?(this.storage.states.put(this.getBaseFileName()+".state",e),this.displayMessage(this.localization("SAVE SAVED TO BROWSER"))):(e=new Blob([e]),l=URL.createObjectURL(e),(e=this.createElement("a")).href=l,e.download=this.getBaseFileName()+".state",e.click()))}),h=e("Load State",'<svg viewBox="0 0 576 512"><path fill="currentColor" d="M572.694 292.093L500.27 416.248A63.997 63.997 0 0 1 444.989 448H45.025c-18.523 0-30.064-20.093-20.731-36.093l72.424-124.155A64 64 0 0 1 152 256h399.964c18.523 0 30.064 20.093 20.73 36.093zM152 224h328v-48c0-26.51-21.49-48-48-48H272l-64-64H48C21.49 64 0 85.49 0 112v278.046l69.077-118.418C86.214 242.25 117.989 224 152 224z"/></svg>',async()=>{var e;0<this.callEvent("load")||("browser"===this.settings["save-state-location"]&&this.saveInBrowserSupported()?this.storage.states.get(this.getBaseFileName()+".state").then(e=>{this.gameManager.loadState(e),this.displayMessage(this.localization("SAVE LOADED FROM BROWSER"))}):(e=await this.selectFile(),e=new Uint8Array(await e.arrayBuffer()),this.gameManager.loadState(e)))}),d=e("Control Settings",'<svg viewBox="0 0 640 512"><path fill="currentColor" d="M480 96H160C71.6 96 0 167.6 0 256s71.6 160 160 160c44.8 0 85.2-18.4 114.2-48h91.5c29 29.6 69.5 48 114.2 48 88.4 0 160-71.6 160-160S568.4 96 480 96zM256 276c0 6.6-5.4 12-12 12h-52v52c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-52H76c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h52v-52c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h52c6.6 0 12 5.4 12 12v40zm184 68c-26.5 0-48-21.5-48-48s21.5-48 48-48 48 21.5 48 48-21.5 48-48 48zm80-80c-26.5 0-48-21.5-48-48s21.5-48 48-48 48 21.5 48 48-21.5 48-48 48z"/></svg>',()=>{this.controlMenu.style.display=""}),u=e("Cheats",'<svg viewBox="0 0 496 512"><path fill="currentColor" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z" class=""></path></svg>',()=>{this.cheatMenu.style.display=""}),p=e("Cache Manager",'<svg viewBox="0 0 1800 1800"><path d="M896 768q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5T231 896 128 768V598q119 84 325 127t443 43zm0 768q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128v-170q119 84 325 127t443 43zm0-384q237 0 443-43t325-127v170q0 69-103 128t-280 93.5-385 34.5-385-34.5-280-93.5-103-128V982q119 84 325 127t443 43zM896 0q208 0 385 34.5t280 93.5 103 128v128q0 69-103 128t-280 93.5T896 640t-385-34.5T231 512 128 384V256q0-69 103-128t280-93.5T896 0z"/></svg>',()=>{this.openCacheMenu()});let f;var m=e("Export Save File",'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 23 23"><path d="M3 6.5V5C3 3.89543 3.89543 3 5 3H16.1716C16.702 3 17.2107 3.21071 17.5858 3.58579L20.4142 6.41421C20.7893 6.78929 21 7.29799 21 7.82843V19C21 20.1046 20.1046 21 19 21H5C3.89543 21 3 20.1046 3 19V17.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" fill="transparent"></path><path d="M8 3H16V8.4C16 8.73137 15.7314 9 15.4 9H8.6C8.26863 9 8 8.73137 8 8.4V3Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" fill="transparent"></path><path d="M18 21V13.6C18 13.2686 17.7314 13 17.4 13H15" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" fill="transparent"></path><path d="M6 21V17.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" fill="transparent"></path><path d="M12 12H1M1 12L4 9M1 12L4 15" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path></svg>',async()=>{var e=await this.gameManager.getSaveFile(),e=new Blob([e]),e=(f=URL.createObjectURL(e),this.createElement("a"));e.href=f,e.download=this.gameManager.getSaveFilePath().split("/").pop(),e.click()}),y=e("Import Save File",'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 23 23"><path d="M3 7.5V5C3 3.89543 3.89543 3 5 3H16.1716C16.702 3 17.2107 3.21071 17.5858 3.58579L20.4142 6.41421C20.7893 6.78929 21 7.29799 21 7.82843V19C21 20.1046 20.1046 21 19 21H5C3.89543 21 3 20.1046 3 19V16.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" fill="transparent"></path><path d="M6 21V17" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M18 21V13.6C18 13.2686 17.7314 13 17.4 13H15" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" fill="transparent"></path><path d="M16 3V8.4C16 8.73137 15.7314 9 15.4 9H13.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" fill="transparent"></path><path d="M8 3V6" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M1 12H12M12 12L9 9M12 12L9 15" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path></svg>',async()=>{var e=await this.selectFile(),e=new Uint8Array(await e.arrayBuffer()),t=this.gameManager.getSaveFilePath(),n=t.split("/");let i="";for(let e=0;e<n.length-1;e++)""===n[e]||(i+="/"+n[e],FS.analyzePath(i).exists)||FS.mkdir(i);FS.analyzePath(t).exists&&FS.unlink(t),FS.writeFile(t,e),this.gameManager.loadSaveFiles()}),g=e("Netplay",'<svg viewBox="0 0 512 512"><path fill="currentColor" d="M364.215 192h131.43c5.439 20.419 8.354 41.868 8.354 64s-2.915 43.581-8.354 64h-131.43c5.154-43.049 4.939-86.746 0-128zM185.214 352c10.678 53.68 33.173 112.514 70.125 151.992.221.001.44.008.661.008s.44-.008.661-.008c37.012-39.543 59.467-98.414 70.125-151.992H185.214zm174.13-192h125.385C452.802 84.024 384.128 27.305 300.95 12.075c30.238 43.12 48.821 96.332 58.394 147.925zm-27.35 32H180.006c-5.339 41.914-5.345 86.037 0 128h151.989c5.339-41.915 5.345-86.037-.001-128zM152.656 352H27.271c31.926 75.976 100.6 132.695 183.778 147.925-30.246-43.136-48.823-96.35-58.393-147.925zm206.688 0c-9.575 51.605-28.163 104.814-58.394 147.925 83.178-15.23 151.852-71.949 183.778-147.925H359.344zm-32.558-192c-10.678-53.68-33.174-112.514-70.125-151.992-.221 0-.44-.008-.661-.008s-.44.008-.661.008C218.327 47.551 195.872 106.422 185.214 160h141.572zM16.355 192C10.915 212.419 8 233.868 8 256s2.915 43.581 8.355 64h131.43c-4.939-41.254-5.154-84.951 0-128H16.355zm136.301-32c9.575-51.602 28.161-104.81 58.394-147.925C127.872 27.305 59.198 84.024 27.271 160h125.385z"/></svg>',async()=>{this.openNetplayMenu()}),v=this.createElement("span"),v=(v.classList.add("ejs_menu_bar_spacer"),this.elements.menu.appendChild(v),this.createElement("div"));v.classList.add("ejs_volume_parent");const _=e("Mute",'<svg viewBox="0 0 640 512"><path d="M412.6 182c-10.28-8.334-25.41-6.867-33.75 3.402c-8.406 10.24-6.906 25.35 3.375 33.74C393.5 228.4 400 241.8 400 255.1c0 14.17-6.5 27.59-17.81 36.83c-10.28 8.396-11.78 23.5-3.375 33.74c4.719 5.806 11.62 8.802 18.56 8.802c5.344 0 10.75-1.779 15.19-5.399C435.1 311.5 448 284.6 448 255.1S435.1 200.4 412.6 182zM473.1 108.2c-10.22-8.334-25.34-6.898-33.78 3.34c-8.406 10.24-6.906 25.35 3.344 33.74C476.6 172.1 496 213.3 496 255.1s-19.44 82.1-53.31 110.7c-10.25 8.396-11.75 23.5-3.344 33.74c4.75 5.775 11.62 8.771 18.56 8.771c5.375 0 10.75-1.779 15.22-5.431C518.2 366.9 544 313 544 255.1S518.2 145 473.1 108.2zM534.4 33.4c-10.22-8.334-25.34-6.867-33.78 3.34c-8.406 10.24-6.906 25.35 3.344 33.74C559.9 116.3 592 183.9 592 255.1s-32.09 139.7-88.06 185.5c-10.25 8.396-11.75 23.5-3.344 33.74C505.3 481 512.2 484 519.2 484c5.375 0 10.75-1.779 15.22-5.431C601.5 423.6 640 342.5 640 255.1S601.5 88.34 534.4 33.4zM301.2 34.98c-11.5-5.181-25.01-3.076-34.43 5.29L131.8 160.1H48c-26.51 0-48 21.48-48 47.96v95.92c0 26.48 21.49 47.96 48 47.96h83.84l134.9 119.8C272.7 477 280.3 479.8 288 479.8c4.438 0 8.959-.9314 13.16-2.835C312.7 471.8 320 460.4 320 447.9V64.12C320 51.55 312.7 40.13 301.2 34.98z"/></svg>',()=>{_.style.display="none",T.style.display="",this.muted=!0,this.setVolume(0)},v),T=e("Unmute",'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M301.2 34.85c-11.5-5.188-25.02-3.122-34.44 5.253L131.8 160H48c-26.51 0-48 21.49-48 47.1v95.1c0 26.51 21.49 47.1 48 47.1h83.84l134.9 119.9c5.984 5.312 13.58 8.094 21.26 8.094c4.438 0 8.972-.9375 13.17-2.844c11.5-5.156 18.82-16.56 18.82-29.16V64C319.1 51.41 312.7 40 301.2 34.85zM513.9 255.1l47.03-47.03c9.375-9.375 9.375-24.56 0-33.94s-24.56-9.375-33.94 0L480 222.1L432.1 175c-9.375-9.375-24.56-9.375-33.94 0s-9.375 24.56 0 33.94l47.03 47.03l-47.03 47.03c-9.375 9.375-9.375 24.56 0 33.94c9.373 9.373 24.56 9.381 33.94 0L480 289.9l47.03 47.03c9.373 9.373 24.56 9.381 33.94 0c9.375-9.375 9.375-24.56 0-33.94L513.9 255.1z"/></svg>',()=>{0===this.volume&&(this.volume=.5),_.style.display="",T.style.display="none",this.muted=!1,this.setVolume(this.volume)},v),b=(T.style.display="none",this.createElement("input")),w=(b.setAttribute("data-range","volume"),b.setAttribute("type","range"),b.setAttribute("min",0),b.setAttribute("max",1),b.setAttribute("step",.01),b.setAttribute("autocomplete","off"),b.setAttribute("role","slider"),b.setAttribute("aria-label","Volume"),b.setAttribute("aria-valuemin",0),b.setAttribute("aria-valuemax",100),this.setVolume=t=>{this.saveSettings(),this.muted=0===t,b.value=t,b.setAttribute("aria-valuenow",100*t),b.setAttribute("aria-valuetext",(100*t).toFixed(1)+"%"),b.setAttribute("style","--value: "+100*t+"%;margin-left: 5px;position: relative;z-index: 2;"),window.AL&&AL.currentCtx&&AL.currentCtx.sources&&AL.currentCtx.sources.forEach(e=>{e.gain.gain.value=t}),T.style.display=0===t?"":"none",_.style.display=0===t?"none":""},this.muted||this.setVolume(this.volume),this.addEventListener(b,"change mousemove touchmove mousedown touchstart mouseup",e=>{setTimeout(()=>{var e=parseFloat(b.value);0===e&&this.muted||(this.volume=e,this.setVolume(this.volume))},5)}),v.appendChild(b),this.elements.menu.appendChild(v),this.settingParent=this.createElement("div"),this.settingsMenuOpen=!1,e("Settings",'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M495.9 166.6C499.2 175.2 496.4 184.9 489.6 191.2L446.3 230.6C447.4 238.9 448 247.4 448 256C448 264.6 447.4 273.1 446.3 281.4L489.6 320.8C496.4 327.1 499.2 336.8 495.9 345.4C491.5 357.3 486.2 368.8 480.2 379.7L475.5 387.8C468.9 398.8 461.5 409.2 453.4 419.1C447.4 426.2 437.7 428.7 428.9 425.9L373.2 408.1C359.8 418.4 344.1 427 329.2 433.6L316.7 490.7C314.7 499.7 307.7 506.1 298.5 508.5C284.7 510.8 270.5 512 255.1 512C241.5 512 227.3 510.8 213.5 508.5C204.3 506.1 197.3 499.7 195.3 490.7L182.8 433.6C167 427 152.2 418.4 138.8 408.1L83.14 425.9C74.3 428.7 64.55 426.2 58.63 419.1C50.52 409.2 43.12 398.8 36.52 387.8L31.84 379.7C25.77 368.8 20.49 357.3 16.06 345.4C12.82 336.8 15.55 327.1 22.41 320.8L65.67 281.4C64.57 273.1 64 264.6 64 256C64 247.4 64.57 238.9 65.67 230.6L22.41 191.2C15.55 184.9 12.82 175.3 16.06 166.6C20.49 154.7 25.78 143.2 31.84 132.3L36.51 124.2C43.12 113.2 50.52 102.8 58.63 92.95C64.55 85.8 74.3 83.32 83.14 86.14L138.8 103.9C152.2 93.56 167 84.96 182.8 78.43L195.3 21.33C197.3 12.25 204.3 5.04 213.5 3.51C227.3 1.201 241.5 0 256 0C270.5 0 284.7 1.201 298.5 3.51C307.7 5.04 314.7 12.25 316.7 21.33L329.2 78.43C344.1 84.96 359.8 93.56 373.2 103.9L428.9 86.14C437.7 83.32 447.4 85.8 453.4 92.95C461.5 102.8 468.9 113.2 475.5 124.2L480.2 132.3C486.2 143.2 491.5 154.7 495.9 166.6V166.6zM256 336C300.2 336 336 300.2 336 255.1C336 211.8 300.2 175.1 256 175.1C211.8 175.1 176 211.8 176 255.1C176 300.2 211.8 336 256 336z"/></svg>',()=>{this.settingsMenuOpen=!this.settingsMenuOpen,w[1].classList.toggle("ejs_svg_rotate",this.settingsMenuOpen),this.settingsMenu.style.display=this.settingsMenuOpen?"":"none",w[2].classList.toggle("ejs_settings_text",this.settingsMenuOpen)},this.settingParent,!0)),x=(this.elements.menu.appendChild(this.settingParent),this.closeSettingsMenu=()=>{this.settingsMenu&&(this.settingsMenuOpen=!1,w[1].classList.toggle("ejs_svg_rotate",this.settingsMenuOpen),w[2].classList.toggle("ejs_settings_text",this.settingsMenuOpen),this.settingsMenu.style.display="none")},this.addEventListener(this.elements.parent,"mousedown touchstart",e=>{this.isChild(this.settingsMenu,e.target)||"touch"!==e.pointerType&&e.target!==w[0]&&e.target!==w[2]&&this.closeSettingsMenu()}),this.addEventListener(this.canvas,"click",e=>{"touch"===e.pointerType||"nds"!==this.getCore(!0)||this.paused||(this.canvas.requestPointerLock?this.canvas.requestPointerLock():this.canvas.mozRequestPointerLock&&this.canvas.mozRequestPointerLock(),this.menu.close())}),e("Enter Fullscreen",'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M208 281.4c-12.5-12.5-32.76-12.5-45.26-.002l-78.06 78.07l-30.06-30.06c-6.125-6.125-14.31-9.367-22.63-9.367c-4.125 0-8.279 .7891-12.25 2.43c-11.97 4.953-19.75 16.62-19.75 29.56v135.1C.0013 501.3 10.75 512 24 512h136c12.94 0 24.63-7.797 29.56-19.75c4.969-11.97 2.219-25.72-6.938-34.87l-30.06-30.06l78.06-78.07c12.5-12.49 12.5-32.75 .002-45.25L208 281.4zM487.1 0h-136c-12.94 0-24.63 7.797-29.56 19.75c-4.969 11.97-2.219 25.72 6.938 34.87l30.06 30.06l-78.06 78.07c-12.5 12.5-12.5 32.76 0 45.26l22.62 22.62c12.5 12.5 32.76 12.5 45.26 0l78.06-78.07l30.06 30.06c9.156 9.141 22.87 11.84 34.87 6.937C504.2 184.6 512 172.9 512 159.1V23.1C512 10.74 501.3 0 487.1 0z"/></svg>',()=>{if(this.elements.parent.requestFullscreen?this.elements.parent.requestFullscreen():this.elements.parent.mozRequestFullScreen?this.elements.parent.mozRequestFullScreen():this.elements.parent.webkitRequestFullscreen?this.elements.parent.webkitRequestFullscreen():this.elements.parent.msRequestFullscreen&&this.elements.parent.msRequestFullscreen(),E.style.display="",x.style.display="none",this.isMobile)try{screen.orientation.lock("nds"===this.getCore(!0)?"portrait":"landscape").catch(e=>{})}catch(e){}})),E=e("Exit Fullscreen",'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M215.1 272h-136c-12.94 0-24.63 7.797-29.56 19.75C45.47 303.7 48.22 317.5 57.37 326.6l30.06 30.06l-78.06 78.07c-12.5 12.5-12.5 32.75-.0012 45.25l22.62 22.62c12.5 12.5 32.76 12.5 45.26 .0013l78.06-78.07l30.06 30.06c6.125 6.125 14.31 9.367 22.63 9.367c4.125 0 8.279-.7891 12.25-2.43c11.97-4.953 19.75-16.62 19.75-29.56V296C239.1 282.7 229.3 272 215.1 272zM296 240h136c12.94 0 24.63-7.797 29.56-19.75c4.969-11.97 2.219-25.72-6.938-34.87l-30.06-30.06l78.06-78.07c12.5-12.5 12.5-32.76 .0002-45.26l-22.62-22.62c-12.5-12.5-32.76-12.5-45.26-.0003l-78.06 78.07l-30.06-30.06c-9.156-9.141-22.87-11.84-34.87-6.937c-11.97 4.953-19.75 16.62-19.75 29.56v135.1C272 229.3 282.7 240 296 240z"/></svg>',()=>{if(document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.msExitFullscreen&&document.msExitFullscreen(),E.style.display="none",x.style.display="",this.isMobile)try{screen.orientation.unlock()}catch(e){}});E.style.display="none",this.addEventListener(document,"webkitfullscreenchange mozfullscreenchange fullscreenchange",e=>{e.target===this.elements.parent&&(null===document.fullscreenElement?(E.style.display="none",x.style.display=""):(E.style.display="",x.style.display="none"))}),this.elements.parent.requestFullscreen||this.elements.parent.mozRequestFullScreen||this.elements.parent.webkitRequestFullscreen||this.elements.parent.msRequestFullscreen||(E.style.display="none",x.style.display="none"),this.elements.bottomBar={playPause:[a,r],restart:[s],settings:[w],fullscreen:[x,E],saveState:[c],loadState:[h],gamepad:[d],cheat:[u],cacheManager:[p],saveSavFiles:[m],loadSavFiles:[y],netplay:[g]},this.config.buttonOpts&&(this.debug&&console.log(this.config.buttonOpts),!1===this.config.buttonOpts.playPause&&(a.style.display="none",r.style.display="none"),!1===this.config.buttonOpts.restart&&(s.style.display="none"),!1===this.config.buttonOpts.settings&&(w[0].style.display="none"),!1===this.config.buttonOpts.fullscreen&&(x.style.display="none",E.style.display="none"),!1===this.config.buttonOpts.saveState&&(c.style.display="none"),!1===this.config.buttonOpts.loadState&&(h.style.display="none"),!1===this.config.buttonOpts.saveSavFiles&&(m.style.display="none"),!1===this.config.buttonOpts.loadSavFiles&&(y.style.display="none"),!1===this.config.buttonOpts.gamepad&&(d.style.display="none"),!1===this.config.buttonOpts.cheat&&(u.style.display="none"),!1===this.config.buttonOpts.cacheManager&&(p.style.display="none"),!1===this.config.buttonOpts.netplay)&&(g.style.display="none")}openCacheMenu(){(async()=>{var e=this.createElement("table");const t=this.createElement("tbody");var n=this.createPopup("Cache Manager",{"Clear All":async()=>{for(const e in await this.storage.rom.getSizes())await this.storage.rom.remove(e);t.innerHTML=""},Close:()=>{this.closePopup()}}),i=await this.storage.rom.getSizes();e.style.width="100%",e.style["padding-left"]="10px",e.style["text-align"]="left",n.appendChild(e),e.appendChild(t);for(const l in i){const c=this.createElement("tr");var o=this.createElement("td"),s=this.createElement("td"),a=this.createElement("td"),r=(a.style.cursor="pointer",o.innerText=l,s.innerText=function(e){let t=-1;for(;e/=1024,t++,1024<e;);return Math.max(e,.1).toFixed(1)+[" kB"," MB"," GB"," TB","PB","EB","ZB","YB"][t]}(i[l]),this.createElement("a"));r.innerText=this.localization("Remove"),this.addEventListener(a,"click",()=>{this.storage.rom.remove(l),c.remove()}),a.appendChild(r),c.appendChild(o),c.appendChild(s),c.appendChild(a),t.appendChild(c)}})()}createControlSettingMenu(){let e=[];this.checkGamepadInputs=()=>e.forEach(e=>e()),this.gamepadLabels=[],this.controls=JSON.parse(JSON.stringify(this.defaultControllers));var t=this.createPopup("Control Settings",{Reset:()=>{this.controls=JSON.parse(JSON.stringify(this.defaultControllers)),this.checkGamepadInputs(),this.saveSettings()},Clear:()=>{this.controls={0:{},1:{},2:{},3:{}},this.checkGamepadInputs(),this.saveSettings()},Close:()=>{this.controlMenu.style.display="none"}},!0);this.controlMenu=t.parentElement,t.classList.add("ejs_control_body");let n;n="nes"===this.getCore(!0)?{8:"A",0:"B",2:"SELECT",3:"START",4:"UP",5:"DOWN",6:"LEFT",7:"RIGHT",24:this.localization("QUICK SAVE STATE"),25:this.localization("QUICK LOAD STATE"),26:this.localization("CHANGE STATE SLOT")}:"snes"===this.getCore(!0)?{0:"B",1:"Y",2:"SELECT",3:"START",4:"UP",5:"DOWN",6:"LEFT",7:"RIGHT",8:"A",9:"X",10:"L",11:"R",24:this.localization("QUICK SAVE STATE"),25:this.localization("QUICK LOAD STATE"),26:this.localization("CHANGE STATE SLOT")}:"n64"===this.getCore(!0)?{0:"A",1:"B",3:"START",4:"UP",5:"DOWN",6:"LEFT",7:"RIGHT",10:"L",11:"R",12:"Z",19:"L STICK UP",18:"L STICK DOWN",17:"L STICK LEFT",16:"L STICK RIGHT",23:"R STICK UP",22:"R STICK DOWN",21:"R STICK LEFT",20:"R STICK RIGHT",24:this.localization("QUICK SAVE STATE"),25:this.localization("QUICK LOAD STATE"),26:this.localization("CHANGE STATE SLOT")}:"nds"===this.getCore(!0)?{0:"B",1:"Y",2:"SELECT",3:"START",4:"UP",5:"DOWN",6:"LEFT",7:"RIGHT",8:"A",9:"X",10:"L",11:"R",14:"Microphone",24:this.localization("QUICK SAVE STATE"),25:this.localization("QUICK LOAD STATE"),26:this.localization("CHANGE STATE SLOT")}:{0:"B",1:"Y",2:"SELECT",3:"START",4:"UP",5:"DOWN",6:"LEFT",7:"RIGHT",8:"A",9:"X",10:"L",11:"R",12:"L2",13:"R2",14:"L3",15:"R3",19:"L STICK UP",18:"L STICK DOWN",17:"L STICK LEFT",16:"L STICK RIGHT",23:"R STICK UP",22:"R STICK DOWN",21:"R STICK LEFT",20:"R STICK RIGHT",24:this.localization("QUICK SAVE STATE"),25:this.localization("QUICK LOAD STATE"),26:this.localization("CHANGE STATE SLOT")},["arcade","mame"].includes(this.getCore(!0))&&(n[2]=this.localization("INSERT COIN"));let i,o=[],s=[];var a=this.createElement("ul");a.classList.add("ejs_control_player_bar");for(let t=1;t<5;t++){var r=this.createElement("li"),l=(r.classList.add("tabs-title"),r.setAttribute("role","presentation"),this.createElement("a"));l.innerText=this.localization("Player")+" "+t,l.setAttribute("role","tab"),l.setAttribute("aria-controls","controls-"+(t-1)),l.setAttribute("aria-selected","false"),l.id="controls-"+(t-1)+"-label",this.addEventListener(l,"click",e=>{e.preventDefault(),o[i].classList.remove("ejs_control_selected"),s[i].setAttribute("hidden",""),i=t-1,o[t-1].classList.add("ejs_control_selected"),s[t-1].removeAttribute("hidden")}),r.appendChild(l),a.appendChild(r),o.push(r)}t.appendChild(a);var c=this.createElement("div");for(let t=0;t<4;t++){this.controls[t]||(this.controls[t]={});var h=this.createElement("div"),d=this.createElement("div"),u=this.createElement("div"),p=(u.style="font-size:12px;",u.innerText=this.localization("Connected Gamepad")+": ",this.createElement("span")),p=(this.gamepadLabels.push(p),p.innerText="n/a",u.appendChild(p),this.createElement("div")),f=(p.style="width:25%;float:left;",p.innerHTML="&nbsp;",this.createElement("div")),m=(f.style="font-size:12px;width:50%;float:left;",this.createElement("div")),m=(m.style="text-align:center;width:50%;float:left;",m.innerText=this.localization("Gamepad"),f.appendChild(m),this.createElement("div")),m=(m.style="text-align:center;width:50%;float:left;",m.innerText=this.localization("Keyboard"),f.appendChild(m),this.createElement("div"));m.style="clear:both;",d.appendChild(u),d.appendChild(p),d.appendChild(f),d.appendChild(m),h.appendChild(d);for(const E in n){var y=this.createElement("div"),g=(y.setAttribute("data-id",E),y.setAttribute("data-index",t),y.setAttribute("data-label",n[E]),y.style="margin-bottom:10px;",y.classList.add("ejs_control_bar"),this.createElement("div")),v=(g.style="width:25%;float:left;font-size:12px;",this.createElement("label")),v=(v.innerText=n[E]+":",g.appendChild(v),this.createElement("div")),_=(v.style="width:50%;float:left;",this.createElement("div"));_.style="width:50%;float:left;padding: 0 5px;";const C=this.createElement("input");C.style="text-align:center;height:25px;width: 100%;",C.type="text",C.setAttribute("readonly",""),C.setAttribute("placeholder",""),_.appendChild(C);var T=this.createElement("div");T.style="width:50%;float:left;padding: 0 5px;";const S=this.createElement("input");S.style="text-align:center;height:25px;width: 100%;",S.type="text",S.setAttribute("readonly",""),S.setAttribute("placeholder",""),T.appendChild(S),e.push(()=>{S.value="",C.value="",this.controls[t][E]&&void 0!==this.controls[t][E].value&&(S.value=this.controls[t][E].value),this.controls[t][E]&&void 0!==this.controls[t][E].value2&&(C.value=this.controls[t][E].value2)}),this.controls[t][E]&&this.controls[t][E].value&&(S.value=this.controls[t][E].value),this.controls[t][E]&&this.controls[t][E].value2&&(C.value="button "+this.controls[t][E].value2),v.appendChild(_),v.appendChild(T);_=this.createElement("div"),T=(_.style="clear:both;",v.appendChild(_),this.createElement("div")),_=(T.style="width:25%;float:left;",this.createElement("a")),_=(_.classList.add("ejs_control_set_button"),_.innerText=this.localization("Set"),T.appendChild(_),this.createElement("div"));_.style="clear:both;",y.appendChild(g),y.appendChild(v),y.appendChild(T),y.appendChild(_),h.appendChild(y),this.addEventListener(y,"mousedown",e=>{e.preventDefault(),this.controlPopup.parentElement.parentElement.removeAttribute("hidden"),this.controlPopup.innerText="[ "+n[E]+" ]\n"+this.localization("Press Keyboard"),this.controlPopup.setAttribute("button-num",E),this.controlPopup.setAttribute("player-num",t)})}c.appendChild(h),h.setAttribute("hidden",""),s.push(h)}t.appendChild(c),i=0,o[0].classList.add("ejs_control_selected"),s[0].removeAttribute("hidden");t=this.createElement("div");t.classList.add("ejs_popup_container");const b=this.createElement("div");this.addEventListener(t,"mousedown click touchstart",e=>{this.isChild(b,e.target)||this.controlPopup.parentElement.parentElement.setAttribute("hidden","")});var w=this.createElement("a"),x=(w.classList.add("ejs_control_set_button"),w.innerText=this.localization("Clear"),this.addEventListener(w,"mousedown click touchstart",e=>{var t=this.controlPopup.getAttribute("button-num"),n=this.controlPopup.getAttribute("player-num");this.controls[n][t]||(this.controls[n][t]={}),this.controls[n][t].value="",this.controls[n][t].value2="",this.controlPopup.parentElement.parentElement.setAttribute("hidden",""),this.checkGamepadInputs(),this.saveSettings()}),b.classList.add("ejs_popup_box"),b.innerText="",t.setAttribute("hidden",""),this.createElement("div"));this.controlPopup=x,t.appendChild(b),b.appendChild(x),b.appendChild(this.createElement("br")),b.appendChild(w),this.controlMenu.appendChild(t)}defaultControllers={0:{0:{value:"x"},1:{value:"s"},2:{value:"v"},3:{value:"enter"},4:{value:"arrowup"},5:{value:"arrowdown"},6:{value:"arrowleft"},7:{value:"arrowright"},8:{value:"z"},9:{value:"a"},10:{value:"q"},11:{value:"e"},12:{value:"e"},13:{value:"w"},14:{},15:{},16:{value:"h"},17:{value:"f"},18:{value:"g"},19:{value:"t"},20:{value:"l"},21:{value:"j"},22:{value:"k"},23:{value:"i"},24:{},25:{},26:{}},1:{},2:{},3:{}};controls;keyChange(n){var e,t;if(!n.repeat&&this.started)if(null===this.controlPopup.parentElement.parentElement.getAttribute("hidden"))e=this.controlPopup.getAttribute("button-num"),t=this.controlPopup.getAttribute("player-num"),this.controls[t][e]||(this.controls[t][e]={}),this.controls[t][e].value=n.key.toLowerCase(),this.controlPopup.parentElement.parentElement.setAttribute("hidden",""),this.checkGamepadInputs(),this.saveSettings();else if("none"===this.settingsMenu.style.display&&!this.isPopupOpen()){n.preventDefault();var i=[16,17,18,19,20,21,22,23];for(let t=0;t<4;t++)for(let e=0;e<27;e++)this.controls[t][e]&&this.controls[t][e].value===n.key.toLowerCase()&&this.gameManager.simulateInput(t,e,"keyup"===n.type?0:i.includes(e)?32767:1)}}gamepadEvent(n){if(this.started){var e,t,i=.5<(e=n.value||0)||e<-.5?0<e?1:-1:0;if(null===this.controlPopup.parentElement.parentElement.getAttribute("hidden"))return"buttonup"===n.type||"axischanged"===n.type&&0==i?void 0:(e=this.controlPopup.getAttribute("button-num"),t=this.controlPopup.getAttribute("player-num"),this.controls[t][e]||(this.controls[t][e]={}),this.controls[t][e].value2="axischanged"===n.type?n.axis+":"+i:n.index,this.controlPopup.parentElement.parentElement.setAttribute("hidden",""),this.checkGamepadInputs(),void this.saveSettings());if("none"===this.settingsMenu.style.display&&!this.isPopupOpen()){var o=[16,17,18,19,20,21,22,23];for(let t=0;t<4;t++)for(let e=0;e<27;e++)["buttonup","buttondown"].includes(n.type)&&this.controls[t][e]&&this.controls[t][e].value2===n.index?this.gameManager.simulateInput(t,e,"buttondown"===n.type?0:o.includes(e)?32767:1):"axischanged"===n.type&&this.controls[t][e]&&"string"==typeof this.controls[t][e].value2&&this.controls[t][e].value2.split(":")[0]===n.axis&&(o.includes(e)?"LEFT_STICK_X"===n.axis?0<n.value?(this.gameManager.simulateInput(n.gamepadIndex,16,32767*n.value),this.gameManager.simulateInput(n.gamepadIndex,17,0)):(this.gameManager.simulateInput(n.gamepadIndex,17,-32767*n.value),this.gameManager.simulateInput(n.gamepadIndex,16,0)):"LEFT_STICK_Y"===n.axis?0<n.value?(this.gameManager.simulateInput(n.gamepadIndex,18,32767*n.value),this.gameManager.simulateInput(n.gamepadIndex,19,0)):(this.gameManager.simulateInput(n.gamepadIndex,19,-32767*n.value),this.gameManager.simulateInput(n.gamepadIndex,18,0)):"RIGHT_STICK_X"===n.axis?0<n.value?(this.gameManager.simulateInput(n.gamepadIndex,20,32767*n.value),this.gameManager.simulateInput(n.gamepadIndex,21,0)):(this.gameManager.simulateInput(n.gamepadIndex,21,-32767*n.value),this.gameManager.simulateInput(n.gamepadIndex,20,0)):"RIGHT_STICK_Y"===n.axis&&(0<n.value?(this.gameManager.simulateInput(n.gamepadIndex,22,32767*n.value),this.gameManager.simulateInput(n.gamepadIndex,23,0)):(this.gameManager.simulateInput(n.gamepadIndex,23,32767*n.value),this.gameManager.simulateInput(n.gamepadIndex,22,0))):this.controls[t][e].value2!==n.axis+":"+i&&0!=i||this.gameManager.simulateInput(t,e,0==i?0:1))}}}setVirtualGamepad(){this.virtualGamepad=this.createElement("div"),this.toggleVirtualGamepad=e=>{this.virtualGamepad.style.display=e?"":"none"},this.virtualGamepad.classList.add("ejs_virtualGamepad_parent"),this.elements.parent.appendChild(this.virtualGamepad);let n;n=this.config.VirtualGamepadSettings&&function(t){if(Array.isArray(t)){if(t.length){for(let e=0;e<t.length;e++)if(t[e].type)try{if("zone"===t[e].type||"dpad"===t[e].type){if(!t[e].location)return void console.warn("Missing location value for "+t[e].type+"! Using default gamepad settings");if(t[e].inputValues)continue;return void console.warn("Missing inputValues for "+t[e].type+"! Using default gamepad settings")}if(!t[e].location)return void console.warn("Missing location value for button "+t[e].text+"! Using default gamepad settings");if(!t[e].type)return void console.warn("Missing type value for button "+t[e].text+"! Using default gamepad settings");if(!t[e].id.toString())return void console.warn("Missing id value for button "+t[e].text+"! Using default gamepad settings");if(!t[e].input_value.toString())return void console.warn("Missing input_value for button "+t[e].text+"! Using default gamepad settings")}catch(e){return void console.warn("Error checking values! Using default gamepad settings")}return 1}console.warn("Virtual gamepad settings is empty! Using default gamepad settings")}else console.warn("Vritual gamepad settings is not array! Using default gamepad settings")}(this.config.VirtualGamepadSettings)?this.config.VirtualGamepadSettings:"gba"===this.getCore(!0)?[{type:"button",text:"A",id:"a",location:"right",left:81,top:40,bold:!0,input_value:8},{type:"button",text:"B",id:"b",location:"right",left:10,top:70,bold:!0,input_value:0},{type:"dpad",location:"left",left:"50%",top:"50%",joystickInput:!1,inputValues:[4,5,6,7]},{type:"button",text:"Start",id:"start",location:"center",left:60,fontSize:15,block:!0,input_value:3},{type:"button",text:"Select",id:"select",location:"center",left:-5,fontSize:15,block:!0,input_value:2},{type:"button",text:"L",id:"l",location:"left",left:3,top:-100,bold:!0,block:!0,input_value:10},{type:"button",text:"R",id:"r",location:"right",right:3,top:-100,bold:!0,block:!0,input_value:11}]:"gb"===this.getCore(!0)?[{type:"button",text:"A",id:"a",location:"right",left:81,top:40,bold:!0,input_value:8},{type:"button",text:"B",id:"b",location:"right",left:10,top:70,bold:!0,input_value:0},{type:"dpad",location:"left",left:"50%",top:"50%",joystickInput:!1,inputValues:[4,5,6,7]},{type:"button",text:"Start",id:"start",location:"center",left:60,fontSize:15,block:!0,input_value:3},{type:"button",text:"Select",id:"select",location:"center",left:-5,fontSize:15,block:!0,input_value:2}]:["vb","nes"].includes(this.getCore(!0))?[{type:"button",text:"B",id:"b",location:"right",right:-10,top:70,bold:!0,input_value:0},{type:"button",text:"A",id:"a",location:"right",right:60,top:70,bold:!0,input_value:8},{type:"dpad",location:"left",left:"50%",right:"50%",joystickInput:!1,inputValues:[4,5,6,7]},{type:"button",text:"Start",id:"start",location:"center",left:60,fontSize:15,block:!0,input_value:3},{type:"button",text:"Select",id:"select",location:"center",left:-5,fontSize:15,block:!0,input_value:2}]:"n64"===this.getCore(!0)?[{type:"button",text:"B",id:"b",location:"right",left:-10,top:95,input_value:1,bold:!0},{type:"button",text:"A",id:"a",location:"right",left:40,top:150,input_value:0,bold:!0},{type:"zone",location:"left",left:"50%",top:"100%",joystickInput:!0,inputValues:[16,17,18,19]},{type:"zone",location:"left",left:"50%",top:"0%",joystickInput:!1,inputValues:[4,5,6,7]},{type:"button",text:"Start",id:"start",location:"center",left:30,top:-10,fontSize:15,block:!0,input_value:3},{type:"button",text:"L",id:"l",block:!0,location:"top",left:10,top:-40,bold:!0,input_value:10},{type:"button",text:"R",id:"r",block:!0,location:"top",right:10,top:-40,bold:!0,input_value:11},{type:"button",text:"Z",id:"z",block:!0,location:"top",left:10,bold:!0,input_value:12},{fontSize:20,type:"button",text:"CU",id:"cu",location:"right",left:25,top:-65,input_value:23},{fontSize:20,type:"button",text:"CD",id:"cd",location:"right",left:25,top:15,input_value:22},{fontSize:20,type:"button",text:"CL",id:"cl",location:"right",left:-15,top:-25,input_value:21},{fontSize:20,type:"button",text:"CR",id:"cr",location:"right",left:65,top:-25,input_value:20}]:"nds"===this.getCore(!0)||"snes"===this.getCore(!0)?[{type:"button",text:"X",id:"x",location:"right",left:40,bold:!0,input_value:9},{type:"button",text:"Y",id:"y",location:"right",top:40,bold:!0,input_value:1},{type:"button",text:"A",id:"a",location:"right",left:81,top:40,bold:!0,input_value:8},{type:"button",text:"B",id:"b",location:"right",left:40,top:80,bold:!0,input_value:0},{type:"dpad",location:"left",left:"50%",top:"50%",joystickInput:!1,inputValues:[4,5,6,7]},{type:"button",text:"Start",id:"start",location:"center",left:60,fontSize:15,block:!0,input_value:3},{type:"button",text:"Select",id:"select",location:"center",left:-5,fontSize:15,block:!0,input_value:2},{type:"button",text:"L",id:"l",location:"left",left:3,top:-100,bold:!0,block:!0,input_value:10},{type:"button",text:"R",id:"r",location:"right",right:3,top:-100,bold:!0,block:!0,input_value:11}]:[{type:"button",text:"Y",id:"y",location:"right",left:40,bold:!0,input_value:9},{type:"button",text:"X",id:"X",location:"right",top:40,bold:!0,input_value:1},{type:"button",text:"B",id:"b",location:"right",left:81,top:40,bold:!0,input_value:8},{type:"button",text:"A",id:"a",location:"right",left:40,top:80,bold:!0,input_value:0},{type:"zone",location:"left",left:"50%",top:"50%",joystickInput:!1,inputValues:[4,5,6,7]},{type:"button",text:"Start",id:"start",location:"center",left:60,fontSize:15,block:!0,input_value:3},{type:"button",text:"Select",id:"select",location:"center",left:-5,fontSize:15,block:!0,input_value:2}],n=JSON.parse(JSON.stringify(n));var e=this.createElement("div"),t=(e.classList.add("ejs_virtualGamepad_top"),this.createElement("div"));t.classList.add("ejs_virtualGamepad_bottom");const i=this.createElement("div"),o=(i.classList.add("ejs_virtualGamepad_left"),this.createElement("div")),s=(o.classList.add("ejs_virtualGamepad_right"),{top:e,center:t,left:i,right:o});this.virtualGamepad.appendChild(e),this.virtualGamepad.appendChild(t),this.virtualGamepad.appendChild(i),this.virtualGamepad.appendChild(o),this.toggleVirtualGamepadLeftHanded=e=>{i.classList.toggle("ejs_virtualGamepad_left",!e),o.classList.toggle("ejs_virtualGamepad_right",!e),i.classList.toggle("ejs_virtualGamepad_right",e),o.classList.toggle("ejs_virtualGamepad_left",e)};for(let t=0;t<n.length;t++)if("button"===n[t].type){let e="";if(n[t].left&&(e+="left:"+n[t].left+("number"==typeof n[t].left?"px":"")+";"),n[t].right&&(e+="right:"+n[t].right+("number"==typeof n[t].right?"px":"")+";"),n[t].top&&(e+="top:"+n[t].top+("number"==typeof n[t].top?"px":"")+";"),n[t].bold?n[t].bold&&(e+="font-weight:bold;"):e+="font-weight:normal;",n[t].fontSize=n[t].fontSize||30,e+="font-size:"+n[t].fontSize+"px;",n[t].block&&(e+="height:31px;text-align:center;border:1px solid #ccc;border-radius:5px;line-height:31px;"),["top","center","left","right"].includes(n[t].location)){var a=this.createElement("div");a.style=e,a.innerText=n[t].text,a.classList.add("ejs_virtualGamepad_button"),s[n[t].location].appendChild(a);const l=n[t].input_new_cores||n[t].input_value;this.addEventListener(a,"touchstart touchend touchcancel",e=>{e.preventDefault(),"touchend"===e.type||"touchcancel"===e.type?(e.target.classList.remove("ejs_virtualGamepad_button_down"),window.setTimeout(()=>{this.gameManager.simulateInput(0,l,0)})):(e.target.classList.add("ejs_virtualGamepad_button_down"),this.gameManager.simulateInput(0,l,1))})}}const r=e=>{var t=e.container;const l=e.event,c=this.createElement("div");c.classList.add("ejs_dpad_main");var e=this.createElement("div"),n=(e.classList.add("ejs_dpad_vertical"),this.createElement("div")),i=(n.classList.add("ejs_dpad_horizontal"),this.createElement("div")),o=(i.classList.add("ejs_dpad_bar"),this.createElement("div"));o.classList.add("ejs_dpad_bar"),n.appendChild(i),e.appendChild(o),c.appendChild(e),c.appendChild(n);this.addEventListener(c,"touchstart touchmove",s=>{s.preventDefault();s=s.targetTouches[0];if(s){var a=c.getBoundingClientRect(),r=s.clientX-a.left-c.clientWidth/2,s=s.clientY-a.top-c.clientHeight/2;let e=0,t=0,n=0,i=0,o=Math.atan(r/s)/(Math.PI/180);s<=-10&&(e=1),10<=s&&(t=1),10<=r&&(i=1,(o<(n=0)&&-35<=o||0<o&&o<=35)&&(i=0),e=o<0&&-55<=o?1:0,t=0<o&&o<=55?1:0),r<=-10&&(i=0,n=o<0&&-35<=o||0<o&&o<=35?0:1,e=0<o&&o<=55?1:0,t=o<0&&-55<=o?1:0),c.classList.toggle("ejs_dpad_up_pressed",e),c.classList.toggle("ejs_dpad_down_pressed",t),c.classList.toggle("ejs_dpad_right_pressed",i),c.classList.toggle("ejs_dpad_left_pressed",n),l(e,t,n,i)}}),this.addEventListener(c,"touchend touchcancel",e=>{e.preventDefault(),c.classList.remove("ejs_dpad_up_pressed"),c.classList.remove("ejs_dpad_down_pressed"),c.classList.remove("ejs_dpad_right_pressed"),c.classList.remove("ejs_dpad_left_pressed"),l(0,0,0,0)}),t.appendChild(c)};if(n.forEach((o,e)=>{if("dpad"===o.type){var t=this.createElement("div");let e="";o.left&&(e+="left:"+o.left+";"),o.right&&(e+="right:"+o.right+";"),o.top&&(e+="top:"+o.top+";"),t.style=e,s[o.location].appendChild(t),r({container:t,event:(e,t,n,i)=>{o.joystickInput&&(1===e&&(e=32767),1===t&&(e=32767),1===n&&(e=32767),1===i)&&(e=32767),this.gameManager.simulateInput(0,o.inputValues[0],e),this.gameManager.simulateInput(0,o.inputValues[1],t),this.gameManager.simulateInput(0,o.inputValues[2],n),this.gameManager.simulateInput(0,o.inputValues[3],i)}})}}),n.forEach((o,e)=>{var t;"zone"===o.type&&(t=this.createElement("div"),this.addEventListener(t,"touchstart touchmove touchend touchcancel",e=>{e.preventDefault()}),s[o.location].appendChild(t),(t=nipplejs.create({zone:t,mode:"static",position:{left:o.left,top:o.top},color:o.color||"red"})).on("end",()=>{this.gameManager.simulateInput(0,o.inputValues[0],0),this.gameManager.simulateInput(0,o.inputValues[1],0),this.gameManager.simulateInput(0,o.inputValues[2],0),this.gameManager.simulateInput(0,o.inputValues[3],0)}),t.on("move",(e,n)=>{var i=n.angle.degree,n=n.distance;if(!0===o.joystickInput){let e=0,t=0;0<i&&i<=45&&(e=n/50,t=-.022222222222222223*i*n/50),45<i&&i<=90&&(e=.022222222222222223*(90-i)*n/50,t=-n/50),90<i&&i<=135&&(e=.022222222222222223*(90-i)*n/50,t=-n/50),135<i&&i<=180&&(e=-n/50,t=-.022222222222222223*(180-i)*n/50),135<i&&i<=225&&(e=-n/50,t=-.022222222222222223*(180-i)*n/50),225<i&&i<=270&&(e=-.022222222222222223*(270-i)*n/50,t=n/50),270<i&&i<=315&&(e=-.022222222222222223*(270-i)*n/50,t=n/50),315<i&&i<=359.9&&(e=n/50,t=.022222222222222223*(360-i)*n/50),0<e?(this.gameManager.simulateInput(0,o.inputValues[0],32767*e),this.gameManager.simulateInput(0,o.inputValues[1],0)):(this.gameManager.simulateInput(0,o.inputValues[1],32767*-e),this.gameManager.simulateInput(0,o.inputValues[0],0)),0<t?(this.gameManager.simulateInput(0,o.inputValues[2],32767*t),this.gameManager.simulateInput(0,o.inputValues[3],0)):(this.gameManager.simulateInput(0,o.inputValues[3],32767*-t),this.gameManager.simulateInput(0,o.inputValues[2],0))}else 30<=i&&i<150?this.gameManager.simulateInput(0,o.inputValues[0],1):window.setTimeout(()=>{this.gameManager.simulateInput(0,o.inputValues[0],0)},30),210<=i&&i<330?this.gameManager.simulateInput(0,o.inputValues[1],1):window.setTimeout(()=>{this.gameManager.simulateInput(0,o.inputValues[1],0)},30),120<=i&&i<240?this.gameManager.simulateInput(0,o.inputValues[2],1):window.setTimeout(()=>{this.gameManager.simulateInput(0,o.inputValues[2],0)},30),300<=i||0<=i&&i<60?this.gameManager.simulateInput(0,o.inputValues[3],1):window.setTimeout(()=>{this.gameManager.simulateInput(0,o.inputValues[3],0)},30)}))}),this.touch||0<navigator.maxTouchPoints){const c=this.createElement("div");c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M0 96C0 78.33 14.33 64 32 64H416C433.7 64 448 78.33 448 96C448 113.7 433.7 128 416 128H32C14.33 128 0 113.7 0 96zM0 256C0 238.3 14.33 224 32 224H416C433.7 224 448 238.3 448 256C448 273.7 433.7 288 416 288H32C14.33 288 0 273.7 0 256zM416 448H32C14.33 448 0 433.7 0 416C0 398.3 14.33 384 32 384H416C433.7 384 448 398.3 448 416C448 433.7 433.7 448 416 448z"/></svg>',c.classList.add("ejs_virtualGamepad_open"),c.style.display="none",this.on("start",()=>c.style.display=""),this.elements.parent.appendChild(c);let t,n=!0;this.addEventListener(c,"touchstart touchend mousedown mouseup click",e=>{n&&(clearTimeout(t),t=setTimeout(()=>{n=!0},2e3),n=!1,e.preventDefault(),this.menu.toggle())}),this.elements.menuToggle=c}this.virtualGamepad.style.display="none"}handleResize(){var e,t,n;this.Module&&(e=window.devicePixelRatio||1,t=(n=this.elements.parent.getBoundingClientRect()).width*e,n=n.height*e,this.Module.setCanvasSize(t,n),this.handleSettingsResize(),"none"===this.virtualGamepad.style.display)&&(this.virtualGamepad.style.opacity=0,this.virtualGamepad.style.display="",setTimeout(()=>{this.virtualGamepad.style.display="none",this.virtualGamepad.style.opacity=""},250))}getElementSize(e){var t=e.cloneNode(!0),e=(t.style.position="absolute",t.style.opacity=0,t.removeAttribute("hidden"),e.parentNode.appendChild(t),t.getBoundingClientRect());return t.remove(),{width:e.width,height:e.height}}saveSettings(){var e,t;window.localStorage&&this.settingsLoaded&&(e={controlSettings:this.controls,settings:this.settings,cheats:this.cheats},t={volume:this.volume,muted:this.muted},localStorage.setItem("ejs-settings",JSON.stringify(t)),localStorage.setItem("ejs-"+this.getCore()+"-settings",JSON.stringify(e)))}loadSettings(){if(window.localStorage){this.settingsLoaded=!0;var e=localStorage.getItem("ejs-settings"),n=localStorage.getItem("ejs-"+this.getCore()+"-settings");if(n)try{if(!((n=JSON.parse(n)).controlSettings instanceof Object&&n.settings instanceof Object&&Array.isArray(n.cheats)))return;this.controls=n.controlSettings,this.checkGamepadInputs();for(const t in n.settings)this.changeSettingOption(t,n.settings[t]);for(let e=0;e<n.cheats.length;e++){var i=n.cheats[e];let t=!1;for(let e=0;e<this.cheats.length;e++)if(this.cheats[e].desc===i.desc&&this.cheats[e].code===i.code){this.cheats[e].checked=i.checked,t=!0;break}t||this.cheats.push(i)}}catch(e){console.warn("Could not load previous settings",e)}if(e)try{"number"==typeof(e=JSON.parse(e)).volume&&"boolean"==typeof e.muted&&(this.volume=e.volume,this.muted=e.muted,this.setVolume(this.muted?0:this.volume))}catch(e){console.warn("Could not load previous settings",e)}}}menuOptionChanged(e,t){if(this.saveSettings(),this.debug&&console.log(e,t),"shader"===e){try{this.Module.FS.unlink("/shader/shader.glslp")}catch(e){}return"disabled"===t?void this.gameManager.toggleShader(0):(this.Module.FS.writeFile("/shader/shader.glslp",window.EJS_SHADERS[t]),void this.gameManager.toggleShader(1))}"disk"===e?this.gameManager.setCurrentDisk(t):("virtual-gamepad"===e?this.toggleVirtualGamepad("disabled"!==t):"virtual-gamepad-left-handed-mode"===e&&this.toggleVirtualGamepadLeftHanded("disabled"!==t),this.gameManager.setVariable(e,t))}setupSettingsMenu(){this.settingsMenu=this.createElement("div"),this.settingsMenu.classList.add("ejs_settings_parent");const m=this.createElement("div"),y=(m.classList.add("ejs_settings_transition"),this.settings={},this.createElement("div")),g=(y.style.overflow="auto",[]);this.handleSettingsResize=()=>{var e=this.settingsMenu.parentElement.getBoundingClientRect().x;let t=this.elements.parent.getBoundingClientRect().height;var n=this.elements.parent.getBoundingClientRect().width;375<t&&(t=375),y.style["max-height"]=t-95+"px",m.style["max-height"]=t-95+"px";for(let e=0;e<g.length;e++)g[e].style["max-height"]=t-95+"px";n<575?this.settingsMenu.classList.toggle("ejs_settings_leftside",!(window.innerWidth/2>e)):this.settingsMenu.classList.remove("ejs_settings_leftside")},y.classList.add("ejs_setting_menu"),m.appendChild(y);let v=[],_=(this.changeSettingOption=(t,e)=>{this.settings[t]=e,v.forEach(e=>e(t))},{});const s=(e,t,n,i)=>{var o=this.createElement("div"),s=(o.classList.add("ejs_settings_main_bar"),this.createElement("span"));s.innerText=e;const a=this.createElement("div"),r=(a.innerText="",a.classList.add("ejs_settings_main_bar_selected"),s.appendChild(a),o.appendChild(s),y.appendChild(o),this.createElement("div"));g.push(r),r.style.overflow="auto",r.setAttribute("hidden","");s=this.createElement("button");const l=()=>{var e=this.getElementSize(y);m.style.width=e.width+20+"px",m.style.height=e.height+"px",r.setAttribute("hidden",""),y.removeAttribute("hidden")};this.addEventListener(o,"click",e=>{var t=this.getElementSize(r);m.style.width=t.width+20+"px",m.style.height=t.height+"px",r.removeAttribute("hidden"),y.setAttribute("hidden","")}),this.addEventListener(s,"click",l),s.type="button",s.classList.add("ejs_back_button"),r.appendChild(s);var o=this.createElement("span"),c=(o.innerText=e,o.classList.add("ejs_menu_text_a"),s.appendChild(o),this.createElement("div"));c.classList.add("ejs_setting_menu");let h=[],d=n;if(Array.isArray(n)){d={};for(let e=0;e<n.length;e++)d[n[e]]=n[e]}_[t]=d,v.push(e=>{if(t===e){for(let e=0;e<h.length;e++)h[e].classList.toggle("ejs_option_row_selected",h[e].getAttribute("ejs_value")===this.settings[t]);this.menuOptionChanged(t,this.settings[t]),a.innerText=d[this.settings[t]]}});for(const p in d){const f=this.createElement("button");h.push(f),f.setAttribute("ejs_value",p),f.type="button",f.value=d[p],f.classList.add("ejs_option_row"),f.classList.add("ejs_button_style"),this.addEventListener(f,"click",e=>{this.settings[t]=p;for(let e=0;e<h.length;e++)h[e].classList.remove("ejs_option_row_selected");f.classList.add("ejs_option_row_selected"),this.menuOptionChanged(t,p),a.innerText=d[p],l()}),i===p&&(f.classList.add("ejs_option_row_selected"),this.menuOptionChanged(t,p),a.innerText=d[p]);var u=this.createElement("span");u.innerText=d[p],f.appendChild(u),c.appendChild(f)}r.appendChild(c),m.appendChild(r)};if(1<this.gameManager.getDiskCount()){var t={};for(let e=0;e<this.gameManager.getDiskCount();e++)t[e.toString()]="Disk "+(e+1);s(this.localization("Disk"),"disk",t,this.gameManager.getCurrentDisk().toString())}window.EJS_SHADERS&&s(this.localization("Shaders"),"shader",{disabled:this.localization("Disabled"),"2xScaleHQ.glslp":this.localization("2xScaleHQ"),"4xScaleHQ.glslp":this.localization("4xScaleHQ"),"crt-easymode.glslp":this.localization("CRT easymode"),"crt-aperture.glslp":this.localization("CRT aperture"),"crt-geom.glslp":this.localization("CRT geom"),"crt-mattias.glslp":this.localization("CRT mattias")},"disabled"),s(this.localization("FPS"),"fps",{show:this.localization("show"),hide:this.localization("hide")},"hide"),this.saveInBrowserSupported()&&(s(this.localization("Save State Slot"),"save-state-slot",["1","2","3","4","5","6","7","8","9"],"1"),s(this.localization("Save State Location"),"save-state-location",{download:this.localization("Download"),browser:this.localization("Keep in Browser")},"download")),(this.touch||0<navigator.maxTouchPoints)&&(s(this.localization("Virtual Gamepad"),"virtual-gamepad",{enabled:this.localization("Enabled"),disabled:this.localization("Disabled")},this.isMobile?"enabled":"disabled"),s(this.localization("Left Handed Mode"),"virtual-gamepad-left-handed-mode",{enabled:this.localization("Enabled"),disabled:this.localization("Disabled")},"disabled")),this.gameManager.getCoreOptions()&&this.gameManager.getCoreOptions().split("\n").forEach((e,t)=>{var e=e.split("; "),n=e[0],i=e[1].split("|"),e=n.split("|")[0].replace(/_/g," ").replace(/.+\-(.+)/,"$1");if(i.slice(1,-1),1!==i.length){var o={};for(let e=0;e<i.length;e++)o[i[e]]=this.localization(i[e]);s(this.localization(e),n.split("|")[0],o,1<n.split("|").length?n.split("|")[1]:i[0].replace("(Default) ",""))}}),this.settingsMenu.appendChild(m),this.settingParent.appendChild(this.settingsMenu),this.settingParent.style.position="relative";var e=this.getElementSize(y);if(m.style.width=e.width+20+"px",m.style.height=e.height+"px",this.settingsMenu.style.display="none",this.debug&&console.log("Available core options",_),this.config.defaultOptions)for(const n in this.config.defaultOptions)this.changeSettingOption(n,this.config.defaultOptions[n])}createSubPopup(e){var t=this.createElement("div"),n=(t.classList.add("ejs_popup_container"),t.classList.add("ejs_popup_container_box"),this.createElement("div"));return n.innerText="",e&&t.setAttribute("hidden",""),t.appendChild(n),[t,n]}createNetplayMenu(){var e=this.createPopup("Netplay",{"Create a Room":()=>{this.isNetplay?this.netplay.leaveRoom():this.netplay.showOpenRoomDialog()},Close:()=>{this.netplayMenu.style.display="none",this.netplay.updateList.stop()}},!0);this.netplayMenu=e.parentElement;const s=this.netplayMenu.getElementsByTagName("a")[0],a=this.createElement("div");var t=this.createElement("strong"),n=(t.innerText=this.localization("Rooms"),this.createElement("table")),i=(n.classList.add("ejs_netplay_table"),n.style.width="100%",n.setAttribute("cellspacing","0"),this.createElement("thead"));const o=this.createElement("tr");var r=e=>{var t=this.createElement("td");return t.innerText=e,t.style["text-align"]="center",o.appendChild(t),t};i.appendChild(o),r("Room Name").style["text-align"]="left",r("Players").style.width="80px",r("").style.width="80px",n.appendChild(i);const l=this.createElement("tbody"),c=(n.appendChild(l),a.appendChild(t),a.appendChild(n),this.createElement("div")),h=this.createElement("strong"),d=(h.innerText="{roomname}",this.createElement("div"));d.innerText="Password: ";r=this.createElement("table"),r.classList.add("ejs_netplay_table"),r.style.width="100%",r.setAttribute("cellspacing","0"),i=this.createElement("thead");const u=this.createElement("tr");t=e=>{var t=this.createElement("td");return t.innerText=e,u.appendChild(t),t};i.appendChild(u),t("Player").style.width="80px",t("Name"),t("").style.width="80px",r.appendChild(i);const p=this.createElement("tbody");r.appendChild(p),c.appendChild(h),c.appendChild(d),c.appendChild(r),c.style.display="none",e.appendChild(a),e.appendChild(c),this.openNetplayMenu=()=>{if(this.netplayMenu.style.display="",!this.netplay){this.netplay={},this.netplay.table=l,this.netplay.playerTable=p,this.netplay.passwordElem=d,this.netplay.roomNameElem=h,this.netplay.createButton=s,this.netplay.tabs=[a,c],this.defineNetplayFunctions();const i=this.createSubPopup();this.netplayMenu.appendChild(i[0]),i[1].classList.add("ejs_cheat_parent");var e=i[1],t=this.createElement("div"),n=this.createElement("h2"),n=(n.innerText=this.localization("Set Player Name"),n.classList.add("ejs_netplay_name_heading"),t.appendChild(n),e.appendChild(t),this.createElement("div")),t=(n.classList.add("ejs_netplay_header"),this.createElement("strong"));t.innerText=this.localization("Player Name");const o=this.createElement("input");o.type="text",o.setAttribute("maxlength",20),n.appendChild(t),n.appendChild(this.createElement("br")),n.appendChild(o),e.appendChild(n),e.appendChild(this.createElement("br"));t=this.createElement("button");t.classList.add("ejs_button_button"),t.classList.add("ejs_popup_submit"),t.style["background-color"]="rgba(var(--ejs-primary-color),1)",t.innerText=this.localization("Submit"),e.appendChild(t),this.addEventListener(t,"click",e=>{o.value.trim()&&(this.netplay.name=o.value.trim(),i[0].remove())})}this.netplay.updateList.start()}}defineNetplayFunctions(){function e(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}for(this.netplay.url=this.config.netplayUrl;this.netplay.url.endsWith("/");)this.netplay.url=this.netplay.url.substring(0,this.netplay.url.length-1);this.netplay.current_frame=0,this.netplay.getOpenRooms=async()=>JSON.parse(await(await fetch(this.netplay.url+"/list?domain="+window.location.host+"&game_id="+this.config.gameId)).text()),this.netplay.updateTableList=async()=>{var e=(t,n,e,i)=>{const o=this.createElement("tr");o.classList.add("ejs_netplay_table_row");var s=e=>{var t=this.createElement("td");return t.innerText=e,t.style.padding="10px 0",t.style["text-align"]="center",o.appendChild(t),t},s=(s(n).style["text-align"]="left",s(e+"/"+i).style.width="80px",s(""));if(s.style.width="80px",this.netplay.table.appendChild(o),e<i)return(e=this.createElement("button")).classList.add("ejs_netplay_join_button"),e.classList.add("ejs_button_button"),e.style["background-color"]="rgba(var(--ejs-primary-color),1)",e.innerText=this.localization("Join"),s.appendChild(e),this.addEventListener(e,"click",e=>{this.netplay.joinRoom(t,n)}),e},t=await this.netplay.getOpenRooms();this.netplay.table.innerHTML="";for(const n in t)e(n,t[n].room_name,t[n].current,t[n].max)},this.netplay.showOpenRoomDialog=()=>{const t=this.createSubPopup();this.netplayMenu.appendChild(t[0]),t[1].classList.add("ejs_cheat_parent");var e=t[1],n=this.createElement("div"),i=this.createElement("h2"),i=(i.innerText=this.localization("Create a room"),i.classList.add("ejs_netplay_name_heading"),n.appendChild(i),e.appendChild(n),this.createElement("div")),n=(i.classList.add("ejs_netplay_header"),this.createElement("strong"));n.innerText=this.localization("Room Name");const o=this.createElement("input");o.type="text",o.setAttribute("maxlength",20);var s=this.createElement("strong");s.innerText=this.localization("Max Players");const a=this.createElement("select");a.setAttribute("disabled","disabled");var r=this.createElement("option"),l=(r.value=2,r.innerText="2",this.createElement("option")),c=(l.value=3,l.innerText="3",this.createElement("option")),r=(c.value=4,c.innerText="4",a.appendChild(r),a.appendChild(l),a.appendChild(c),this.createElement("strong"));r.innerText=this.localization("Password (optional)");const h=this.createElement("input");h.type="text",h.setAttribute("maxlength",20),i.appendChild(n),i.appendChild(this.createElement("br")),i.appendChild(o),i.appendChild(s),i.appendChild(this.createElement("br")),i.appendChild(a),i.appendChild(r),i.appendChild(this.createElement("br")),i.appendChild(h),e.appendChild(i),e.appendChild(this.createElement("br"));l=this.createElement("button"),l.classList.add("ejs_button_button"),l.classList.add("ejs_popup_submit"),l.style["background-color"]="rgba(var(--ejs-primary-color),1)",l.style.margin="0 10px",l.innerText=this.localization("Submit"),e.appendChild(l),this.addEventListener(l,"click",e=>{o.value.trim()&&(this.netplay.openRoom(o.value.trim(),parseInt(a.value),h.value.trim()),t[0].remove())}),c=this.createElement("button");c.classList.add("ejs_button_button"),c.classList.add("ejs_popup_submit"),c.style.margin="0 10px",c.innerText=this.localization("Close"),e.appendChild(c),this.addEventListener(c,"click",e=>{t[0].remove()})},this.netplay.startSocketIO=e=>{this.netplay.socket=io(this.netplay.url),this.netplay.socket.on("connect",()=>e()),this.netplay.socket.on("users-updated",e=>{this.debug&&console.log(e),this.netplay.players=e,this.netplay.updatePlayersTable(),this.netplay.owner&&this.netplay.sync()}),this.netplay.socket.on("disconnect",()=>this.netplay.roomLeft()),this.netplay.socket.on("data-message",e=>{this.netplay.dataMessage(e)})},this.netplay.openRoom=(t,n,i)=>{const o=e();this.netplay.playerID=e(),this.netplay.players={},this.netplay.extra={domain:window.location.host,game_id:this.config.gameId,room_name:t,player_name:this.netplay.name,userid:this.netplay.playerID,sessionid:o},this.netplay.players[this.netplay.playerID]=this.netplay.extra,this.netplay.users={},this.netplay.startSocketIO(e=>{this.netplay.socket.emit("open-room",{extra:this.netplay.extra,maxPlayers:n,password:i},e=>{e?this.debug&&console.log("error: ",e):this.netplay.roomJoined(!0,t,i,o)})})},this.netplay.leaveRoom=()=>{this.debug&&console.log("asd"),this.netplay.roomLeft()},this.netplay.joinRoom=(n,i)=>{this.netplay.playerID=e(),this.netplay.players={},this.netplay.extra={domain:window.location.host,game_id:this.config.gameId,room_name:i,player_name:this.netplay.name,userid:this.netplay.playerID,sessionid:n},this.netplay.players[this.netplay.playerID]=this.netplay.extra,this.netplay.startSocketIO(e=>{this.netplay.socket.emit("join-room",{extra:this.netplay.extra},(e,t)=>{e?this.debug&&console.log("error: ",e):(this.netplay.players=t,this.netplay.roomJoined(!1,i,"",n))})})},this.netplay.roomJoined=(e,t,n,i)=>{this.isNetplay=!0,this.netplay.inputs={},this.netplay.owner=e,this.debug&&console.log(this.netplay.extra),this.netplay.roomNameElem.innerText=t,this.netplay.tabs[0].style.display="none",this.netplay.tabs[1].style.display="",n?(this.netplay.passwordElem.style.display="",this.netplay.passwordElem.innerText=this.localization("Password")+": "+n):this.netplay.passwordElem.style.display="none",this.netplay.createButton.innerText=this.localization("Leave Room"),this.netplay.updatePlayersTable(),this.netplay.owner?this.netplay.oldStyles=[this.elements.bottomBar.cheat[0].style.display]:(this.netplay.oldStyles=[this.elements.bottomBar.cheat[0].style.display,this.elements.bottomBar.playPause[0].style.display,this.elements.bottomBar.playPause[1].style.display,this.elements.bottomBar.restart[0].style.display,this.elements.bottomBar.loadState[0].style.display,this.elements.bottomBar.saveState[0].style.display,this.elements.bottomBar.saveSavFiles[0].style.display,this.elements.bottomBar.loadSavFiles[0].style.display,this.elements.contextMenu.save.style.display,this.elements.contextMenu.load.style.display],this.elements.bottomBar.cheat[0].style.display="none",this.elements.bottomBar.playPause[0].style.display="none",this.elements.bottomBar.playPause[1].style.display="none",this.elements.bottomBar.restart[0].style.display="none",this.elements.bottomBar.loadState[0].style.display="none",this.elements.bottomBar.saveState[0].style.display="none",this.elements.bottomBar.saveSavFiles[0].style.display="none",this.elements.bottomBar.loadSavFiles[0].style.display="none",this.elements.contextMenu.save.style.display="none",this.elements.contextMenu.load.style.display="none",this.gameManager.resetCheat()),this.elements.bottomBar.cheat[0].style.display="none"},this.netplay.updatePlayersTable=()=>{const o=this.netplay.playerTable;o.innerHTML="";var e=(e,t)=>{const n=this.createElement("tr");var i=e=>{var t=this.createElement("td");return t.innerText=e,n.appendChild(t),t};i(e).style.width="80px",i(t),i("").style.width="80px",o.appendChild(n)};let t=1;for(const n in this.netplay.players)e(t,this.netplay.players[n].player_name),t++},this.netplay.roomLeft=()=>{this.isNetplay=!1,this.netplay.tabs[0].style.display="",this.netplay.tabs[1].style.display="none",this.netplay.extra=null,this.netplay.playerID=null,this.netplay.createButton.innerText=this.localization("Create a Room"),this.netplay.socket.disconnect(),this.elements.bottomBar.cheat[0].style.display=this.netplay.oldStyles[0],this.netplay.owner||(this.elements.bottomBar.playPause[0].style.display=this.netplay.oldStyles[1],this.elements.bottomBar.playPause[1].style.display=this.netplay.oldStyles[2],this.elements.bottomBar.restart[0].style.display=this.netplay.oldStyles[3],this.elements.bottomBar.loadState[0].style.display=this.netplay.oldStyles[4],this.elements.bottomBar.saveState[0].style.display=this.netplay.oldStyles[5],this.elements.bottomBar.saveSavFiles[0].style.display=this.netplay.oldStyles[6],this.elements.bottomBar.loadSavFiles[0].style.display=this.netplay.oldStyles[7],this.elements.contextMenu.save.style.display=this.netplay.oldStyles[8],this.elements.contextMenu.load.style.display=this.netplay.oldStyles[9]),this.updateCheatUI()};let t=!(this.netplay.setLoading=e=>{this.debug&&console.log("loading:",e)}),n=(this.netplay.sync=async()=>{var e;t||(t=!0,this.debug&&console.log("sync"),this.netplay.ready=0,e=await this.gameManager.getState(),this.netplay.sendMessage({state:e}),this.netplay.setLoading(!0),this.pause(!0),this.netplay.ready++,this.netplay.current_frame=0,this.netplay.ready===this.netplay.getUserCount()&&this.play(!0),t=!1)},this.netplay.getUserIndex=e=>{let t=0;for(const n in this.netplay.players){if(n===e)return t;t++}return-1},!(this.netplay.getUserCount=()=>{let e=0;for(const t in this.netplay.players)e++;return e}));this.netplay.dataMessage=e=>{e.state&&(this.netplay.setLoading(!0),this.pause(!0),this.gameManager.loadState(new Uint8Array(e.state)),this.netplay.sendMessage({ready:!0})),e.play&&!this.owner&&this.play(!0),e.pause&&!this.owner&&this.pause(!0),e.ready&&this.netplay.owner&&(this.netplay.ready++,this.netplay.ready===this.netplay.getUserCount())&&(this.netplay.sendMessage({readyready:!0,resetCurrentFrame:!0}),setTimeout(()=>this.play(!0),100),this.netplay.setLoading(!1),this.netplay.current_frame=0,n=!0),e.readyready&&(this.netplay.setLoading(!1),this.netplay.current_frame=0,this.play(!0)),e.resetCurrentFrame&&(this.play(!0),this.netplay.current_frame=0,this.netplay.inputs={}),e.user_frame&&this.netplay.owner&&(n&&(n=!1,this.netplay.current_frame=0,this.netplay.inputs={}),this.netplay.users[e.user_frame.user]=e.user_frame.frame),e.shortPause===this.netplay.playerID?(this.pause(!0),setTimeout(()=>this.play(!0),5)):e.lessShortPause===this.netplay.playerID&&(this.pause(!0),setTimeout(()=>this.play(!0),10)),e.input&&this.netplay.owner&&this.netplay.simulateInput(this.netplay.getUserIndex(e.user),e.input[0],e.input[1],!0),e.connected_input&&!this.netplay.owner&&(this.netplay.inputs[e.frame]||(this.netplay.inputs[e.frame]=[]),this.netplay.inputs[e.frame].push([e.connected_input[0],e.connected_input[1],e.connected_input[2]])),e.restart&&(this.gameManager.restart(),this.netplay.current_frame=0,this.netplay.inputs={},this.play(!0))},this.netplay.simulateInput=(e,t,n,i)=>{this.isNetplay&&(0===e||i)&&(this.netplay.owner?(i=this.netplay.current_frame,this.gameManager.functions.simulateInput(e,t,n),this.netplay.sendMessage({frame:i,connected_input:[e,t,n]})):this.netplay.sendMessage({user:this.netplay.playerID,input:[t,n]}))},this.netplay.sendMessage=e=>{this.netplay.socket.emit("data-message",e)},this.Module.postMainLoop=()=>{if(this.isNetplay&&!this.paused)if(this.netplay.current_frame++,this.netplay.owner)for(const t in this.netplay.users)if(-1===this.netplay.getUserIndex(t))delete this.netplay.users[t];else{var e=this.netplay.current_frame-this.netplay.users[t];if(75<Math.abs(e))return void this.netplay.sync();e<0&&this.netplay.sendMessage({lessShortPause:t}),e<5?this.netplay.sendMessage({shortPause:t}):30<e?(this.pause(!0),setTimeout(()=>this.play(!0),10)):10<e&&(this.pause(!0),setTimeout(()=>this.play(!0),5))}else{this.netplay.sendMessage({user_frame:{user:this.netplay.playerID,frame:this.netplay.current_frame}});for(const n in this.netplay.inputs)n<=this.netplay.current_frame&&(this.netplay.inputs[n].forEach(e=>{this.gameManager.functions.simulateInput(e[0],e[1],e[2])}),delete this.netplay.inputs[n])}},this.netplay.updateList={start:()=>{this.netplay.updateList.interval=setInterval(this.netplay.updateTableList.bind(this),1e3)},stop:()=>{clearInterval(this.netplay.updateList.interval)}}}createCheatsMenu(){var e=this.createPopup("Cheats",{"Add Cheat":()=>{const t=this.createSubPopup();this.cheatMenu.appendChild(t[0]),t[1].classList.add("ejs_cheat_parent"),t[1].style.width="100%";var e=t[1],n=this.createElement("div"),i=(n.classList.add("ejs_cheat_header"),this.createElement("h2")),o=(i.innerText=this.localization("Add Cheat Code"),i.classList.add("ejs_cheat_heading"),this.createElement("button")),i=(o.classList.add("ejs_cheat_close"),n.appendChild(i),n.appendChild(o),e.appendChild(n),this.addEventListener(o,"click",e=>{t[0].remove()}),this.createElement("div")),n=(i.classList.add("ejs_cheat_main"),this.createElement("strong"));n.innerText=this.localization("Code"),i.appendChild(n),i.appendChild(this.createElement("br"));const s=this.createElement("textarea");s.classList.add("ejs_cheat_code"),s.style.width="100%",s.style.height="80px",i.appendChild(s),i.appendChild(this.createElement("br"));o=this.createElement("strong");o.innerText=this.localization("Description"),i.appendChild(o),i.appendChild(this.createElement("br"));const a=this.createElement("input");a.type="text",a.classList.add("ejs_cheat_code"),i.appendChild(a),i.appendChild(this.createElement("br")),e.appendChild(i);var n=this.createElement("footer"),o=this.createElement("button"),i=this.createElement("button"),r=(o.innerText=this.localization("Submit"),i.innerText=this.localization("Close"),o.classList.add("ejs_button_button"),i.classList.add("ejs_button_button"),o.classList.add("ejs_popup_submit"),i.classList.add("ejs_popup_submit"),o.style["background-color"]="rgba(var(--ejs-primary-color),1)",n.appendChild(o),this.createElement("span"));r.innerText=" ",n.appendChild(r),n.appendChild(i),e.appendChild(n),this.addEventListener(o,"click",e=>{s.value.trim()&&a.value.trim()&&(t[0].remove(),this.cheats.push({code:s.value,desc:a.value,checked:!1}),this.updateCheatUI(),this.saveSettings())}),this.addEventListener(i,"click",e=>{t[0].remove()})},Close:()=>{this.cheatMenu.style.display="none"}},!0),t=(this.cheatMenu=e.parentElement,this.createElement("div"));e.appendChild(t),t.classList.add("ejs_cheat_rows"),this.elements.cheatRows=t}updateCheatUI(){this.elements.cheatRows.innerHTML="";const r=(t,n)=>{for(let e=0;e<this.cheats.length;e++)if(this.cheats[e].desc===t&&this.cheats[e].code===n)return e};var t=(t,e,n,i)=>{const o=this.createElement("div"),s=(o.classList.add("ejs_cheat_row"),this.createElement("input"));s.type="checkbox",s.checked=e,s.value=i,s.id="ejs_cheat_switch_"+i,o.appendChild(s);var a=this.createElement("label"),a=(a.for="ejs_cheat_switch_"+i,a.innerText=t,o.appendChild(a),a.addEventListener("click",e=>{s.checked=!s.checked,this.cheats[r(t,n)].checked=s.checked,this.cheatChanged(s.checked,n,r(t,n)),this.saveSettings()}),this.createElement("a"));a.classList.add("ejs_cheat_row_button"),a.innerText="×",o.appendChild(a),a.addEventListener("click",e=>{this.cheatChanged(!1,n,r(t,n)),this.cheats.splice(r(t,n),1),o.remove()}),this.elements.cheatRows.appendChild(o),this.cheatChanged(e,n,i)};this.gameManager.resetCheat();for(let e=0;e<this.cheats.length;e++)t(this.cheats[e].desc,this.cheats[e].checked,this.cheats[e].code,e)}cheatChanged(e,t,n){this.gameManager.setCheat(n,e,t)}}