(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={INFO:1,WARNING:2,ERROR:3,SOUND_START:10,SOUND_STOP:11,SOUND_UPDATE:12,MUSIC_SET_GENMIDI:20,MUSIC_REGISTER:21,MUSIC_PLAY:22,MUSIC_PAUSE:23,MUSIC_RESUME:24,MUSIC_STOP:25,MUSIC_UNREGISTER:26,MUSIC_SET_VOLUME:27,SAVE_WRITTEN:30,GAME_STATE_CHANGED:100,LEVEL_LOADED:101,LEVEL_COMPLETED:102,LEVEL_EXIT_TRIGGERED:103,PLAYER_SPAWNED:110,PLAYER_DIED:111,PLAYER_RESPAWNED:112,WEAPON_FIRED:120,WEAPON_CHANGED:121,PLAYER_DAMAGED:122,ENEMY_KILLED:130,EXPLOSION:131,ENEMY_AWAKENED:132,ENEMY_DAMAGED:133,ITEM_PICKED_UP:140,KEY_OBTAINED:141,SECRET_FOUND:150,LOCKED_DOOR_BLOCKED:160,DOOR:161,SWITCH_ACTIVATED:162,TELEPORT:163,PLATFORM:164,HUD_MESSAGE:170,FACE_CHANGED:171,CHEAT_ACTIVATED:172,SETTINGS_CHANGED:180};new Map(Object.entries(e).map(([e,t])=>[t,e]));function*t(e){let t=e.wasmdoom_events_len();if(t===0)return;let n=e.wasmdoom_events_ptr(),r=new DataView(e.memory.buffer,n,t),i=0;for(;i+4<=t;){let a=r.getUint16(i,!0),o=r.getUint16(i+2,!0),s=i+4;if(s+o>t)break;yield{tag:a,payload:new DataView(e.memory.buffer,n+s,o)},i=s+o}}function n(e){let n=new Map;function r(){if(e.wasmdoom_events_len()!==0){for(let{tag:r,payload:i}of t(e))n.get(r)?.(i);e.wasmdoom_events_clear()}}return{register(e,t){n.set(e,t)},drain:r}}var r=``+new URL(`music-worklet-BRuiHdwD.js`,import.meta.url).href;function i(...e){return e.filter(e=>e!==``).join(`/`).replace(/\/{2,}/g,`/`)}function a(e){if(!e)return!1;let t=e.userAgent??``,n=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(t),r=e.maxTouchPoints??0;return n||r>1}function o(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function s(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var{BASE_URL:c}={BASE_URL:`./`},l=8,u=11025,d=`wasmdoom.music`,f=`wasmdoom.music.wasm`;function p(e,t,n){return e<t?t:e>n?n:e}function m(e){return p(e/127,0,1)}function h(e){return p((e-128)/127,-1,1)}function g(e){return Math.max(e,1)/128}function _(){let t=null,n=new Map,a=new Map,o=null,s=[];function p(e,t=[]){o?o.port.postMessage(e,t):s.push({msg:e,transfer:t})}async function _(e){let t=i(c,f);if(console.log(`[wasmdoom] music setup starting`,{workletURL:r,musicWasmUrl:t}),!e.audioWorklet){console.error(`[wasmdoom] AudioWorklet unavailable (music disabled): the page must be loaded from a secure context. Use http://localhost instead of a LAN IP, or serve over HTTPS.`);return}let n;try{n=await(await fetch(t)).arrayBuffer()}catch(e){console.error(`[wasmdoom] music wasm failed to fetch:`,e);return}try{await e.audioWorklet.addModule(r)}catch(e){console.error(`[wasmdoom] music worklet failed to load:`,e);return}let a;try{a=new AudioWorkletNode(e,d,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]})}catch(e){console.error(`[wasmdoom] AudioWorkletNode construction failed:`,e);return}a.port.onmessage=e=>console.log(`[music]`,e.data),a.onprocessorerror=e=>console.error(`[wasmdoom] worklet processor error:`,e),a.connect(e.destination),a.port.postMessage({type:`init`,wasm:n},[n]),o=a;for(let{msg:e,transfer:t}of s)a.port.postMessage(e,t);s=[]}function v(r,i){function o(e,t){let n=new Uint8Array(i.memory.buffer,e,t),r=new ArrayBuffer(t);return new Uint8Array(r).set(n),r}function s(e,t,n){let r=new Uint8Array(i.memory.buffer,t,n),a=Math.max(0,n-l),o=e.createBuffer(1,a,u),s=o.getChannelData(0);for(let e=0;e<a;e++)s[e]=(r[l+e]-128)/128;return o}r.register(e.SOUND_START,e=>{let r=e.getInt32(0,!0),i=e.getInt32(4,!0),o=e.getUint32(8,!0),c=e.getInt32(12,!0),l=e.getInt32(16,!0),u=e.getInt32(20,!0),d=e.getInt32(24,!0);if(!t)return;let f=n.get(i);f||(f=s(t,o,c),n.set(i,f));let p=t.createBufferSource();p.buffer=f,p.playbackRate.value=g(d);let _=t.createStereoPanner();_.pan.value=h(u);let v=t.createGain();v.gain.value=m(l),p.connect(_).connect(v).connect(t.destination),p.onended=()=>{a.delete(r)},a.set(r,{src:p,gain:v,pan:_}),p.start()}),r.register(e.SOUND_STOP,e=>{let t=e.getInt32(0,!0),n=a.get(t);if(n){n.src.onended=null;try{n.src.stop()}catch{}a.delete(t)}}),r.register(e.SOUND_UPDATE,e=>{let t=e.getInt32(0,!0),n=e.getInt32(4,!0),r=e.getInt32(8,!0),i=e.getInt32(12,!0),o=a.get(t);o&&(o.gain.gain.value=m(n),o.pan.pan.value=h(r),o.src.playbackRate.value=g(i))}),r.register(e.MUSIC_SET_GENMIDI,e=>{let t=e.getUint32(0,!0),n=e.getInt32(4,!0);if(n<=0)return;let r=o(t,n);p({type:`setGenmidi`,data:r},[r])}),r.register(e.MUSIC_REGISTER,e=>{let t=e.getInt32(0,!0),n=e.getUint32(4,!0),r=e.getInt32(8,!0);if(r<=0)return;let i=o(n,r);p({type:`register`,handle:t,data:i},[i])}),r.register(e.MUSIC_PLAY,e=>{p({type:`play`,handle:e.getInt32(0,!0),looping:e.getInt32(4,!0)!==0})}),r.register(e.MUSIC_PAUSE,e=>{p({type:`pause`,handle:e.getInt32(0,!0)})}),r.register(e.MUSIC_RESUME,e=>{p({type:`resume`,handle:e.getInt32(0,!0)})}),r.register(e.MUSIC_STOP,e=>{p({type:`stop`,handle:e.getInt32(0,!0)})}),r.register(e.MUSIC_UNREGISTER,e=>{p({type:`unregister`,handle:e.getInt32(0,!0)})}),r.register(e.MUSIC_SET_VOLUME,e=>{p({type:`setVolume`,volume:e.getInt32(0,!0)})})}return{register:v,start(){t||(t=new AudioContext,_(t)),t.state===`suspended`&&t.resume()},suspend(){t&&t.state===`running`&&t.suspend()},resume(){t&&t.state===`suspended`&&t.resume()}}}var v=8,y=180224;function b(e,t){return[`wasmdoom`,`save`,e,String(t)].join(`:`)}function x(t){let{namespace:n}=t;function r(e){for(let t=0;t<v;t++){let r=localStorage.getItem(b(n,t));if(r===null)continue;let i;try{i=s(r)}catch(e){console.error(`[doom_host] could not decode save slot ${t}:`,e);continue}if(i.length>y){console.error(`[doom_host] save slot ${t} too large (${i.length} > ${y})`);continue}let a=e.wasmdoom_save_slot_ptr(t);new Uint8Array(e.memory.buffer,a,i.length).set(i),e.wasmdoom_save_commit(t,i.length)}}function i(t,r){t.register(e.SAVE_WRITTEN,e=>{let t=e.getUint32(0,!0),i=e.getUint32(4,!0),a=e.getUint32(8,!0),s=new Uint8Array(r.memory.buffer,i,a).slice();try{localStorage.setItem(b(n,t),o(s))}catch(e){console.error(`[doom_host] save_game(slot ${t}) failed`,e)}})}return{installAll:r,register:i}}var ee=[`wasmdoom_init`,`wasmdoom_argv_ptr`,`wasmdoom_wad_alloc`,`wasmdoom_tick`,`wasmdoom_keydown`,`wasmdoom_keyup`,`wasmdoom_send_mouse`,`wasmdoom_get_framebuffer`,`wasmdoom_get_palette`,`wasmdoom_events_ptr`,`wasmdoom_events_len`,`wasmdoom_events_clear`,`wasmdoom_save_slot_ptr`,`wasmdoom_save_commit`,`wasmdoom_snapshot_player`,`wasmdoom_player_snapshot_ptr`,`wasmdoom_apply_player`,`wasmdoom_snapshot_map_objects`,`wasmdoom_map_objects_ptr`,`wasmdoom_apply_map_objects`,`wasmdoom_snapshot_settings`,`wasmdoom_settings_ptr`,`wasmdoom_apply_settings`];function S(e){if(!(e.memory instanceof WebAssembly.Memory))throw Error("wasm module is missing a `memory` export");for(let t of ee)if(typeof e[t]!=`function`)throw Error(`wasm module is missing a \`${t}\` export`)}function C(e){switch(e.toLowerCase()){case`doom2.wad`:case`doom2f.wad`:case`plutonia.wad`:case`tnt.wad`:case`freedoom2.wad`:return`commercial`;case`doomu.wad`:case`freedoom1.wad`:return`retail`;case`doom.wad`:return`registered`;case`doom1.wad`:return`shareware`;default:return`indetermined`}}var w={doom1:`doom1.wad`,doom:`doom.wad`,doom2:`doom2.wad`,freedoom:`freedoom1.wad`,freedoom1:`freedoom1.wad`,freedoom2:`freedoom2.wad`,tnt:`tnt.wad`,chex:`CHEX.WAD`};function te(e){return w[e.toLowerCase()]}var ne=4096;function re(e,t,n){let r=new TextEncoder,i=n.map(e=>r.encode(e)),a=i.reduce((e,t)=>e+t.length+1,0)+1;if(a>4096)throw Error(`flags need ${a} bytes, exceeds ARGV_BUF_CAP (${ne})`);let o=new Uint8Array(e.buffer,t,ne),s=0;for(let e of i)o.set(e,s),s+=e.length,o[s++]=0;o[s]=0}async function ie(e){let{instance:t}=await WebAssembly.instantiateStreaming(fetch(e.wasmUrl)),{exports:n}=t;return S(n),{exports:n,loadWad(e){let t=n.wasmdoom_wad_alloc(e.length);if(t===0)throw Error(`wasmdoom_wad_alloc(${e.length}) failed`);new Uint8Array(n.memory.buffer,t,e.length).set(e)},init(e=[]){re(n.memory,n.wasmdoom_argv_ptr(),e),n.wasmdoom_init()}}}function ae(e,t,n){let r=e-t;return r<n?{tick:!1,nextLastFrame:t}:{tick:!0,nextLastFrame:e-r%n}}function oe(e){let t=1e3/e.fps,n=performance.now(),r=!1;function i(a){if(r)return;requestAnimationFrame(i);let o=ae(a,n,t);if(n=o.nextLastFrame,o.tick)try{e.tick()}catch(e){console.error(`[wasmdoom] tick failure:`,e),r=!0}}requestAnimationFrame(i)}var T=`dynamic`,E=`semi`,D=`static`,se=typeof window<`u`&&`ontouchstart`in window,ce={start:`mousedown`,move:`mousemove`,end:`mouseup, mouseleave`,pressure:`webkitmouseforcechanged`},O,k;typeof window<`u`&&window.PointerEvent?O={start:`pointerdown`,move:`pointermove`,end:`pointerup, pointercancel, pointerleave`,pressure:`webkitmouseforcechanged`}:se?(O={start:`touchstart`,move:`touchmove`,end:`touchend, touchcancel`,pressure:`webkitmouseforcechanged`},k=ce):O=ce;var A=O,j=k,M=Math.PI/4,le=Math.PI/2,N=(e,t)=>{let n=t.x-e.x,r=t.y-e.y;return Math.sqrt(n*n+r*r)},P=e=>Math.PI/180*e,ue=e=>180/Math.PI*e,F=new Map,I=e=>{F.has(e)&&clearTimeout(F.get(e)),F.set(e,setTimeout(e,100))},L=(e,t,n)=>{let r=t.split(/[ ,]+/g);for(let t=0;t<r.length;t+=1)e.addEventListener(r[t],n,!1)},R=(e,t,n)=>{let r=t.split(/[ ,]+/g);for(let t=0;t<r.length;t+=1)e.removeEventListener(r[t],n)},de=e=>`force`in e?e.force:`pressure`in e?e.pressure:`webkitForce`in e?e.webkitForce/3:+(`buttons`in e&&e.buttons!==0),fe=(e,t)=>({identifier:`identifier`in t?t.identifier:`pointerId`in t?t.pointerId:1,isTouch:`touches`in e||`changedTouches`in e,position:{x:t.pageX,y:t.pageY},pressure:de(t),type:e.type,initial:e,raw:t}),z=()=>({x:window.scrollX,y:window.scrollY}),pe=(e,t)=>{let{left:n,top:r,right:i,bottom:a,x:o,y:s}=t;r||i||a||n?V(e.style,{top:r,right:i,bottom:a,left:n}):(H(o)||H(s))&&V(e.style,{left:H(o)?`${o}px`:void 0,top:H(s)?`${s}px`:void 0})},B=(e,t=``)=>({[e]:t}),V=(e,t)=>{for(let n in t)Object.hasOwn(t,n)&&(e[n]=t[n]);return e},H=e=>typeof e==`number`&&!isNaN(e),U={debug:0,info:1,warning:2,error:3,none:4},W=`warning`,G=class{constructor(e){this.uid=0,this.index=0,this.name=`super`,this._domHandlers_=new Map,this._handlers_={},this.name=e,this.log(`construct`,this.name,this.index)}mapOnEvents(e,t){let n=e.split(/[ ,]+/g);for(let e=0;e<n.length;e+=1)t(n[e])}on(e,t){this.mapOnEvents(e,(e=>{this._handlers_[e]=this._handlers_[e]||new Set,this._handlers_[e].add(t)}))}off(e,t){e===void 0?this._handlers_={}:this.mapOnEvents(e,(e=>{t===void 0?this._handlers_[e]=new Set:this._handlers_[e]&&this._handlers_[e].delete(t)}))}trigger(e,t){this.mapOnEvents(e,(e=>{this.log(`- "${e}" [trigger]`);let n=this._handlers_[e];if(n&&n.size){let r=[...n];for(let n of r)n.call(this,{type:e,target:this,data:t})}}))}bindEvt(e,t,n){let r=e=>{for(let r of(e=>{e.type.toLowerCase().includes(`move`)&&e.preventDefault();let t=[];if(`changedTouches`in e)for(let n of e.changedTouches)n&&t.push(n);else t.push(e);return t.map((t=>fe(e,t)))})(e))this.log(`- "${t}" [dom:trigger:${r.identifier}]`),n.call(this,r)};this._domHandlers_.set(n,r),L(e,A[t],r),j?.[t]&&L(e,j[t],r)}unbindEvt(e,t,n){let r=this._domHandlers_.get(n);r?(R(e,A[t],r),j?.[t]&&R(e,j[t],r),this._domHandlers_.delete(n)):this.error(`Internal handler not found for event ${t}.`,n)}logPrefix(){return{super:``,joystick:` `,collection:` `,factory:` `}[this.name]}logSuffix(){return`[${this.name}|${this.uid}]`}static get logLevel(){return W}static set logLevel(e){W=e}log(...e){U[W]<=U.debug&&console.log(this.logPrefix(),...e,this.logSuffix())}info(...e){U[W]<=U.info&&console.info(this.logPrefix(),...e,this.logSuffix())}warn(...e){U[W]<=U.warning&&console.warn(this.logPrefix(),...e,this.logSuffix())}error(...e){U[W]<=U.error&&console.error(this.logPrefix(),...e,this.logSuffix())}},me=class e extends G{constructor(t,n){super(`joystick`),this.direction={},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.position=n.position,this.frontPosition=n.frontPosition,this.collection=t,this.options={...this.defaults,...n},this.options.mode===`dynamic`&&(this.options.restOpacity=0),this.uid=e.index++,this.ui={el:document.createElement(`div`),back:document.createElement(`div`),front:document.createElement(`div`)}}init(){this.options.dataOnly||this.buildEl(),this.trigger(`added`,this),this.trigger(`joystickCreated`,this)}get identifier(){return this._identifier}set identifier(e){H(e)?(this._identifier=e,this.trigger(`attached`,{collection:this.collection,joystick:this,identifier:e})):(this.trigger(`detached`,{collection:this.collection,joystick:this,identifier:this._identifier}),this._identifier=void 0)}resolveColors(){let e=this.options.color;return typeof e==`object`&&e?e:{front:e,back:e}}buildEl(){this.ui.el.className=`joystick collection_${this.collection.uid}`,this.ui.back.className=`back`,this.ui.front.className=`front`,this.ui.el.setAttribute(`id`,`joystick_${this.collection.uid}_${this.uid}`),this.ui.el.appendChild(this.ui.back),this.ui.el.appendChild(this.ui.front);let e=`${this.options.fadeTime}ms`,t=B(`borderRadius`,`50%`),n=B(`transition`,`opacity ${e}`),r=this.resolveColors();V(this.ui.el.style,{position:`absolute`,opacity:this.options.restOpacity.toString(),display:`block`,zIndex:`999`,touchAction:`none`,userSelect:`none`,...n}),V(this.ui.back.style,{position:`absolute`,display:`block`,width:`${this.options.size}px`,height:`${this.options.size}px`,left:`0`,marginLeft:-this.options.size/2+`px`,marginTop:-this.options.size/2+`px`,background:r.back,...this.options.shape===`circle`?t:{}}),V(this.ui.front.style,{width:this.options.size/2+`px`,height:this.options.size/2+`px`,position:`absolute`,display:`block`,left:`0`,marginLeft:-this.options.size/4+`px`,marginTop:-this.options.size/4+`px`,background:r.front,opacity:`.5`,transform:`translate(0px, 0px)`,...t})}get pressure(){return this._pressure??0}set pressure(e){e!==this._pressure&&(this._pressure=e,this.trigger(`pressure`,e))}startPressureInterval(e){this.pressureInterval||=window.setInterval((()=>{this.pressure=de(e)}),100)}stopPressureInterval(){clearInterval(this.pressureInterval),this.pressureInterval=void 0}addToDom(){this.options.dataOnly||this.options.zone.contains(this.ui.el)||this.options.zone.appendChild(this.ui.el)}removeFromDom(){!this.options.dataOnly&&this.options.zone.contains(this.ui.el)&&this.options.zone.removeChild(this.ui.el)}clearTimeouts(){clearTimeout(this.removeTimeout),clearTimeout(this.showTimeout),clearTimeout(this.restTimeout),clearTimeout(this.activeTimeout),this.removeTimeout=void 0,this.showTimeout=void 0,this.restTimeout=void 0,this.activeTimeout=void 0}start(e,t){this.trigger(`start`,this),this.clearTimeouts(),this.options.dataOnly?typeof t==`function`&&t.call(this):(this.addToDom(),this.startPressureInterval(e),requestAnimationFrame((()=>{this.ui.el.style.opacity=`1`})),this.showTimeout=window.setTimeout((()=>{this.showTimeout=void 0,this.trigger(`shown`,this),typeof t==`function`&&t.call(this)}),this.options.fadeTime))}end(e){if(this.resetDirection(),this.clearTimeouts(),this.stopPressureInterval(),this.pressure=0,this.trigger(`end`,this),this.options.dataOnly)typeof e==`function`&&e.call(this);else{if(this.ui.el.style.opacity=this.options.restOpacity.toString(),this.options.restJoystick){let t=this.options.restJoystick,n={x:!0===t||!1!==t.x?0:this.frontPosition.x,y:!0===t||!1!==t.y?0:this.frontPosition.y};this.setPosition(e,n)}clearTimeout(this.removeTimeout),this.removeTimeout=window.setTimeout((()=>{this.removeTimeout=void 0,this.ui.el.style.display=this.options.mode===T?`none`:`block`,this.trigger(`hidden`,this),this.options.mode===T&&(this.trigger(`removed`,this),this.destroy()),typeof e==`function`&&e.call(this)}),this.options.fadeTime)}}setTransition(e=!1,t){if(e){let e=V(B(`transition`,`transform 100ms`),B(`transform`,`translate(${this.frontPosition.x}px, ${this.frontPosition.y}px)`));V(this.ui.front.style,e),clearTimeout(this.activeTimeout),this.activeTimeout=window.setTimeout((()=>{this.activeTimeout=void 0,typeof t==`function`&&t.call(this)}),100)}else V(this.ui.front.style,B(`transition`,`none`))}setPosition(e,t){this.frontPosition={x:t.x,y:t.y},this.setTransition(!0),clearTimeout(this.restTimeout),this.restTimeout=window.setTimeout((()=>{this.restTimeout=void 0,typeof e==`function`&&e.call(this),this.setTransition(!1),this.trigger(`rested`,this)}),this.options.fadeTime)}resetDirection(){this.direction={}}computeDirectionAndTriggerEvents(e){let t=e.angle.radian,n={};return t>M&&t<3*M&&!e.lockX?n.angle=`up`:t>-M&&t<=M&&!e.lockY?n.angle=`left`:t>3*-M&&t<=-M&&!e.lockX?n.angle=`down`:e.lockY||(n.angle=`right`),e.lockY||(n.x=t>-le&&t<le?`left`:`right`),e.lockX||(n.y=t>0?`up`:`down`),e.angle={radian:P(180-e.angle.degree),degree:180-e.angle.degree},this.triggerDirectionEvents(e,n),e}triggerDirectionEvents(e,t){if(e.force>this.options.threshold){let n={x:this.direction.x,y:this.direction.y,angle:this.direction.angle};this.direction=t,e.direction=t,n.x!==t.x&&this.trigger(`plain plain:${t.x}`,e),n.y!==t.y&&this.trigger(`plain plain:${t.y}`,e),n.angle!==t.angle&&this.trigger(`dir dir:${t.angle}`,e)}else this.resetDirection();this.trigger(`move`,e)}destroy(){this.clearTimeouts(),this.identifier=void 0,this.removeFromDom(),this.trigger(`joystickDestroyed`,this),this.off()}};me.index=0;var he=me,ge=class e extends G{constructor(t,n){super(`collection`),this.all=new Map,this.idles=new Set,this.actives=new Map,this.resting=new Map,this.parentIsFlex=!1,this.defaults={catchDistance:200,color:`white`,dataOnly:!1,dynamicPage:!1,fadeTime:250,follow:!1,lockX:!1,lockY:!1,maxNumberOfJoysticks:10,mode:T,multitouch:!1,position:{top:`0px`,left:`0px`},restJoystick:!0,restOpacity:.5,shape:`circle`,size:100,threshold:.1,zone:document.body},this.factory=t,this.uid=e.index++,this.options={...this.defaults,...n},this.options.mode!==D&&this.options.mode!==E||(this.options.multitouch=!1),this.options.multitouch||(this.options.maxNumberOfJoysticks=1),(this.options.zone.parentElement&&getComputedStyle(this.options.zone.parentElement))?.display===`flex`&&(this.parentIsFlex=!0),getComputedStyle(this.options.zone).position===`static`&&this.warn(`The zone element has no CSS "position" set (it is "static").`,`Joysticks may not be positioned correctly.`,`Set "position: relative" (or absolute/fixed) on the zone element.`),this.box=this.options.zone.getBoundingClientRect(),this.bindEvt(this.options.zone,`start`,this.processOnStart),V(this.options.zone.style,{touchAction:`none`,userSelect:`none`,webkitUserSelect:`none`}),typeof ResizeObserver<`u`&&(this.resizeObserver=new ResizeObserver((()=>{this.reposition()})),this.resizeObserver.observe(this.options.zone))}init(){this.trigger(`collectionCreated`,this),this.options.mode===D&&this.createJoystick(this.options.position).addToDom()}getJoystickByUid(e){return e===void 0?this.all.values().next().value:this.all.get(e)}bindJoystick(e){e.on(`joystickDestroyed`,(()=>{this.deleteJoystickFromLists(e)})),e.on(`attached`,(t=>{this.idles.delete(t.data.joystick.uid),this.actives.set(t.data.identifier,e)})),e.on(`detached`,(e=>{this.idles.add(e.data.joystick.uid),this.deleteIdentifierFromLists(e.data.identifier)})),e.on(`end`,(t=>{H(t.data.identifier)&&(this.actives.delete(t.data.identifier),this.resting.set(t.data.identifier,e)),this.idles.add(t.data.uid)})),e.on(`start`,(e=>{H(e.data.identifier)&&this.resting.delete(e.data.identifier)})),e.on(`hidden`,(e=>{H(e.data.identifier)&&this.resting.delete(e.data.identifier)})),e.on(`pressure`,(t=>{this.trigger(`pressure ${e.uid}:pressure`,t.data)})),e.on(`attached detached`,(e=>{let t=`${e.type} ${e.data.joystick.uid}:${e.type}`;this.trigger(t,e.data)})),e.on(`added start shown hidden rested removed end joystickCreated joystickDestroyed`,(e=>{let t=`${e.type} ${e.data.uid}:${e.type}`;this.trigger(t,e.data)})),e.on(`move`,(e=>{this.trigger(`move ${e.data.instance.uid}:move`,e.data)})),e.on(`dir dir:up dir:right dir:down dir:left`,(e=>{let t=`${e.type} ${e.data.instance.uid}:${e.type}`;this.trigger(t,e.data)})),e.on(`plain plain:up plain:right plain:down plain:left`,(e=>{let t=`${e.type} ${e.data.instance.uid}:${e.type}`;this.trigger(t,e.data)}))}deleteJoystickFromLists(e){this.deleteUidFromLists(e.uid),H(e.identifier)&&this.deleteIdentifierFromLists(e.identifier)}deleteUidFromLists(e){this.all.delete(e),this.idles.delete(e)}deleteIdentifierFromLists(e){this.actives.delete(e),this.resting.delete(e)}getOrCreate(e){if(this.options.mode===E||this.options.mode===D){let t=this.idles.values().next().value;if(H(t)){let e=this.all.get(t);if(e)return e;this.error(`Couldn't find the joystick ${t}. Creating a new one.`),this.deleteUidFromLists(t)}if(this.options.mode===E)return this.createJoystick(e);this.warn(`Couldn't find the expected joystick. Creating a new one.`)}return this.createJoystick(e)}createJoystick(e){let t=this.factory.scroll,n=this.parentIsFlex?t.x:t.x+this.box.left,r=this.parentIsFlex?t.y:t.y+this.box.top,i,a;if(H(e.x)&&H(e.y))i={x:e.x-n,y:e.y-r},a={x:e.x,y:e.y};else{if(!(e.top||e.right||e.bottom||e.left))return void this.error(`Invalid or missing position.`,e);{let n=document.createElement(`DIV`);V(n.style,{visibility:`hidden`,position:`absolute`,top:e.top,right:e.right,bottom:e.bottom,left:e.left}),this.options.zone.appendChild(n);let r=n.getBoundingClientRect();this.options.zone.removeChild(n),i=e,a={x:r.left+t.x,y:r.top+t.y}}}let o=new he(this,{color:this.options.color,size:this.options.size,threshold:this.options.threshold,fadeTime:this.options.fadeTime,dataOnly:this.options.dataOnly,restJoystick:this.options.restJoystick,restOpacity:this.options.restOpacity,mode:this.options.mode,position:a,zone:this.options.zone,frontPosition:{x:0,y:0},shape:this.options.shape});return this.all.has(o.uid)&&this.error(`Joystick with uid ${o.uid} already exists.`),this.options.dataOnly||(pe(o.ui.el,i),pe(o.ui.front,o.frontPosition)),this.all.set(o.uid,o),this.idles.add(o.uid),this.bindJoystick(o),o.init(),o}processOnStart(e,t=0){if(this.box=this.options.zone.getBoundingClientRect(),!this.actives.has(e.identifier)&&this.actives.size>=this.options.maxNumberOfJoysticks)return void this.warn(`No more joysticks allowed.`);let n=this.actives.get(e.identifier)||this.resting.get(e.identifier)||this.getOrCreate(e.position),r=()=>{n.start(e.raw),n.identifier=e.identifier,this.processOnMove(e,!0)};this.options.mode===E?N(e.position,n.position)<=this.options.catchDistance?r():t<3?(n.destroy(),this.processOnStart(e,t+1)):this.error(`Max semi-mode recursion depth reached.`):r()}processOnMove(e,t=!1){let n=this.actives.get(e.identifier),r=this.factory.scroll;if(!n)return this.error(`Found zombie joystick onMove with identifier ${e.identifier}`),void this.deleteIdentifierFromLists(e.identifier);this.options.dynamicPage&&this.reposition();let i=n.options.size/2,a={x:e.position.x,y:e.position.y};this.options.lockX&&(a.y=n.position.y),this.options.lockY&&(a.x=n.position.x);let o=N(a,n.position),s=((e,t)=>{let n=t.x-e.x,r=t.y-e.y;return ue(Math.atan2(r,n))})(a,n.position),c=P(s),l=o/i,u={distance:o,position:a},d,f;n.options.shape===`circle`?(d=Math.min(o,i),f=((e,t,n)=>{let r=P(n);return{x:e.x-t*Math.cos(r),y:e.y-t*Math.sin(r)}})(n.position,d,s)):(f=((e,t,n)=>({x:Math.min(Math.max(e.x,t.x-n),t.x+n),y:Math.min(Math.max(e.y,t.y-n),t.y+n)}))(a,n.position,i),d=N(f,n.position));let p={x:0,y:0};if(this.options.follow){if(o>i){let e=a.x-f.x,t=a.y-f.y;p={x:e,y:-t},n.position.x+=e,n.position.y+=t,V(n.ui.el.style,{top:n.position.y-(this.box.top+r.y)+`px`,left:n.position.x-(this.box.left+r.x)+`px`}),o=N(a,n.position)}}else a=f,o=d;let m=a.x-n.position.x,h=a.y-n.position.y;n.frontPosition={x:m,y:h},this.options.dataOnly||(t&&n.setTransition(!0,(()=>{n.setTransition(!1)})),n.ui.front.style.transform=`translate(${m}px,${h}px)`);let g={position:a,force:l,pressure:e.pressure,distance:o,angle:{radian:c,degree:s},vector:{x:m/i,y:-h/i},raw:u,instance:n,lockX:this.options.lockX,lockY:this.options.lockY,baseDelta:p};n.computeDirectionAndTriggerEvents(g)}processOnEnd(e){let t=this.actives.get(e.identifier);if(!t)return this.error(`Found zombie joystick onEnd with identifier ${e.identifier}`),void this.deleteIdentifierFromLists(e.identifier);t.end()}reposition(){this.factory.scroll=z(),this.box=this.options.zone.getBoundingClientRect();let e=this.factory.scroll;this.all.forEach((t=>{if(t.options.dataOnly)return;let n=t.ui.el.getBoundingClientRect();t.position={x:e.x+n.left,y:e.y+n.top}}))}destroy(){this.resizeObserver&&=(this.resizeObserver.disconnect(),void 0),this.unbindEvt(this.options.zone,`start`,this.processOnStart),this.all.forEach((e=>{e.destroy()})),this.all.clear(),this.idles.clear(),this.actives.clear(),this.resting.clear(),this.trigger(`collectionDestroyed`,this),this.off()}};ge.index=0;var _e=ge,ve=new class extends G{constructor(){super(`factory`),this.scroll=z(),this.binded=!1,this.joysticksByUid=new Map,this.joysticksByIdentifier=new Map,this.collections=new Set,this.resizeHandler=null,this.scrollHandler=null,this.repositionAll=()=>{this.collections.forEach((e=>{e.reposition()}))},this.refreshScroll=()=>{this.scroll=z()},this.bindResize(),this.bindScroll(),this.trigger(`factoryCreated`,this)}bindResize(){this.resizeHandler=()=>I(this.repositionAll),L(window,`resize`,this.resizeHandler)}bindScroll(){this.scrollHandler=()=>I(this.refreshScroll),L(window,`scroll`,this.scrollHandler)}getJoystickByUid(e){return this.joysticksByUid.get(e)}getJoystickByIdentifier(e){return this.joysticksByIdentifier.get(e)}create(e){let t=new _e(this,e);return this.bindCollection(t),this.collections.add(t),t.init(),t}removeJoystickFromLists(e){this.joysticksByUid.delete(e.uid),H(e.identifier)&&this.joysticksByIdentifier.delete(e.identifier)}bindCollection(e){e.on(`collectionDestroyed`,(e=>{this.collections.delete(e.data),e.data.all.forEach((e=>{this.removeJoystickFromLists(e)})),this.unbindDocument()})),e.on(`joystickDestroyed`,(e=>{this.removeJoystickFromLists(e.data),this.unbindDocument()})),e.on(`end`,(e=>{H(e.data.identifier)&&this.joysticksByIdentifier.delete(e.data.identifier),this.unbindDocument()})),e.on(`added`,(e=>{this.joysticksByUid.set(e.data.uid,e.data),this.bindDocument()})),e.on(`attached`,(e=>{this.joysticksByIdentifier.set(e.data.identifier,e.data.joystick)})),e.on(`pressure`,(e=>{this.trigger(`pressure ${e.target.uid}:pressure`,e.data)})),e.on(`collectionCreated collectionDestroyed`,(e=>{let t=`${e.type} ${e.data.uid}:${e.type}`;this.trigger(t,e.data)})),e.on(`attached detached`,(e=>{let t=`${e.type} ${e.data.joystick.uid}:${e.type}`;this.trigger(t,e.data)})),e.on(`added start shown hidden rested removed end joystickCreated joystickDestroyed`,(e=>{let t=`${e.type} ${e.data.uid}:${e.type}`;this.trigger(t,e.data)})),e.on(`move`,(e=>{this.trigger(`move ${e.data.instance.uid}:move`,e.data)})),e.on(`dir dir:up dir:right dir:down dir:left`,(e=>{let t=`${e.type} ${e.data.instance.uid}:${e.type}`;this.trigger(t,e.data)})),e.on(`plain plain:up plain:right plain:down plain:left`,(e=>{let t=`${e.type} ${e.data.instance.uid}:${e.type}`;this.trigger(t,e.data)}))}cleanInactiveTouches(e){let t=`touches`in e.initial?Array.from(e.initial.touches).map((e=>e.identifier)):[e.identifier];this.log(`Cleaning inactive`,t,Array.from(this.joysticksByIdentifier.keys()));for(let[n,r]of this.joysticksByIdentifier)if(r.collection.options.mode===T&&!t.includes(n)){if(!r)return void this.error(`No collection found for cleaning identifier ${n}`);this.log(`💣 Cleaning`,n);let t=e.raw;r.collection.processOnEnd(fe(e.initial,{identifier:n,pageX:t.pageX,pageY:t.pageY,clientX:t.clientX,clientY:t.clientY}))}}bindDocument(){this.binded||=(this.log(`bind dom`),this.bindEvt(document,`start`,this.onstart),this.bindEvt(document,`move`,this.onmove),this.bindEvt(document,`end`,this.onend),this.bindEvt(document,`pressure`,this.onpressure),!0)}unbindDocument(e=!1){!this.binded||this.joysticksByUid.size&&!0!==e||(this.log((e?`force `:``)+`unbind dom`),this.unbindEvt(document,`start`,this.onstart),this.unbindEvt(document,`move`,this.onmove),this.unbindEvt(document,`end`,this.onend),this.unbindEvt(document,`pressure`,this.onpressure),this.binded=!1)}onstart(e){this.cleanInactiveTouches(e)}onmove(e){this.handleEventInCollection(e,(t=>{t.processOnMove(e)}))}onend(e){this.cleanInactiveTouches(e),this.handleEventInCollection(e,(t=>{t.processOnEnd(e)}))}onpressure(e){e.initial.preventDefault();let t=this.joysticksByIdentifier.get(e.identifier);t?t.pressure=e.pressure:this.error(`No joystick found for pressure event ${e.identifier}`)}handleEventInCollection(e,t){let n=this.joysticksByIdentifier.get(e.identifier);n&&t(n.collection)}destroy(){this.unbindDocument(!0),this.collections.forEach((e=>{e.destroy()})),this.resizeHandler&&=(R(window,`resize`,this.resizeHandler),null),this.scrollHandler&&=(R(window,`scroll`,this.scrollHandler),null),this.trigger(`factoryDestroyed`,this),this.off()}},ye={create:e=>ve.create(e),factory:ve,setLogLevel:e=>{G.logLevel=e},getLogLevel:()=>G.logLevel},K=class e{x;y;constructor(e=0,t=0){this.x=e,this.y=t}static zero(){return new e(0,0)}static from(t){return new e(t.x,t.y)}add(t){return new e(this.x+t.x,this.y+t.y)}setX(t){return new e(t,this.y)}setY(t){return new e(this.x,t)}sub(t){return new e(this.x-t.x,this.y-t.y)}equals(e){return this.x===e.x&&this.y===e.y}toString(){return`(${this.x}, ${this.y})`}},q={RIGHT:174,LEFT:172,UP:173,DOWN:175,MOVE_FORWARD:173,MOVE_BACKWARD:175,TURN_LEFT:172,TURN_RIGHT:174,STRAFE_LEFT:44,STRAFE_RIGHT:46,STRAFE_ON:184,FIRE:157,USE:32,RUN:182,WEAPON_1:49,WEAPON_2:50,WEAPON_3:51,WEAPON_4:52,WEAPON_5:53,WEAPON_6:54,WEAPON_7:55,MENU_OPEN:27,MENU_CONFIRM:13,MENU_BACK:127,PAUSE:255,VIEW_SIZE_UP:61,VIEW_SIZE_DOWN:45,AUTOMAP_TOGGLE:9,AUTOMAP_FOLLOW:102,AUTOMAP_GRID:103,AUTOMAP_MARK:109,AUTOMAP_CLEARMARK:99,AUTOMAP_GOBIG:48,HELP:187,SAVE:188,LOAD:189,SOUND_VOLUME:190,DETAIL:191,QUICKSAVE:192,END_GAME:193,MESSAGES:194,QUICKLOAD:195,QUIT:196,GAMMA:215,SPY:216},J={FIRE:1,STRAFE:2,USE:4},Y={health:0,armorpoints:4,armortype:8,readyweapon:12,pendingweapon:16,backpack:20,cheats:24,killcount:28,itemcount:32,secretcount:36,playerstate:40,damagecount:44,bonuscount:48,attackdown:52,usedown:56,refire:60,cards:64,weapons:68,ammo:72,maxammo:88,powers:104,x:128,y:132,z:136,angle:140,momx:144,momy:148,momz:152,dirty:156,faceindex:160},be={health:1,armorpoints:2,armortype:4,readyweapon:8,pendingweapon:16,backpack:32,cheats:64,killcount:128,itemcount:256,secretcount:512,playerstate:1024,damagecount:2048,bonuscount:4096,attackdown:8192,usedown:16384,refire:32768,cards:65536,weapons:1<<17,ammo:1<<18,maxammo:1<<19,powers:1<<20,pos:1<<21},X={gamestate:0,gameepisode:4,gamemap:8,gameskill:12,sfx_volume:16,music_volume:20,mouse_sensitivity:24,show_messages:28,screenblocks:32,detail_level:36,menuactive:40,save_string_enter:44,dirty:48},xe=9,Se=24,Ce=new Map([[`KeyW`,q.MOVE_FORWARD],[`KeyS`,q.MOVE_BACKWARD],[`KeyA`,q.STRAFE_LEFT],[`KeyD`,q.STRAFE_RIGHT],[`ArrowUp`,q.UP],[`ArrowDown`,q.DOWN],[`ArrowLeft`,q.LEFT],[`ArrowRight`,q.RIGHT],[`Enter`,q.MENU_CONFIRM],[`Space`,q.FIRE],[`ShiftLeft`,q.RUN],[`KeyE`,q.USE],[`Comma`,q.STRAFE_LEFT],[`Period`,q.STRAFE_RIGHT],[`Backspace`,q.MENU_BACK],[`KeyQ`,q.MENU_OPEN],[`Tab`,q.AUTOMAP_TOGGLE],[`Minus`,q.VIEW_SIZE_DOWN],[`Equal`,q.VIEW_SIZE_UP],[`KeyF`,q.AUTOMAP_FOLLOW],[`KeyG`,q.AUTOMAP_GRID],[`KeyM`,q.AUTOMAP_MARK],[`KeyC`,q.AUTOMAP_CLEARMARK],[`Digit0`,q.AUTOMAP_GOBIG],[`Digit1`,q.WEAPON_1],[`Digit2`,q.WEAPON_2],[`Digit3`,q.WEAPON_3],[`Digit4`,q.WEAPON_4],[`Digit5`,q.WEAPON_5],[`Digit6`,q.WEAPON_6],[`Digit7`,q.WEAPON_7],[`F1`,q.HELP],[`F2`,q.SAVE],[`F3`,q.LOAD],[`F4`,q.SOUND_VOLUME],[`F5`,q.DETAIL],[`F6`,q.QUICKSAVE],[`F7`,q.END_GAME],[`F8`,q.MESSAGES],[`F9`,q.QUICKLOAD],[`F10`,q.QUIT],[`F11`,q.GAMMA],[`F12`,q.SPY]]),we=[J.FIRE,J.STRAFE,J.USE];function Te(e){let{canvas:t,doom:n,audio:r,recorder:i}=e,o=a(typeof navigator>`u`?void 0:navigator),s=0,c=K.zero();window.addEventListener(`keydown`,e=>{let t=!1,r=Ce.get(e.code);if(r!==void 0&&(n.wasmdoom_keydown(r),i?.key(`keydown`,r),t=!0),e.key.length===1){let r=e.key.charCodeAt(0);r>=32&&r<=126&&(n.wasmdoom_keydown(256|r),i?.key(`keydown`,256|r),t=!0)}t&&e.preventDefault()}),window.addEventListener(`keyup`,e=>{let t=Ce.get(e.code);t!==void 0&&(e.preventDefault(),n.wasmdoom_keyup(t),i?.key(`keyup`,t))}),t.addEventListener(`click`,()=>{r.start()}),t.addEventListener(`contextmenu`,e=>e.preventDefault()),document.addEventListener(`mousemove`,e=>{document.pointerLockElement===t&&(c=c.add(new K(e.movementX,0)))}),document.addEventListener(`mousedown`,e=>{if(document.pointerLockElement!==t)return;let n=we[e.button];n!==void 0&&(s|=n)}),document.addEventListener(`mouseup`,e=>{if(document.pointerLockElement!==t)return;let n=we[e.button];n!==void 0&&(s&=~n)});let l=o?je(n):null;return{flushFrame(){l&&(l.syncUiMode(),c=c.add(l.fetchJoystick())),n.wasmdoom_send_mouse(s,c.x,c.y),i?.mouse(s,c.x,c.y),c=K.zero()}}}var Ee=.3,De=200,Oe=.15,ke=100,Ae=.15;function je(e){let t=document.getElementById(`mobile-controls`),n=document.getElementById(`joystick-left-zone`),r=document.getElementById(`joystick-right-zone`),i=document.getElementById(`fire-btn`),a=document.getElementById(`use-btn`),o=document.getElementById(`back-btn`),s=document.getElementById(`menu-btn`),c=document.getElementById(`weapon-btn`),l=document.getElementById(`dpad-up`),u=document.getElementById(`dpad-down`),d=document.getElementById(`dpad-left`),f=document.getElementById(`dpad-right`);if(!t||!n||!r||!i||!a||!o||!s||!c||!l||!u||!d||!f)return null;t.classList.add(`visible`),Z(i,e,q.FIRE),Z(i,e,q.MENU_CONFIRM),Z(a,e,q.USE),Z(a,e,q.MENU_CONFIRM),Z(s,e,q.MENU_OPEN),Z(o,e,q.MENU_OPEN),Z(l,e,q.UP),Z(u,e,q.DOWN),Z(d,e,q.LEFT),Z(f,e,q.RIGHT);let p=t=>{if(t.preventDefault(),c.classList.add(`pressed`),!e.wasmdoom_snapshot_player())return;let n=e.wasmdoom_player_snapshot_ptr(),r=new DataView(e.memory.buffer),i=r.getInt32(n+Y.weapons,!0),a=r.getInt32(n+Y.readyweapon,!0),o=-1;for(let e=1;e<=xe;e++){let t=(a+e)%xe;if(t!==a&&i&1<<t){o=t;break}}if(o<0)return;r.setInt32(n+Y.pendingweapon,o,!0);let s=r.getUint32(n+Y.dirty,!0);r.setUint32(n+Y.dirty,s|be.pendingweapon,!0),e.wasmdoom_apply_player()},m=e=>{e.preventDefault(),c.classList.remove(`pressed`)};c.addEventListener(`touchstart`,p,{passive:!1}),c.addEventListener(`touchend`,m,{passive:!1}),c.addEventListener(`touchcancel`,m,{passive:!1}),c.addEventListener(`mousedown`,p),c.addEventListener(`mouseup`,m),c.addEventListener(`mouseleave`,m);let h=ye.create({zone:n,mode:`static`,position:{left:`50%`,top:`50%`},color:`white`,size:150,restJoystick:!0,shape:`square`}),g=ye.create({zone:r,mode:`static`,position:{left:`50%`,top:`50%`},color:`white`,size:150,restJoystick:!0,shape:`square`}),_={left:!1,right:!1},v=K.zero(),y=(t,n,r)=>{_[t]!==r&&(_[t]=r,r?e.wasmdoom_keydown(n):e.wasmdoom_keyup(n))},b=null;h.on(`move`,e=>{let t=e.data;if(!t||!t.vector)return;let n=K.from(t.vector);b===null&&(b=n);let r=n.sub(b);v=v.setY(r.y),y(`left`,q.STRAFE_LEFT,r.x<-Ee),y(`right`,q.STRAFE_RIGHT,r.x>Ee)}),h.on(`end`,()=>{v=v.setY(0),y(`left`,q.STRAFE_LEFT,!1),y(`right`,q.STRAFE_RIGHT,!1),b=null});let x=null;g.on(`move`,e=>{let t=e.data;if(!t||!t.vector)return;let n=K.from(t.vector);x===null&&(x=n),v=v.setX(n.sub(x).x)}),g.on(`end`,()=>{v=v.setX(0),x=null});let ee=()=>{y(`left`,q.STRAFE_LEFT,!1),y(`right`,q.STRAFE_RIGHT,!1),v=K.zero(),b=null,x=null;for(let t of[q.UP,q.DOWN,q.LEFT,q.RIGHT])e.wasmdoom_keyup(t)},S=(t,n)=>{for(let t=0;t<Se-1;t++)e.wasmdoom_keydown(q.MENU_BACK);let r=t.getInt32(n+X.gameepisode,!0),i=t.getInt32(n+X.gamemap,!0),a=new Date,o=`E${r}M${i} ${String(a.getHours()).padStart(2,`0`)}:${String(a.getMinutes()).padStart(2,`0`)}`;for(let t=0;t<o.length;t++)e.wasmdoom_keydown(256|o.charCodeAt(t));e.wasmdoom_keydown(q.MENU_CONFIRM)},C=!1,w=!1;return{syncUiMode(){e.wasmdoom_snapshot_settings();let n=e.wasmdoom_settings_ptr(),r=new DataView(e.memory.buffer),i=r.getInt32(n+X.save_string_enter,!0)!==0;i&&!w&&S(r,n),w=i;let a=r.getInt32(n+X.menuactive,!0)!==0;a!==C&&(C=a,t.classList.toggle(`menu-mode`,a),ee())},fetchJoystick(){let e=0,t=0;return Math.abs(v.x)>=Oe&&(e=Math.round(Math.sign(v.x)*v.x*v.x*De)),Math.abs(v.y)>=Ae&&(t=Math.round(v.y*ke)),new K(e,t)}}}function Z(e,t,n){let r=r=>{r.preventDefault(),e.classList.add(`pressed`),t.wasmdoom_keydown(n)},i=r=>{r.preventDefault(),e.classList.remove(`pressed`),t.wasmdoom_keyup(n)};e.addEventListener(`touchstart`,r,{passive:!1}),e.addEventListener(`touchend`,i,{passive:!1}),e.addEventListener(`touchcancel`,i,{passive:!1}),e.addEventListener(`mousedown`,r),e.addEventListener(`mouseup`,i),e.addEventListener(`mouseleave`,i)}var Me=320,Ne=200,Pe=Me*Ne,Fe=256*3;function Ie(e,t,n){for(let r=0;r<e.length;r++){let i=e[r]*3,a=r*4;n[a+0]=t[i+0],n[a+1]=t[i+1],n[a+2]=t[i+2],n[a+3]=255}}function Le(e){let t=e.getContext(`2d`);if(t===null)throw Error(`failed to get 2d rendering context`);let n=t.createImageData(Me,Ne);return{drawFrame(e){Ie(new Uint8Array(e.memory.buffer,e.wasmdoom_get_framebuffer(),Pe),new Uint8Array(e.memory.buffer,e.wasmdoom_get_palette(),Fe),n.data),t.putImageData(n,0,0)}}}function Re(e){if(typeof window>`u`||!new URLSearchParams(window.location.search).has(`record`))return null;let t=[...e.flags],n=[],r=0,i=0,a={key(e,t){n.push({tick:r,type:e,key:t})},mouse(e,t,a){e===i&&t===0&&a===0||(i=e,n.push({tick:r,type:`mouse`,buttons:e,dx:t,dy:a}))},endTick(){r++}},o=()=>{let e=n.length?n[n.length-1].tick:0;return{ticks:Math.max(r,e+1,1),flags:t,commands:n}};return window.__doomExport=()=>{let e=new Blob([JSON.stringify(o(),null,2)+`
`],{type:`application/json`}),t=URL.createObjectURL(e),r=document.createElement(`a`);r.href=t,r.download=`recording.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(t),console.log(`[recorder] exported ${n.length} command(s) over ${o().ticks} ticks`)},console.log(`[recorder] recording active — call window.__doomExport() to download recording.json`),a}function ze(e,t){let n=e=>e.replace(/^\/+/,``),r=n(n(e).slice(n(t).length)).match(/^wad\/([^/]+)\/?$/);return r&&te(r[1])||`doom1.wad`}function Q(e,t,n){if(e===null||!/^\d+$/.test(e))return null;let r=Number(e);return r>=t&&r<=n?r:null}function Be(e){let t=[],n=Q(e.get(`skill`),1,5);n!==null&&t.push(`-skill`,String(n));let r=e.get(`warp`);if(r!==null){let e=r.match(/\d+/g)?.slice(0,2);e&&e.length>0&&t.push(`-warp`,...e)}let i=Q(e.get(`episode`),1,9);i!==null&&t.push(`-episode`,String(i));let a=Q(e.get(`turbo`),10,400);a!==null&&t.push(`-turbo`,String(a));for(let n of[`nomonsters`,`respawn`,`fast`])e.has(n)&&t.push(`-${n}`);return t}var{BASE_URL:$}={BASE_URL:`./`};async function Ve(){let t=document.getElementById(`screen`);if(!(t instanceof HTMLCanvasElement))throw Error(`missing #screen canvas element`);let r=ze(window.location.pathname,$),a=Le(t),o=x({namespace:r}),s=_(),c=await ie({wasmUrl:i($,`wasmdoom.wasm`)}),l=await fetch(i($,`wads/${r}`)),u=new Uint8Array(await l.arrayBuffer());c.loadWad(u),o.installAll(c.exports);let d=n(c.exports);s.register(d,c.exports),o.register(d,c.exports);let f=e=>new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));d.register(e.ERROR,e=>console.error(`[doom_engine] ${f(e)}`)),d.register(e.INFO,e=>console.log(`[doom_engine] ${f(e)}`)),d.register(e.WARNING,e=>console.warn(`[doom_engine] ${f(e)}`));let p=new URLSearchParams(window.location.search),m=[`-mode`,C(r),...Be(p)];c.init(m),d.drain();let h=Re({flags:m}),g=Te({canvas:t,doom:c.exports,audio:s,recorder:h});document.addEventListener(`visibilitychange`,()=>{document.hidden?s.suspend():s.resume()}),oe({fps:35,tick:()=>{g.flushFrame();try{c.exports.wasmdoom_tick(),h?.endTick()}finally{d.drain()}a.drawFrame(c.exports)}})}Ve().catch(e=>{console.error(e)});