c64-ready 0.11.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -108,6 +108,13 @@ and native snapshots (`.c64`, `.snapshot`, `.s64`).
108
108
 
109
109
  Note: VICE `.vsf` snapshots are currently disabled in the browser runtime.
110
110
 
111
+ ### Keyboard limitations (current WASM build)
112
+
113
+ - The C64 `RESTORE` key is currently not functional in this build.
114
+ - We verified browser key mapping for `Page Up` is received, but the underlying
115
+ WASM core does not appear to trigger restore behavior from key input.
116
+ - Treat this as a runtime limitation of the shipped binary for now.
117
+
111
118
  ### Environment variables
112
119
 
113
120
  All options live in `docker/.env` (copy from `docker/.env.example`). See that file for
@@ -540,9 +547,10 @@ On every push to `master`:
540
547
  - [x] Docker headless streaming (RTMP / HTTP-FLV via Node Media Server)
541
548
  - [ ] Gamepad support
542
549
  - [ ] Touch controls
543
- - [ ] Loading more game formats (e.g., .d64 disk images)
550
+ - [ ] Mobile Layout
551
+ - [x] Loading more game formats (e.g., .d64 disk images)
544
552
  - [ ] Performance optimizations (e.g., offscreen canvas, audio worklets)
545
- - [ ] Fix creeping video jitter (currently starts at 100ms and grows over time)
553
+ - [ ] Jitter creep - frame timing optimizations for smoother rendering
546
554
 
547
555
  ## Changelog & Releases
548
556
 
@@ -6,9 +6,27 @@ All notable changes to this project will be documented in this file.
6
6
 
7
7
  No unreleased changes.
8
8
 
9
+ ## v0.11.0 - 2026-04-11T10:48:07+01:00
10
+
11
+ - chore(release): 0.11.0 (1f4ff40)
12
+ - Merge pull request #38 from hayesmaker/feature/live-settings-parity-backend (8fdb739)
13
+ - feat(input): support host-defined joystick port overrides (86701b2)
14
+ - fix(prg): make headless autorun typing deterministic (d55ca16)
15
+ - feat(headless): support typed load-file command and reset-only hard reset (1b575b2)
16
+ - Merge pull request #37 from hayesmaker/feature/add-prg-support (b883c3e)
17
+ - feat: added keyboard test prg and snapshots (7325ffa)
18
+ - revert(snapshot): disable VICE .vsf support in browser runtime (5911735)
19
+ - feat(runtime): add ?game override and refine VICE snapshot parsing (69a38b6)
20
+ - feat(snapshot): add VICE best-effort loader and runtime load diagnostics (9330bfa)
21
+ - feat: lvllvl snapshot support (eb2fe61)
22
+ - fix(d64): enable 1541 drive before disk insert (9835894)
23
+ - fix(prg): auto-run after load and use inject mode (373615f)
24
+ - feat(ui): split settings into tabs and add format-aware loading (3df4373)
25
+ - Merge pull request #36 from hayesmaker/chore/deploy-and-release (3e5d444)
26
+
9
27
  ## v0.10.0 - 2026-04-09T09:24:54+01:00
10
28
 
11
- - chore(release): 0.10.0 (470bc73)
29
+ - chore(release): 0.10.0 (6716e49)
12
30
 
13
31
  ## v0.9.0 - 2026-04-09T09:24:36+01:00
14
32
 
@@ -1,4 +1,4 @@
1
- (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=class e{exports=null;heap=null;wasmMemory=null;static async load(t=`/src/emulator/c64.wasm`){let n=await fetch(t);if(!n.ok)throw Error(`Failed to fetch ${t}: ${n.status}`);let r=await n.arrayBuffer(),i=new e;return await i.instantiate(r),i}static DYNAMICTOP_PTR=5583504;static DYNAMIC_BASE=10826544;static INITIAL_PAGES=256;async instantiate(t,n){let r=new WebAssembly.Memory({initial:e.INITIAL_PAGES});this.wasmMemory=r;let i={env:{...this.makeEnvImports(r),...n??{}},wasi_snapshot_preview1:this.makeWasiImports(r)};try{this.exports=(await WebAssembly.instantiate(t,i)).instance.exports,this.updateHeapViews(),new DataView(r.buffer).setUint32(e.DYNAMICTOP_PTR,e.DYNAMIC_BASE,!0),this.exports.__wasm_call_ctors()}catch(e){throw Error(`WASM instantiation failed: ${e}`,{cause:e})}}allocAndWrite(e){if(!this.exports||!this.heap)throw Error(`WASM not ready`);let t=this.exports.malloc(e.length);return this.updateHeapViews(),this.heap.heapU8.set(e,t),t}free(e){this.exports?.free(e)}updateHeapViews(){if(!this.wasmMemory)throw Error(`WASM memory not initialized`);let e=this.wasmMemory.buffer;this.heap={heapU8:new Uint8Array(e),heapF32:new Float32Array(e),heapU32:new Uint32Array(e)}}makeEnvImports(t){return{memory:t,emscripten_get_sbrk_ptr:()=>e.DYNAMICTOP_PTR,emscripten_resize_heap:e=>{let n=65536,r=2147483648-n;if(e>r)return 0;let i=t.buffer.byteLength;for(let a=1;a<=4;a*=2){let o=i*(1+.2/a);o=Math.min(o,e+100663296);let s=Math.min(r,Math.ceil(Math.max(16777216,e,o)/n)*n);try{return t.grow(s-t.buffer.byteLength+65535>>>16),this.updateHeapViews(),1}catch{}}return 0},emscripten_memcpy_big:(e,n,r)=>(new Uint8Array(t.buffer).copyWithin(e,n,n+r),e),setTempRet0:e=>{},emscripten_asm_const_iii:(e,t,n)=>0,table:new WebAssembly.Table({initial:512,maximum:512,element:`anyfunc`})}}makeWasiImports(e){return{fd_write:(t,n,r,i)=>{let a=new DataView(e.buffer),o=new Uint8Array(e.buffer),s=0;for(let e=0;e<r;e++){let r=a.getUint32(n+e*8,!0),i=a.getUint32(n+e*8+4,!0);if(t===2){let e=new TextDecoder().decode(o.subarray(r,r+i));console.error(e)}s+=i}return a.setUint32(i,s,!0),0}}}},t=384,n=272,r=44100,i=class i{wasm;config;running=!1;frameCount=0;onFrame;onAudio;constructor(e,i={}){this.wasm=e,this.config={videoWidth:t,videoHeight:n,sampleRate:r,audioChannels:1,cyclesPerFrame:50,...i}}static async load(t=`/src/emulator/c64.wasm`,n={}){let r=new i(await e.load(t),n);return r.init(),r}init(){let e=this.wasm.exports;if(!e)throw Error(`WASM exports not available`);if(e.c64_init(),this.config.sampleRate){let e=this.wasm.exports.sid_setSampleRate;typeof e==`function`&&e(this.config.sampleRate)}}start(){this.running=!0}pause(){this.running=!1}isRunning(){return this.running}getFrameCount(){return this.frameCount}reset(){this.wasm.exports?.c64_reset(),this.frameCount=0}static AUDIO_BUFFER_SIZE=4096;tick(e=0){if(!this.running)return;let r=this.wasm.exports,i=r.debugger_update(e);if(this.frameCount++,i&&this.onFrame){let e=r.c64_getPixelBuffer(),i=this.wasm.heap.heapU8.subarray(e,e+t*n*4);this.onFrame({width:t,height:n,data:i,timestamp:this.frameCount})}}loadGame(e){let t=this.wasm.exports;if(!t||!this.wasm.heap)throw Error(`WASM not ready`);let n=this.wasm.allocAndWrite(e.data);try{switch(e.type){case`prg`:t.c64_loadPRG(n,e.data.length,1);break;case`d64`:t.c64_setDriveEnabled(1),t.c64_insertDisk(n,e.data.length);break;case`crt`:t.c64_loadCartridge(n,e.data.length);break;case`snapshot`:this.loadSnapshotData(n,e.data.length);break}}finally{this.wasm.free(n)}}removeCartridge(){this.wasm.exports?.c64_removeCartridge(),this.wasm.exports?.c64_reset(),this.frameCount=0}handleInput(e){let t=this.wasm.exports;if(t){if(e.type===`key`&&e.key!==void 0)t.keyboard_keyPressed(Number(e.key));else if(e.type===`joystick`){let n=(e.joystickPort??1)-1;e.direction&&t.c64_joystick_push(n,{up:1,down:2,left:4,right:8}[e.direction]??0),e.fire1&&t.c64_joystick_push(n,16)}}}keyDown(e){this.wasm.exports?.keyboard_keyPressed(e)}keyUp(e){this.wasm.exports?.keyboard_keyReleased(e)}joystickPush(e,t){this.wasm.exports?.c64_joystick_push(e-1,t)}joystickRelease(e,t){this.wasm.exports?.c64_joystick_release(e-1,t)}mousePosition(e,t){this.wasm.exports?.c64_mouse_position(e,t)}ramRead(e){return this.wasm.exports?.c64_ramRead(e)??0}ramWrite(e,t){this.wasm.exports?.c64_ramWrite(e,t)}cpuRead(e){return this.wasm.exports?.c64_cpuRead(e)??0}cpuWrite(e,t){this.wasm.exports?.c64_cpuWrite(e,t)}getPC(){return this.wasm.exports?.c64_getPC()??0}getRegA(){return this.wasm.exports?.c64_getRegA()??0}getRegX(){return this.wasm.exports?.c64_getRegX()??0}getRegY(){return this.wasm.exports?.c64_getRegY()??0}getSP(){return this.wasm.exports?.c64_getSP()??0}getCycleCount(){return this.wasm.exports?.c64_getCycleCount()??0}getFrameBuffer(){if(!this.wasm.exports||!this.wasm.heap)throw Error(`WASM not ready`);let e=this.wasm.exports.c64_getPixelBuffer();return{width:t,height:n,data:this.wasm.heap.heapU8.slice(e,e+t*n*4),timestamp:this.frameCount}}getSnapshot(){let e=this.wasm.exports;if(!e||!this.wasm.heap)throw Error(`WASM not ready`);let t=e.c64_getSnapshotSize(),n=e.malloc(t);e.c64_getSnapshot(n);let r=this.wasm.heap.heapU8.slice(n,n+t);return e.free(n),r}loadSnapshotData(e,t){let n=this.wasm.exports;if(!n)throw Error(`WASM not ready`);n.c64_loadSnapshot(e,t),this.frameCount=0}debuggerPause(){this.wasm.exports?.debugger_pause()}debuggerPlay(){this.wasm.exports?.debugger_play()}debuggerStep(){this.wasm.exports?.debugger_step()}debuggerIsRunning(){return(this.wasm.exports?.debugger_isRunning()??0)!==0}setDebugSpeed(e){this.wasm.exports?.debugger_set_speed(e)}setSampleRate(e){this.wasm.exports?.sid_setSampleRate(e)}getSidBuffer(){let e=this.wasm.exports;if(!e||!this.wasm.heap)return null;let t=e.sid_getAudioBuffer();return new Float32Array(this.wasm.heap.heapF32.subarray(t>>2,(t>>2)+i.AUDIO_BUFFER_SIZE))}setSIDModel(e){this.wasm.exports?.sid_setModel(e)}setVoiceEnabled(e,t){this.wasm.exports?.sid_setVoiceEnabled(t?e:0)}setDriveEnabled(e){this.wasm.exports?.c64_setDriveEnabled(e?1:0)}getDriveEnabled(){return(this.wasm.exports?.c64_getDriveEnabled()??0)!==0}};const a={UP:1,DOWN:2,LEFT:4,RIGHT:8},o={ArrowUp:a.UP,ArrowDown:a.DOWN,ArrowLeft:a.LEFT,ArrowRight:a.RIGHT,ControlLeft:16},s=Object.keys(o),c={ArrowUp:a.UP,ArrowDown:a.DOWN,ArrowLeft:a.LEFT,ArrowRight:a.RIGHT,KeyZ:16,ControlLeft:16},l={ARROW_LEFT:0,ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5,SIX:6,SEVEN:7,EIGHT:8,NINE:9,ZERO:10,PLUS:11,MINUS:12,POUND:13,CLEAR_HOME:14,INS_DEL:15,CTRL:16,Q:17,W:18,E:19,R:20,T:21,Y:22,U:23,I:24,O:25,P:26,AT:27,STAR:28,ARROW_UP:29,RUN_STOP:30,A:31,S:32,D:33,F:34,G:35,H:36,J:37,K:38,L:39,COLON:40,SEMICOLON:41,EQUALS:42,RETURN:43,COMMODORE:44,SHIFT_LEFT:45,Z:46,X:47,C:48,V:49,B:50,N:51,M:52,COMMA:53,PERIOD:54,SLASH:55,SHIFT_RIGHT:56,CURSOR_UP_DOWN:57,CURSOR_LEFT_RIGHT:58,SPACE:59,F1:60,F3:61,F5:62,F7:63,RESTORE:64};function u(e,t,n){let r=e.toLowerCase(),i=n===`keydown`,a=[],o=e=>a.push({key:e,action:`press`}),s=e=>a.push({key:e,action:`release`}),c=e=>a.push({key:e,action:i?`press`:`release`});switch(i&&(t?o(l.SHIFT_LEFT):r!==`arrowup`&&r!==`arrowleft`&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT))),r){case`a`:c(l.A);break;case`b`:c(l.B);break;case`c`:c(l.C);break;case`d`:c(l.D);break;case`e`:c(l.E);break;case`f`:c(l.F);break;case`g`:c(l.G);break;case`h`:c(l.H);break;case`i`:c(l.I);break;case`j`:c(l.J);break;case`k`:c(l.K);break;case`l`:c(l.L);break;case`m`:c(l.M);break;case`n`:c(l.N);break;case`o`:c(l.O);break;case`p`:c(l.P);break;case`q`:c(l.Q);break;case`r`:c(l.R);break;case`s`:c(l.S);break;case`t`:c(l.T);break;case`u`:c(l.U);break;case`v`:c(l.V);break;case`w`:c(l.W);break;case`x`:c(l.X);break;case`y`:c(l.Y);break;case`z`:c(l.Z);break;case`0`:c(l.ZERO);break;case`1`:c(l.ONE);break;case`2`:c(l.TWO);break;case`3`:c(l.THREE);break;case`4`:c(l.FOUR);break;case`5`:c(l.FIVE);break;case`6`:c(l.SIX);break;case`7`:c(l.SEVEN);break;case`8`:c(l.EIGHT);break;case`9`:c(l.NINE);break;case`!`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.ONE);break;case`"`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.TWO);break;case`#`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.THREE);break;case`$`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.FOUR);break;case`%`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.FIVE);break;case`&`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.SIX);break;case`'`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.SEVEN);break;case`(`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.EIGHT);break;case`)`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.NINE);break;case` `:c(l.SPACE);break;case`enter`:c(l.RETURN);break;case`backspace`:case`delete`:c(l.INS_DEL);break;case`escape`:c(l.RUN_STOP);break;case`-`:c(l.MINUS);break;case`=`:c(l.EQUALS);break;case`+`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.PLUS);break;case`*`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.STAR);break;case`@`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.AT);break;case`^`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.ARROW_UP);break;case"`":c(l.ARROW_LEFT);break;case`~`:c(l.ARROW_UP);break;case`\\`:c(l.POUND);break;case`,`:case`<`:c(l.COMMA);break;case`.`:case`>`:c(l.PERIOD);break;case`/`:case`?`:c(l.SLASH);break;case`;`:c(l.SEMICOLON);break;case`:`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.COLON);break;case`[`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.COLON);break;case`]`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.SEMICOLON);break;case`shift`:c(l.SHIFT_LEFT);break;case`tab`:c(l.CTRL);break;case`control`:c(l.COMMODORE);break;case`capslock`:c(l.COMMODORE);break;case`home`:c(l.CLEAR_HOME);break;case`f1`:c(l.F1);break;case`f2`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.F1);break;case`f3`:c(l.F3);break;case`f4`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.F3);break;case`f5`:c(l.F5);break;case`f6`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.F5);break;case`f7`:c(l.F7);break;case`f8`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.F7);break;case`arrowdown`:c(l.CURSOR_UP_DOWN);break;case`arrowup`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.CURSOR_UP_DOWN);break;case`arrowright`:c(l.CURSOR_LEFT_RIGHT);break;case`arrowleft`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.CURSOR_LEFT_RIGHT);break;default:break}return a}var d=class{emulator;target;keyboardJoystickPort;inputMode=`joystick`;pressedControls=new Set;keyDownHandler=e=>{this.handleKeyDown(e)};keyUpHandler=e=>{this.handleKeyUp(e)};constructor(e,t=window,n=2){this.emulator=e,this.target=t,this.keyboardJoystickPort=n}attach(){this.target.addEventListener(`keydown`,this.keyDownHandler),this.target.addEventListener(`keyup`,this.keyUpHandler)}detach(){this.target.removeEventListener(`keydown`,this.keyDownHandler),this.target.removeEventListener(`keyup`,this.keyUpHandler),this.releaseAll()}handleKeyDown(e){if(this.inputMode===`keyboard`){let t=u(e.key,e.shiftKey,`keydown`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}return}if(this.inputMode===`mixed`){if(e.code in c){let t=c[e.code];this.emulator.joystickPush(this.keyboardJoystickPort,t),e.preventDefault()}else{let t=u(e.key,e.shiftKey,`keydown`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}}return}let t=this.getMappedControl(e);!t||this.pressedControls.has(t)||(this.pressedControls.add(t),this.emulator.joystickPush(this.keyboardJoystickPort,o[t]),e.preventDefault())}handleKeyUp(e){if(this.inputMode===`keyboard`){let t=u(e.key,e.shiftKey,`keyup`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}return}if(this.inputMode===`mixed`){if(e.code in c){let t=c[e.code];this.emulator.joystickRelease(this.keyboardJoystickPort,t),e.preventDefault()}else{let t=u(e.key,e.shiftKey,`keyup`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}}return}let t=this.getMappedControl(e);t&&(this.pressedControls.delete(t),this.emulator.joystickRelease(this.keyboardJoystickPort,o[t]),e.preventDefault())}getMappedControl(e){return e.code in o?e.code:null}releaseAll(){for(let e of this.pressedControls)this.emulator.joystickRelease(this.keyboardJoystickPort,o[e]);this.pressedControls.clear()}setKeyboardPort(e){this.keyboardJoystickPort!==e&&(this.releaseAll(),this.keyboardJoystickPort=e)}setInputMode(e){this.inputMode!==e&&(this.releaseAll(),this.inputMode=e)}getInputMode(){return this.inputMode}};const f={0:`Normal cartridge`,1:`Action Replay`,2:`KCS Power Cartridge`,3:`Final Cartridge III`,4:`Simons BASIC`,5:`Ocean type 1`,6:`Expert Cartridge`,7:`Fun Play, Power Play`,8:`Super Games`,9:`Atomic Power`,10:`Epyx Fastload`,11:`Westermann Learning`,12:`Rex Utility`,13:`Final Cartridge I`,14:`Magic Formel`,15:`C64 Game System (SYSTEM 3)`,16:`Warp Speed`,17:`Dinamic`,18:`Zaxxon / Super Zaxxon (SEGA)`,19:`Magic Desk / Domark / HES Australia`,20:`Super Snapshot V5`,21:`Comal-80`,22:`Structured BASIC`,23:`Ross`,24:`Dela EP64`,25:`Dela EP7x8`,26:`Dela EP256`,27:`Rex EP256`,28:`Mikro Assembler`,29:`Final Cartridge Plus`,30:`Action Replay 4`,31:`Stardos`,32:`EasyFlash`,33:`EasyFlash Xbank`,34:`Capture`,35:`Action Replay 3`,36:`Retro Replay`,37:`MMC64`,38:`MMC Replay`,39:`IDE64`,40:`Super Snapshot V4`,41:`IEEE-488`,42:`Game Killer`,43:`Prophet64`,44:`EXOS`,45:`Freeze Frame`,46:`Freeze Machine`,47:`Snapshot64`,48:`Super Explode V5.0`,49:`Magic Voice`,50:`Action Replay 2`,51:`MACH 5`,52:`Diashow-Maker`,53:`Pagefox`,54:`Kingsoft`,55:`Silverrock 128K Longshot`,56:`Formel 64`,57:`RGCD`,58:`RR-Net MK3`,59:`Easy Calc`,60:`GMod2`,61:`MAX Basic`,62:`GMod3`,63:`ZIPP-CODE 48`,64:`Blackbox V8`,65:`Blackbox V3`,66:`Blackbox V4`,67:`REX RAM-Floppy`,68:`BIS-Plus`,69:`SD-BOX`,70:`MultiMAX`,71:`Blackbox V9`,72:`Lt. Kernal Host Adaptor`,73:`RAMLink`,74:`H.E.R.O.`,75:`IEEE Flash! 64`,76:`Turtle Graphics II`,77:`Freeze Frame MK2`,78:`Partner 64`};function p(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function m(e,t){return(e[t]<<8|e[t+1])>>>0}function h(e,t){if(!e||e.length<64||!String.fromCharCode(...Array.from(e.slice(0,16))).startsWith(`C64 CARTRIDGE`))return null;let n=p(e,16),r=m(e,22),i=e[24],a=e[25],o=``;for(let t=32;t<64&&e[t]!==0;t++)o+=String.fromCharCode(e[t]);o=o.trim();let s;s=i===0&&a===0?`16K (ROML+ROMH)`:i===0&&a===1?`8K (ROML only)`:i===1&&a===0?`Ultimax`:`inactive (pass-through)`;let c=0,l=0,u=Math.max(n,64);for(;u+16<=e.length&&String.fromCharCode(...Array.from(e.slice(u,u+4)))===`CHIP`;){let t=p(e,u+4);if(t<16)break;let n=m(e,u+14);c++,l+=n,u+=t}let d=f[r]??`Unknown(${r})`,h=t?` "${t}"`:``,g=o?` name="${o}"`:``,_=(l/1024).toFixed(0);return{line:`[C64 cart]${h} loading: hwType=${r}(${d}) | ${s} flags, ${_}K actual | ${c} CHIP(s) | ${e.length} bytes${g}`,hwType:r,hwName:d,exrom:i,game:a,bankConfig:s,cartName:o,chipCount:c,totalRomBytes:l}}var g=44100,_=class{ctx=null;workletNode=null;gainNode=null;_muted=!1;_volume=.75;_suspended=!0;_initialised=!1;_ready=!1;_readSidBuffer=null;onStateChange;get muted(){return this._muted}get volume(){return this._volume}get suspended(){return this._suspended}get ready(){return this._ready}get sampleRate(){return this.ctx?.sampleRate??g}async init(){if(this._initialised)return!this._suspended;this._initialised=!0;try{return this.ctx=new AudioContext({sampleRate:g}),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=this._volume,this.gainNode.connect(this.ctx.destination),this.ctx.addEventListener(`statechange`,()=>{let e=this._suspended;this._suspended=this.ctx?.state===`suspended`,e!==this._suspended&&this.fireStateChange()}),this._suspended=this.ctx.state===`suspended`,await this.loadWorklet(),this._suspended&&=(this.ctx.resume().catch(()=>{}),this.ctx.state===`suspended`),this.fireStateChange(),!this._suspended}catch{return!1}}async loadWorklet(){if(!this.ctx||!this.gainNode)return;let e=`/c64-ready/audio-worklet-processor.js`.replace(/\/+/g,`/`);await this.ctx.audioWorklet.addModule(e),this.workletNode=new AudioWorkletNode(this.ctx,`c64-audio-processor`,{outputChannelCount:[1]}),this.workletNode.connect(this.gainNode),this.workletNode.port.onmessage=()=>{this.feedWorklet()},this._ready=!0}setSidBufferReader(e){this._readSidBuffer=e}feedWorklet(){if(!this.workletNode||!this._readSidBuffer||this._suspended)return;let e=this._readSidBuffer();e&&e.length>0&&this.workletNode.port.postMessage(e)}async resume(){if(this.ctx)try{await this.ctx.resume(),this._suspended=this.ctx.state===`suspended`,this.fireStateChange()}catch(e){console.error(`AudioEngine: resume failed`,e)}}setMuted(e){this._muted=e,this.gainNode&&(this.gainNode.gain.value=e?0:this._volume),this.fireStateChange()}toggleMute(){this.setMuted(!this._muted)}setVolume(e){this._volume=Math.max(0,Math.min(1,e)),this.gainNode&&!this._muted&&(this.gainNode.gain.value=this._volume),this.fireStateChange()}adjustVolume(e){this.setVolume(this._volume+e)}async destroy(){this.workletNode?.disconnect(),this.gainNode?.disconnect(),await this.ctx?.close(),this.workletNode=null,this.gainNode=null,this.ctx=null,this._initialised=!1,this._ready=!1,this._suspended=!0,this._readSidBuffer=null}fireStateChange(){this.onStateChange?.({muted:this._muted,volume:this._volume,suspended:this._suspended})}},v=class{emulatorInput;captureKeyDown=e=>this.onCaptureKeyDown(e);captureKeyUp=e=>this.onCaptureKeyUp(e);constructor(e,t=window){this.emulatorInput=new d(e,t)}attach(){window.addEventListener(`keydown`,this.captureKeyDown,!0),window.addEventListener(`keyup`,this.captureKeyUp,!0),this.emulatorInput.attach()}detach(){window.removeEventListener(`keydown`,this.captureKeyDown,!0),window.removeEventListener(`keyup`,this.captureKeyUp,!0),this.emulatorInput.detach()}setKeyboardJoystickPort(e){this.emulatorInput.setKeyboardPort(e)}setInputMode(e){this.emulatorInput.setInputMode(e)}getInputMode(){return this.emulatorInput.getInputMode()}onCaptureKeyDown(e){if(new Set([...s,...Object.keys(c)]).has(e.code)){try{if(typeof document<`u`){if(`hidden`in document){if(document.hidden){e.stopImmediatePropagation();return}}else if(typeof document.hasFocus==`function`&&!document.hasFocus()){e.stopImmediatePropagation();return}}}catch{}try{if(typeof document<`u`&&(document.querySelector(`.c64-help-overlay.visible`)||document.querySelector(`.c64-menu-overlay.visible`))){e.stopImmediatePropagation(),e.preventDefault();return}}catch{}}}onCaptureKeyUp(e){if(new Set([...s,...Object.keys(c)]).has(e.code))try{if(typeof document<`u`){if(`hidden`in document){if(document.hidden){e.stopImmediatePropagation();return}}else if(typeof document.hasFocus==`function`&&!document.hasFocus()){e.stopImmediatePropagation();return}if(document.querySelector(`.c64-help-overlay.visible`)||document.querySelector(`.c64-menu-overlay.visible`)){e.stopImmediatePropagation(),e.preventDefault();return}}}catch{}}};const y=[{type:`crt`,label:`Cartridge (.crt)`,extensions:[`.crt`]},{type:`prg`,label:`Program (.prg)`,extensions:[`.prg`]},{type:`d64`,label:`Disk image (.d64)`,extensions:[`.d64`]},{type:`snapshot`,label:`Snapshot (.snapshot, .c64, .s64)`,extensions:[`.snapshot`,`.c64`,`.s64`]}];var b=new Set(y.map(e=>e.type));function x(e){return typeof e==`string`&&b.has(e)}function S(e){let t=e.toLowerCase();for(let e of y)if(e.extensions.some(e=>t.endsWith(e)))return e.type;return null}function C(e,t,n=`crt`){return e===`auto`?S(t)??n:e}function w(e){return(e===`auto`?y.flatMap(e=>e.extensions):y.find(t=>t.type===e)?.extensions??[]).join(`,`)}function T(e){return y.find(t=>t.type===e)?.label??e.toUpperCase()}var E=class{emulator=null;inputHandler=null;audio=new _;options;constructor(e){this.options={gameType:`crt`,...e}}async start(){let{wasmUrl:e,gameUrl:t,gameType:n,renderer:r,onProgress:a}=this.options;a?.(10,`INITIALISING WASM...`),this.emulator=await i.load(e),this.inputHandler=new v(this.emulator),this.inputHandler.attach(),r.attachTo(this.emulator),t&&t!==`null`&&await this.loadGame(t,n,a),this.emulator.start(),this.initAudio()}initAudio(){if(!this.emulator)return;let e=this.emulator;this.audio.onStateChange=e=>{window.dispatchEvent(new CustomEvent(`c64-audio-state`,{detail:e}))},this.audio.init().then(t=>{e.setSampleRate(this.audio.sampleRate),this.audio.setSidBufferReader(()=>e.getSidBuffer()),t||window.dispatchEvent(new CustomEvent(`c64-audio-suspended`))})}async loadGame(e,t=`crt`,n){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);n?.(20,`LOADING GAME...`);let r=await fetch(e);if(!r.ok)throw Error(`Failed to fetch game: ${r.status}`);let i=Number(r.headers.get(`content-length`)??0),a;if(i>0&&r.body){let e=r.body.getReader(),t=[],o=0,s=await e.read();for(;!s.done;){t.push(s.value),o+=s.value.byteLength;let r=20+Math.round(o/i*65);n?.(r,`LOADING GAME... ${Math.round(o/i*100)}%`),s=await e.read()}a=new Uint8Array(o);let c=0;for(let e of t)a.set(e,c),c+=e.byteLength}else a=new Uint8Array(await r.arrayBuffer());if(n?.(90,`INSERTING ${O(t)}...`),t===`crt`&&!D(a)){n?.(0,`INVALID CRT`);let e=Error(`Invalid CRT file format`);throw console.error(e),e}if(t===`crt`){let t=e.split(`/`).pop()??e,n=h(a,t);n&&console.log(n.line)}this.assertSnapshotFormatSupported(a,t,e),this.emitSnapshotLoadInfo(t,e);try{this.emulator.loadGame({type:t,data:a}),t===`prg`&&await this.autoRunPrgIfRunning(),n?.(100,`READY!`),window.dispatchEvent(new CustomEvent(`c64-load-success`,{detail:{url:e,type:t}}))}catch(r){throw n?.(0,`FAILED`),console.error(`Failed to insert cartridge or load game:`,r),window.dispatchEvent(new CustomEvent(`c64-load-error`,{detail:{error:String(r),url:e,type:t}})),r}}async loadFile(e,t){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);let n=this.options.onProgress,r=t??S(e.name)??`crt`;try{n?.(20,`READING FILE ${e.name}...`);let t=await e.arrayBuffer(),i=new Uint8Array(t);if(n?.(90,`INSERTING ${O(r)}...`),r===`crt`&&!D(i)){n?.(0,`INVALID CRT`);let e=Error(`Invalid CRT file format`);throw console.error(e),e}if(r===`crt`){let t=h(i,e.name);t&&console.log(t.line)}this.assertSnapshotFormatSupported(i,r,e.name),this.emitSnapshotLoadInfo(r,e.name);try{this.emulator.loadGame({type:r,data:i}),r===`prg`&&await this.autoRunPrgIfRunning(),n?.(100,`READY!`),window.dispatchEvent(new CustomEvent(`c64-close-dialog`,{detail:{file:e.name,type:r}}))}catch(t){throw n?.(0,`FAILED`),console.error(`Failed to insert cartridge from file:`,t),window.dispatchEvent(new CustomEvent(`c64-load-error`,{detail:{error:String(t),file:e.name,type:r}})),t}}catch(e){throw n?.(0,`FAILED`),e}}detachCartridge(){if(this.emulator)try{this.emulator.removeCartridge(),window.dispatchEvent(new CustomEvent(`c64-detach`,{detail:{}})),window.dispatchEvent(new CustomEvent(`c64-close-menu`))}catch(e){console.error(`Failed to detach cartridge:`,e)}}hardReset(){if(this.emulator)try{this.emulator.reset(),this.emulator.start(),window.dispatchEvent(new CustomEvent(`c64-hard-reset`,{detail:{}})),window.dispatchEvent(new CustomEvent(`c64-close-menu`))}catch(e){console.error(`Failed to perform hard reset:`,e)}}setKeyboardJoystickPort(e){this.inputHandler?.setKeyboardJoystickPort(e)}setInputMode(e){this.inputHandler?.setInputMode(e)}async autoRunPrgIfRunning(){!this.emulator||!this.emulator.isRunning()||(await k(120),await this.typeCommand(`run
1
+ (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=class e{exports=null;heap=null;wasmMemory=null;static async load(t=`/src/emulator/c64.wasm`){let n=await fetch(t);if(!n.ok)throw Error(`Failed to fetch ${t}: ${n.status}`);let r=await n.arrayBuffer(),i=new e;return await i.instantiate(r),i}static DYNAMICTOP_PTR=5583504;static DYNAMIC_BASE=10826544;static INITIAL_PAGES=256;async instantiate(t,n){let r=new WebAssembly.Memory({initial:e.INITIAL_PAGES});this.wasmMemory=r;let i={env:{...this.makeEnvImports(r),...n??{}},wasi_snapshot_preview1:this.makeWasiImports(r)};try{this.exports=(await WebAssembly.instantiate(t,i)).instance.exports,this.updateHeapViews(),new DataView(r.buffer).setUint32(e.DYNAMICTOP_PTR,e.DYNAMIC_BASE,!0),this.exports.__wasm_call_ctors()}catch(e){throw Error(`WASM instantiation failed: ${e}`,{cause:e})}}allocAndWrite(e){if(!this.exports||!this.heap)throw Error(`WASM not ready`);let t=this.exports.malloc(e.length);return this.updateHeapViews(),this.heap.heapU8.set(e,t),t}free(e){this.exports?.free(e)}updateHeapViews(){if(!this.wasmMemory)throw Error(`WASM memory not initialized`);let e=this.wasmMemory.buffer;this.heap={heapU8:new Uint8Array(e),heapF32:new Float32Array(e),heapU32:new Uint32Array(e)}}makeEnvImports(t){return{memory:t,emscripten_get_sbrk_ptr:()=>e.DYNAMICTOP_PTR,emscripten_resize_heap:e=>{let n=65536,r=2147483648-n;if(e>r)return 0;let i=t.buffer.byteLength;for(let a=1;a<=4;a*=2){let o=i*(1+.2/a);o=Math.min(o,e+100663296);let s=Math.min(r,Math.ceil(Math.max(16777216,e,o)/n)*n);try{return t.grow(s-t.buffer.byteLength+65535>>>16),this.updateHeapViews(),1}catch{}}return 0},emscripten_memcpy_big:(e,n,r)=>(new Uint8Array(t.buffer).copyWithin(e,n,n+r),e),setTempRet0:e=>{},emscripten_asm_const_iii:(e,t,n)=>0,table:new WebAssembly.Table({initial:512,maximum:512,element:`anyfunc`})}}makeWasiImports(e){return{fd_write:(t,n,r,i)=>{let a=new DataView(e.buffer),o=new Uint8Array(e.buffer),s=0;for(let e=0;e<r;e++){let r=a.getUint32(n+e*8,!0),i=a.getUint32(n+e*8+4,!0);if(t===2){let e=new TextDecoder().decode(o.subarray(r,r+i));console.error(e)}s+=i}return a.setUint32(i,s,!0),0}}}},t=384,n=272,r=44100,i=class i{wasm;config;running=!1;frameCount=0;onFrame;onAudio;constructor(e,i={}){this.wasm=e,this.config={videoWidth:t,videoHeight:n,sampleRate:r,audioChannels:1,cyclesPerFrame:50,...i}}static async load(t=`/src/emulator/c64.wasm`,n={}){let r=new i(await e.load(t),n);return r.init(),r}init(){let e=this.wasm.exports;if(!e)throw Error(`WASM exports not available`);if(e.c64_init(),this.config.sampleRate){let e=this.wasm.exports.sid_setSampleRate;typeof e==`function`&&e(this.config.sampleRate)}}start(){this.running=!0}pause(){this.running=!1}isRunning(){return this.running}getFrameCount(){return this.frameCount}reset(){this.wasm.exports?.c64_reset(),this.frameCount=0}static AUDIO_BUFFER_SIZE=4096;tick(e=0){if(!this.running)return;let r=this.wasm.exports,i=r.debugger_update(e);if(this.frameCount++,i&&this.onFrame){let e=r.c64_getPixelBuffer(),i=this.wasm.heap.heapU8.subarray(e,e+t*n*4);this.onFrame({width:t,height:n,data:i,timestamp:this.frameCount})}}loadGame(e){let t=this.wasm.exports;if(!t||!this.wasm.heap)throw Error(`WASM not ready`);let n=this.wasm.allocAndWrite(e.data);try{switch(e.type){case`prg`:t.c64_loadPRG(n,e.data.length,1);break;case`d64`:t.c64_setDriveEnabled(1),t.c64_insertDisk(n,e.data.length);break;case`crt`:t.c64_loadCartridge(n,e.data.length);break;case`snapshot`:this.loadSnapshotData(n,e.data.length);break}}finally{this.wasm.free(n)}}removeCartridge(){this.wasm.exports?.c64_removeCartridge(),this.wasm.exports?.c64_reset(),this.frameCount=0}handleInput(e){let t=this.wasm.exports;if(t){if(e.type===`key`&&e.key!==void 0)t.keyboard_keyPressed(Number(e.key));else if(e.type===`joystick`){let n=(e.joystickPort??1)-1;e.direction&&t.c64_joystick_push(n,{up:1,down:2,left:4,right:8}[e.direction]??0),e.fire1&&t.c64_joystick_push(n,16)}}}keyDown(e){this.wasm.exports?.keyboard_keyPressed(e)}keyUp(e){this.wasm.exports?.keyboard_keyReleased(e)}joystickPush(e,t){this.wasm.exports?.c64_joystick_push(e-1,t)}joystickRelease(e,t){this.wasm.exports?.c64_joystick_release(e-1,t)}mousePosition(e,t){this.wasm.exports?.c64_mouse_position(e,t)}ramRead(e){return this.wasm.exports?.c64_ramRead(e)??0}ramWrite(e,t){this.wasm.exports?.c64_ramWrite(e,t)}cpuRead(e){return this.wasm.exports?.c64_cpuRead(e)??0}cpuWrite(e,t){this.wasm.exports?.c64_cpuWrite(e,t)}getPC(){return this.wasm.exports?.c64_getPC()??0}getRegA(){return this.wasm.exports?.c64_getRegA()??0}getRegX(){return this.wasm.exports?.c64_getRegX()??0}getRegY(){return this.wasm.exports?.c64_getRegY()??0}getSP(){return this.wasm.exports?.c64_getSP()??0}getCycleCount(){return this.wasm.exports?.c64_getCycleCount()??0}getFrameBuffer(){if(!this.wasm.exports||!this.wasm.heap)throw Error(`WASM not ready`);let e=this.wasm.exports.c64_getPixelBuffer();return{width:t,height:n,data:this.wasm.heap.heapU8.slice(e,e+t*n*4),timestamp:this.frameCount}}getSnapshot(){let e=this.wasm.exports;if(!e||!this.wasm.heap)throw Error(`WASM not ready`);let t=e.c64_getSnapshotSize(),n=e.malloc(t);e.c64_getSnapshot(n);let r=this.wasm.heap.heapU8.slice(n,n+t);return e.free(n),r}loadSnapshotData(e,t){let n=this.wasm.exports;if(!n)throw Error(`WASM not ready`);n.c64_loadSnapshot(e,t),this.frameCount=0}debuggerPause(){this.wasm.exports?.debugger_pause()}debuggerPlay(){this.wasm.exports?.debugger_play()}debuggerStep(){this.wasm.exports?.debugger_step()}debuggerIsRunning(){return(this.wasm.exports?.debugger_isRunning()??0)!==0}setDebugSpeed(e){this.wasm.exports?.debugger_set_speed(e)}setSampleRate(e){this.wasm.exports?.sid_setSampleRate(e)}getSidBuffer(){let e=this.wasm.exports;if(!e||!this.wasm.heap)return null;let t=e.sid_getAudioBuffer();return new Float32Array(this.wasm.heap.heapF32.subarray(t>>2,(t>>2)+i.AUDIO_BUFFER_SIZE))}setSIDModel(e){this.wasm.exports?.sid_setModel(e)}setVoiceEnabled(e,t){this.wasm.exports?.sid_setVoiceEnabled(t?e:0)}setDriveEnabled(e){this.wasm.exports?.c64_setDriveEnabled(e?1:0)}getDriveEnabled(){return(this.wasm.exports?.c64_getDriveEnabled()??0)!==0}};const a={UP:1,DOWN:2,LEFT:4,RIGHT:8},o={ArrowUp:a.UP,ArrowDown:a.DOWN,ArrowLeft:a.LEFT,ArrowRight:a.RIGHT,ControlLeft:16},s=Object.keys(o),c={ArrowUp:a.UP,ArrowDown:a.DOWN,ArrowLeft:a.LEFT,ArrowRight:a.RIGHT,KeyZ:16,ControlLeft:16},l={ARROW_LEFT:0,ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5,SIX:6,SEVEN:7,EIGHT:8,NINE:9,ZERO:10,PLUS:11,MINUS:12,POUND:13,CLEAR_HOME:14,INS_DEL:15,CTRL:16,Q:17,W:18,E:19,R:20,T:21,Y:22,U:23,I:24,O:25,P:26,AT:27,STAR:28,ARROW_UP:29,RUN_STOP:30,A:31,S:32,D:33,F:34,G:35,H:36,J:37,K:38,L:39,COLON:40,SEMICOLON:41,EQUALS:42,RETURN:43,COMMODORE:44,SHIFT_LEFT:45,Z:46,X:47,C:48,V:49,B:50,N:51,M:52,COMMA:53,PERIOD:54,SLASH:55,SHIFT_RIGHT:56,CURSOR_UP_DOWN:57,CURSOR_LEFT_RIGHT:58,SPACE:59,F1:60,F3:61,F5:62,F7:63,RESTORE:64};function u(e,t,n){let r=e.toLowerCase(),i=n===`keydown`,a=[],o=e=>a.push({key:e,action:`press`}),s=e=>a.push({key:e,action:`release`}),c=e=>a.push({key:e,action:i?`press`:`release`});switch(i&&(t?o(l.SHIFT_LEFT):r!==`arrowup`&&r!==`arrowleft`&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT))),r){case`a`:c(l.A);break;case`b`:c(l.B);break;case`c`:c(l.C);break;case`d`:c(l.D);break;case`e`:c(l.E);break;case`f`:c(l.F);break;case`g`:c(l.G);break;case`h`:c(l.H);break;case`i`:c(l.I);break;case`j`:c(l.J);break;case`k`:c(l.K);break;case`l`:c(l.L);break;case`m`:c(l.M);break;case`n`:c(l.N);break;case`o`:c(l.O);break;case`p`:c(l.P);break;case`q`:c(l.Q);break;case`r`:c(l.R);break;case`s`:c(l.S);break;case`t`:c(l.T);break;case`u`:c(l.U);break;case`v`:c(l.V);break;case`w`:c(l.W);break;case`x`:c(l.X);break;case`y`:c(l.Y);break;case`z`:c(l.Z);break;case`0`:c(l.ZERO);break;case`1`:c(l.ONE);break;case`2`:c(l.TWO);break;case`3`:c(l.THREE);break;case`4`:c(l.FOUR);break;case`5`:c(l.FIVE);break;case`6`:c(l.SIX);break;case`7`:c(l.SEVEN);break;case`8`:c(l.EIGHT);break;case`9`:c(l.NINE);break;case`!`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.ONE);break;case`"`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.TWO);break;case`#`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.THREE);break;case`$`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.FOUR);break;case`%`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.FIVE);break;case`&`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.SIX);break;case`'`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.SEVEN);break;case`(`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.EIGHT);break;case`)`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.NINE);break;case` `:c(l.SPACE);break;case`enter`:c(l.RETURN);break;case`backspace`:case`delete`:c(l.INS_DEL);break;case`escape`:c(l.RUN_STOP);break;case`-`:c(l.MINUS);break;case`=`:c(l.EQUALS);break;case`+`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.PLUS);break;case`*`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.STAR);break;case`@`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.AT);break;case`^`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.ARROW_UP);break;case"`":c(l.ARROW_LEFT);break;case`~`:c(l.ARROW_UP);break;case`\\`:c(l.POUND);break;case`,`:case`<`:c(l.COMMA);break;case`.`:case`>`:c(l.PERIOD);break;case`/`:case`?`:c(l.SLASH);break;case`;`:c(l.SEMICOLON);break;case`:`:i&&(s(l.SHIFT_LEFT),s(l.SHIFT_RIGHT)),c(l.COLON);break;case`[`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.COLON);break;case`]`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.SEMICOLON);break;case`shift`:c(l.SHIFT_LEFT);break;case`tab`:c(l.CTRL);break;case`control`:c(l.COMMODORE);break;case`capslock`:c(l.COMMODORE);break;case`home`:c(l.CLEAR_HOME);break;case`pageup`:c(l.RESTORE);break;case`f1`:c(l.F1);break;case`f2`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.F1);break;case`f3`:c(l.F3);break;case`f4`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.F3);break;case`f5`:c(l.F5);break;case`f6`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.F5);break;case`f7`:c(l.F7);break;case`f8`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.F7);break;case`arrowdown`:c(l.CURSOR_UP_DOWN);break;case`arrowup`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.CURSOR_UP_DOWN);break;case`arrowright`:c(l.CURSOR_LEFT_RIGHT);break;case`arrowleft`:i?o(l.SHIFT_LEFT):s(l.SHIFT_LEFT),c(l.CURSOR_LEFT_RIGHT);break;default:break}return a}var d=class{emulator;target;keyboardJoystickPort;inputMode=`mixed`;pressedControls=new Set;keyDownHandler=e=>{this.handleKeyDown(e)};keyUpHandler=e=>{this.handleKeyUp(e)};constructor(e,t=window,n=2){this.emulator=e,this.target=t,this.keyboardJoystickPort=n}attach(){this.target.addEventListener(`keydown`,this.keyDownHandler),this.target.addEventListener(`keyup`,this.keyUpHandler)}detach(){this.target.removeEventListener(`keydown`,this.keyDownHandler),this.target.removeEventListener(`keyup`,this.keyUpHandler),this.releaseAll()}handleKeyDown(e){if(this.inputMode===`keyboard`){let t=u(e.key,e.shiftKey,`keydown`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}return}if(this.inputMode===`mixed`){if(e.code in c){let t=c[e.code];this.emulator.joystickPush(this.keyboardJoystickPort,t),e.preventDefault()}else{let t=u(e.key,e.shiftKey,`keydown`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}}return}let t=this.getMappedControl(e);!t||this.pressedControls.has(t)||(this.pressedControls.add(t),this.emulator.joystickPush(this.keyboardJoystickPort,o[t]),e.preventDefault())}handleKeyUp(e){if(this.inputMode===`keyboard`){let t=u(e.key,e.shiftKey,`keyup`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}return}if(this.inputMode===`mixed`){if(e.code in c){let t=c[e.code];this.emulator.joystickRelease(this.keyboardJoystickPort,t),e.preventDefault()}else{let t=u(e.key,e.shiftKey,`keyup`);if(t.length>0){for(let e of t)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);e.preventDefault()}}return}let t=this.getMappedControl(e);t&&(this.pressedControls.delete(t),this.emulator.joystickRelease(this.keyboardJoystickPort,o[t]),e.preventDefault())}getMappedControl(e){return e.code in o?e.code:null}releaseAll(){for(let e of this.pressedControls)this.emulator.joystickRelease(this.keyboardJoystickPort,o[e]);this.pressedControls.clear()}setKeyboardPort(e){this.keyboardJoystickPort!==e&&(this.releaseAll(),this.keyboardJoystickPort=e)}setInputMode(e){this.inputMode!==e&&(this.releaseAll(),this.inputMode=e)}getInputMode(){return this.inputMode}};const f={0:`Normal cartridge`,1:`Action Replay`,2:`KCS Power Cartridge`,3:`Final Cartridge III`,4:`Simons BASIC`,5:`Ocean type 1`,6:`Expert Cartridge`,7:`Fun Play, Power Play`,8:`Super Games`,9:`Atomic Power`,10:`Epyx Fastload`,11:`Westermann Learning`,12:`Rex Utility`,13:`Final Cartridge I`,14:`Magic Formel`,15:`C64 Game System (SYSTEM 3)`,16:`Warp Speed`,17:`Dinamic`,18:`Zaxxon / Super Zaxxon (SEGA)`,19:`Magic Desk / Domark / HES Australia`,20:`Super Snapshot V5`,21:`Comal-80`,22:`Structured BASIC`,23:`Ross`,24:`Dela EP64`,25:`Dela EP7x8`,26:`Dela EP256`,27:`Rex EP256`,28:`Mikro Assembler`,29:`Final Cartridge Plus`,30:`Action Replay 4`,31:`Stardos`,32:`EasyFlash`,33:`EasyFlash Xbank`,34:`Capture`,35:`Action Replay 3`,36:`Retro Replay`,37:`MMC64`,38:`MMC Replay`,39:`IDE64`,40:`Super Snapshot V4`,41:`IEEE-488`,42:`Game Killer`,43:`Prophet64`,44:`EXOS`,45:`Freeze Frame`,46:`Freeze Machine`,47:`Snapshot64`,48:`Super Explode V5.0`,49:`Magic Voice`,50:`Action Replay 2`,51:`MACH 5`,52:`Diashow-Maker`,53:`Pagefox`,54:`Kingsoft`,55:`Silverrock 128K Longshot`,56:`Formel 64`,57:`RGCD`,58:`RR-Net MK3`,59:`Easy Calc`,60:`GMod2`,61:`MAX Basic`,62:`GMod3`,63:`ZIPP-CODE 48`,64:`Blackbox V8`,65:`Blackbox V3`,66:`Blackbox V4`,67:`REX RAM-Floppy`,68:`BIS-Plus`,69:`SD-BOX`,70:`MultiMAX`,71:`Blackbox V9`,72:`Lt. Kernal Host Adaptor`,73:`RAMLink`,74:`H.E.R.O.`,75:`IEEE Flash! 64`,76:`Turtle Graphics II`,77:`Freeze Frame MK2`,78:`Partner 64`};function p(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function m(e,t){return(e[t]<<8|e[t+1])>>>0}function h(e,t){if(!e||e.length<64||!String.fromCharCode(...Array.from(e.slice(0,16))).startsWith(`C64 CARTRIDGE`))return null;let n=p(e,16),r=m(e,22),i=e[24],a=e[25],o=``;for(let t=32;t<64&&e[t]!==0;t++)o+=String.fromCharCode(e[t]);o=o.trim();let s;s=i===0&&a===0?`16K (ROML+ROMH)`:i===0&&a===1?`8K (ROML only)`:i===1&&a===0?`Ultimax`:`inactive (pass-through)`;let c=0,l=0,u=Math.max(n,64);for(;u+16<=e.length&&String.fromCharCode(...Array.from(e.slice(u,u+4)))===`CHIP`;){let t=p(e,u+4);if(t<16)break;let n=m(e,u+14);c++,l+=n,u+=t}let d=f[r]??`Unknown(${r})`,h=t?` "${t}"`:``,g=o?` name="${o}"`:``,_=(l/1024).toFixed(0);return{line:`[C64 cart]${h} loading: hwType=${r}(${d}) | ${s} flags, ${_}K actual | ${c} CHIP(s) | ${e.length} bytes${g}`,hwType:r,hwName:d,exrom:i,game:a,bankConfig:s,cartName:o,chipCount:c,totalRomBytes:l}}var g=44100,_=class{ctx=null;workletNode=null;gainNode=null;_muted=!1;_volume=.75;_suspended=!0;_initialised=!1;_ready=!1;_readSidBuffer=null;onStateChange;get muted(){return this._muted}get volume(){return this._volume}get suspended(){return this._suspended}get ready(){return this._ready}get sampleRate(){return this.ctx?.sampleRate??g}async init(){if(this._initialised)return!this._suspended;this._initialised=!0;try{return this.ctx=new AudioContext({sampleRate:g}),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=this._volume,this.gainNode.connect(this.ctx.destination),this.ctx.addEventListener(`statechange`,()=>{let e=this._suspended;this._suspended=this.ctx?.state===`suspended`,e!==this._suspended&&this.fireStateChange()}),this._suspended=this.ctx.state===`suspended`,await this.loadWorklet(),this._suspended&&=(this.ctx.resume().catch(()=>{}),this.ctx.state===`suspended`),this.fireStateChange(),!this._suspended}catch{return!1}}async loadWorklet(){if(!this.ctx||!this.gainNode)return;let e=`/c64-ready/audio-worklet-processor.js`.replace(/\/+/g,`/`);await this.ctx.audioWorklet.addModule(e),this.workletNode=new AudioWorkletNode(this.ctx,`c64-audio-processor`,{outputChannelCount:[1]}),this.workletNode.connect(this.gainNode),this.workletNode.port.onmessage=()=>{this.feedWorklet()},this._ready=!0}setSidBufferReader(e){this._readSidBuffer=e}feedWorklet(){if(!this.workletNode||!this._readSidBuffer||this._suspended)return;let e=this._readSidBuffer();e&&e.length>0&&this.workletNode.port.postMessage(e)}async resume(){if(this.ctx)try{await this.ctx.resume(),this._suspended=this.ctx.state===`suspended`,this.fireStateChange()}catch(e){console.error(`AudioEngine: resume failed`,e)}}setMuted(e){this._muted=e,this.gainNode&&(this.gainNode.gain.value=e?0:this._volume),this.fireStateChange()}toggleMute(){this.setMuted(!this._muted)}setVolume(e){this._volume=Math.max(0,Math.min(1,e)),this.gainNode&&!this._muted&&(this.gainNode.gain.value=this._volume),this.fireStateChange()}adjustVolume(e){this.setVolume(this._volume+e)}async destroy(){this.workletNode?.disconnect(),this.gainNode?.disconnect(),await this.ctx?.close(),this.workletNode=null,this.gainNode=null,this.ctx=null,this._initialised=!1,this._ready=!1,this._suspended=!0,this._readSidBuffer=null}fireStateChange(){this.onStateChange?.({muted:this._muted,volume:this._volume,suspended:this._suspended})}},v=class{emulatorInput;captureKeyDown=e=>this.onCaptureKeyDown(e);captureKeyUp=e=>this.onCaptureKeyUp(e);constructor(e,t=window){this.emulatorInput=new d(e,t)}attach(){window.addEventListener(`keydown`,this.captureKeyDown,!0),window.addEventListener(`keyup`,this.captureKeyUp,!0),this.emulatorInput.attach()}detach(){window.removeEventListener(`keydown`,this.captureKeyDown,!0),window.removeEventListener(`keyup`,this.captureKeyUp,!0),this.emulatorInput.detach()}setKeyboardJoystickPort(e){this.emulatorInput.setKeyboardPort(e)}setInputMode(e){this.emulatorInput.setInputMode(e)}getInputMode(){return this.emulatorInput.getInputMode()}onCaptureKeyDown(e){if(new Set([...s,...Object.keys(c)]).has(e.code)){try{if(typeof document<`u`){if(`hidden`in document){if(document.hidden){e.stopImmediatePropagation();return}}else if(typeof document.hasFocus==`function`&&!document.hasFocus()){e.stopImmediatePropagation();return}}}catch{}try{if(typeof document<`u`&&(document.querySelector(`.c64-help-overlay.visible`)||document.querySelector(`.c64-menu-overlay.visible`))){e.stopImmediatePropagation(),e.preventDefault();return}}catch{}}}onCaptureKeyUp(e){if(new Set([...s,...Object.keys(c)]).has(e.code))try{if(typeof document<`u`){if(`hidden`in document){if(document.hidden){e.stopImmediatePropagation();return}}else if(typeof document.hasFocus==`function`&&!document.hasFocus()){e.stopImmediatePropagation();return}if(document.querySelector(`.c64-help-overlay.visible`)||document.querySelector(`.c64-menu-overlay.visible`)){e.stopImmediatePropagation(),e.preventDefault();return}}}catch{}}};const y=[{type:`crt`,label:`Cartridge (.crt)`,extensions:[`.crt`]},{type:`prg`,label:`Program (.prg)`,extensions:[`.prg`]},{type:`d64`,label:`Disk image (.d64)`,extensions:[`.d64`]},{type:`snapshot`,label:`Snapshot (.snapshot, .c64, .s64)`,extensions:[`.snapshot`,`.c64`,`.s64`]}];var b=new Set(y.map(e=>e.type));function x(e){return typeof e==`string`&&b.has(e)}function S(e){let t=e.toLowerCase();for(let e of y)if(e.extensions.some(e=>t.endsWith(e)))return e.type;return null}function C(e,t,n=`crt`){return e===`auto`?S(t)??n:e}function w(e){return(e===`auto`?y.flatMap(e=>e.extensions):y.find(t=>t.type===e)?.extensions??[]).join(`,`)}function T(e){return y.find(t=>t.type===e)?.label??e.toUpperCase()}var E=class{emulator=null;inputHandler=null;audio=new _;options;constructor(e){this.options={gameType:`crt`,...e}}async start(){let{wasmUrl:e,gameUrl:t,gameType:n,renderer:r,onProgress:a}=this.options;a?.(10,`INITIALISING WASM...`),this.emulator=await i.load(e),this.inputHandler=new v(this.emulator),this.inputHandler.attach(),r.attachTo(this.emulator),t&&t!==`null`&&await this.loadGame(t,n,a),this.emulator.start(),this.initAudio()}initAudio(){if(!this.emulator)return;let e=this.emulator;this.audio.onStateChange=e=>{window.dispatchEvent(new CustomEvent(`c64-audio-state`,{detail:e}))},this.audio.init().then(t=>{e.setSampleRate(this.audio.sampleRate),this.audio.setSidBufferReader(()=>e.getSidBuffer()),t||window.dispatchEvent(new CustomEvent(`c64-audio-suspended`))})}async loadGame(e,t=`crt`,n){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);n?.(20,`LOADING GAME...`);let r=await fetch(e);if(!r.ok)throw Error(`Failed to fetch game: ${r.status}`);let i=Number(r.headers.get(`content-length`)??0),a;if(i>0&&r.body){let e=r.body.getReader(),t=[],o=0,s=await e.read();for(;!s.done;){t.push(s.value),o+=s.value.byteLength;let r=20+Math.round(o/i*65);n?.(r,`LOADING GAME... ${Math.round(o/i*100)}%`),s=await e.read()}a=new Uint8Array(o);let c=0;for(let e of t)a.set(e,c),c+=e.byteLength}else a=new Uint8Array(await r.arrayBuffer());if(n?.(90,`INSERTING ${O(t)}...`),t===`crt`&&!D(a)){n?.(0,`INVALID CRT`);let e=Error(`Invalid CRT file format`);throw console.error(e),e}if(t===`crt`){let t=e.split(`/`).pop()??e,n=h(a,t);n&&console.log(n.line)}this.assertSnapshotFormatSupported(a,t,e),this.emitSnapshotLoadInfo(t,e);try{this.emulator.loadGame({type:t,data:a}),t===`prg`&&await this.autoRunPrgIfRunning(),n?.(100,`READY!`),window.dispatchEvent(new CustomEvent(`c64-load-success`,{detail:{url:e,type:t}}))}catch(r){throw n?.(0,`FAILED`),console.error(`Failed to insert cartridge or load game:`,r),window.dispatchEvent(new CustomEvent(`c64-load-error`,{detail:{error:String(r),url:e,type:t}})),r}}async loadFile(e,t){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);let n=this.options.onProgress,r=t??S(e.name)??`crt`;try{n?.(20,`READING FILE ${e.name}...`);let t=await e.arrayBuffer(),i=new Uint8Array(t);if(n?.(90,`INSERTING ${O(r)}...`),r===`crt`&&!D(i)){n?.(0,`INVALID CRT`);let e=Error(`Invalid CRT file format`);throw console.error(e),e}if(r===`crt`){let t=h(i,e.name);t&&console.log(t.line)}this.assertSnapshotFormatSupported(i,r,e.name),this.emitSnapshotLoadInfo(r,e.name);try{this.emulator.loadGame({type:r,data:i}),r===`prg`&&await this.autoRunPrgIfRunning(),n?.(100,`READY!`),window.dispatchEvent(new CustomEvent(`c64-close-dialog`,{detail:{file:e.name,type:r}}))}catch(t){throw n?.(0,`FAILED`),console.error(`Failed to insert cartridge from file:`,t),window.dispatchEvent(new CustomEvent(`c64-load-error`,{detail:{error:String(t),file:e.name,type:r}})),t}}catch(e){throw n?.(0,`FAILED`),e}}async loadTool(e,t){if(!this.emulator)throw Error(`Emulator not initialised — call start() first`);let n=this.options.onProgress,r=t??S(e)??`prg`;n?.(10,`PREPARING TOOL...`);try{this.emulator.removeCartridge()}catch{}this.emulator.reset(),this.emulator.start(),await k(120),await this.loadGame(e,r,n)}detachCartridge(){if(this.emulator)try{this.emulator.removeCartridge(),window.dispatchEvent(new CustomEvent(`c64-detach`,{detail:{}})),window.dispatchEvent(new CustomEvent(`c64-close-menu`))}catch(e){console.error(`Failed to detach cartridge:`,e)}}hardReset(){if(this.emulator)try{this.emulator.reset(),this.emulator.start(),window.dispatchEvent(new CustomEvent(`c64-hard-reset`,{detail:{}})),window.dispatchEvent(new CustomEvent(`c64-close-menu`))}catch(e){console.error(`Failed to perform hard reset:`,e)}}setKeyboardJoystickPort(e){this.inputHandler?.setKeyboardJoystickPort(e)}setInputMode(e){this.inputHandler?.setInputMode(e)}async autoRunPrgIfRunning(){!this.emulator||!this.emulator.isRunning()||(await k(220),await this.typeCommand(`run
2
2
  `))}async typeCommand(e){if(this.emulator)for(let t of e){let e=t===`
3
3
  `?`enter`:t,n=u(e,!1,`keydown`);for(let e of n)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);await k(22);let r=u(e,!1,`keyup`);for(let e of r)e.action===`press`?this.emulator.keyDown(e.key):this.emulator.keyUp(e.key);await k(22)}}emitSnapshotLoadInfo(e,t){if(e!==`snapshot`)return;let n=`native`,r=`Loading native LVL snapshot (${t})`;console.info(`[snapshot] mode=${n} source=${t}`),window.dispatchEvent(new CustomEvent(`c64-load-info`,{detail:{mode:n,source:t,message:r}}))}assertSnapshotFormatSupported(e,t,n){if(t!==`snapshot`||!A(e))return;let r=Error(`Unsupported snapshot format for ${n}. VICE .vsf snapshots are disabled for now; use LVLLVL/native snapshots (.c64, .snapshot, .s64).`);throw console.error(r),window.dispatchEvent(new CustomEvent(`c64-load-info`,{detail:{mode:`warning`,source:n,message:`Snapshot must be LVLLVL/native format (.c64, .snapshot, .s64).`}})),r}};function D(e){return h(e)!==null}function O(e){let t=T(e),n=t.indexOf(` (`);return(n>0?t.slice(0,n):t).toUpperCase()}function k(e){return new Promise(t=>setTimeout(t,e))}function A(e){if(e.length<19)return!1;for(let t=0;t<19;t++)if(e[t]!==`VICE Snapshot File`.charCodeAt(t))return!1;return!0}var j=`/* Loader styles extracted from canvas-renderer.ts */
4
4
  .c64-loader {
@@ -134,6 +134,21 @@
134
134
  list-style: none;
135
135
  font-size: 13px;
136
136
  }
137
+ .c64-help-special {
138
+ margin: 0 0 12px;
139
+ padding: 0;
140
+ list-style: none;
141
+ font-size: 12px;
142
+ }
143
+ .c64-help-special li {
144
+ display: flex;
145
+ justify-content: space-between;
146
+ padding: 3px 0;
147
+ border-bottom: 1px solid #2a2a3e;
148
+ }
149
+ .c64-help-special li:last-child {
150
+ border-bottom: none;
151
+ }
137
152
  .c64-help-controls li {
138
153
  display: flex;
139
154
  justify-content: space-between;
@@ -348,6 +363,15 @@
348
363
  padding: 4px 8px;
349
364
  font-family: monospace;
350
365
  }
366
+ .c64-tool-select {
367
+ flex: 1;
368
+ min-width: 180px;
369
+ }
370
+ .c64-tools-section {
371
+ margin-top: 12px;
372
+ padding-top: 10px;
373
+ border-top: 1px solid #2a2a3e;
374
+ }
351
375
  .c64-radio-row {
352
376
  margin-top: 8px;
353
377
  display: flex;
@@ -394,7 +418,7 @@
394
418
  flex-wrap: wrap;
395
419
  }
396
420
  .c64-btn { background:#222; border:1px solid #444; color:#ddd; padding:6px 10px; border-radius:4px; cursor:pointer; }
397
- `,P=`modulepreload`,F=function(e){return`/c64-ready/`+e},I={};const L=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=F(t,n),t in I)return;I[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:P,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};var R=[[`Move Up`,`↑`],[`Move Down`,`↓`],[`Move Left`,`←`],[`Move Right`,`→`],[`Fire`,`Left Ctrl`]],z=class{helpOverlay=null;settingsOverlay=null;fileInput=null;player=null;savedHtmlOverflow=null;savedBodyOverflow=null;init(e){this.player=e??null,this.injectCSS(),this.createButton(),this.createDialog(),this.createHamburger(),this.createMenu(),this.createUnmuteButton()}injectCSS(){if(document.querySelector(`style[data-c64-help]`))return;let e=document.createElement(`style`);e.setAttribute(`data-c64-help`,``),e.textContent=N,document.head.appendChild(e)}createButton(){let e=document.createElement(`button`);e.className=`c64-help-btn`,e.textContent=`?`,e.title=`Help`,e.addEventListener(`click`,()=>this.open()),document.body.appendChild(e)}createDialog(){let e=document.createElement(`div`);e.className=`c64-help-overlay`,e.addEventListener(`click`,t=>{t.target===e&&this.close()}),e.innerHTML=`
421
+ `,P=`modulepreload`,F=function(e){return`/c64-ready/`+e},I={};const L=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=F(t,n),t in I)return;I[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:P,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};var R=[[`Move Up`,`↑`],[`Move Down`,`↓`],[`Move Left`,`←`],[`Move Right`,`→`],[`Fire`,`Z or Left Ctrl`]],z=[[`Run/Stop`,`Esc`],[`Restore`,`Page Up (currently unsupported)`],[`Insert/Delete`,`Backspace or Delete`],[`Clear/Home`,`Home`],[`Commodore`,`Ctrl or Caps Lock`],[`Control`,`Tab`],[`Arrow Left glyph`,"`"],[`Arrow Up glyph`,`^ or ~`],[`Pound`,`\\`],[`Colon / Semicolon`,`: ; [ ]`],[`Slash`,`/ ?`],[`Comma / Period`,`, . < >`],[`C64 function keys`,`F1-F8`]],B=class{helpOverlay=null;settingsOverlay=null;fileInput=null;player=null;savedHtmlOverflow=null;savedBodyOverflow=null;init(e){this.player=e??null,this.injectCSS(),this.createButton(),this.createDialog(),this.createHamburger(),this.createMenu(),this.createUnmuteButton()}injectCSS(){if(document.querySelector(`style[data-c64-help]`))return;let e=document.createElement(`style`);e.setAttribute(`data-c64-help`,``),e.textContent=N,document.head.appendChild(e)}createButton(){let e=document.createElement(`button`);e.className=`c64-help-btn`,e.textContent=`?`,e.title=`Help`,e.addEventListener(`click`,()=>this.open()),document.body.appendChild(e)}createDialog(){let e=document.createElement(`div`);e.className=`c64-help-overlay`,e.addEventListener(`click`,t=>{t.target===e&&this.close()}),e.innerHTML=`
398
422
  <div class="c64-help-dialog">
399
423
  <button class="c64-help-close">&times;</button>
400
424
  <h2>C64 READY</h2>
@@ -402,7 +426,9 @@
402
426
  <p><a href="https://github.com/hayesmaker/c64-ready" target="_blank" rel="noopener">Source code on GitHub</a> · <a href="#" id="c64-view-changelog">View changelog</a></p>
403
427
  <h2>CONTROLS</h2>
404
428
  <ul class="c64-help-controls">${R.map(([e,t])=>`<li><span>${e}</span><span class="c64-help-key">${t}</span></li>`).join(``)}</ul>
405
- <div class="c64-version">v0.10.0 (build: 8fdb739)</div>
429
+ <h2>SPECIAL KEYS</h2>
430
+ <ul class="c64-help-special">${z.map(([e,t])=>`<li><span>${e}</span><span class="c64-help-key">${t}</span></li>`).join(``)}</ul>
431
+ <div class="c64-version">v0.11.0 (build: a24cc52)</div>
406
432
  </div>
407
433
  `,e.querySelector(`.c64-help-close`).addEventListener(`click`,()=>this.close()),document.body.appendChild(e),this.helpOverlay=e;let t=document.createElement(`div`);t.className=`c64-help-overlay`,t.style.zIndex=`1003`,t.innerHTML=`
408
434
  <div class="c64-help-dialog c64-changelog-dialog">
@@ -410,7 +436,7 @@
410
436
  <h2>CHANGELOG</h2>
411
437
  <div id="c64-changelog-content">Loading...</div>
412
438
  </div>
413
- `,t.querySelector(`.c64-help-close`).addEventListener(`click`,()=>t.classList.remove(`visible`)),document.body.appendChild(t);let n=e.querySelector(`#c64-view-changelog`);n&&n.addEventListener(`click`,e=>{e.preventDefault(),this.loadAndShowChangelog(t)})}async loadAndShowChangelog(e){e.classList.add(`visible`);try{let t=await L(()=>import(`./CHANGELOG-CPMeNyjb.js`),[]),n=(t.default??t).split(`
439
+ `,t.querySelector(`.c64-help-close`).addEventListener(`click`,()=>t.classList.remove(`visible`)),document.body.appendChild(t);let n=e.querySelector(`#c64-view-changelog`);n&&n.addEventListener(`click`,e=>{e.preventDefault(),this.loadAndShowChangelog(t)})}async loadAndShowChangelog(e){e.classList.add(`visible`);try{let t=await L(()=>import(`./CHANGELOG-CPlXKLCV.js`),[]),n=(t.default??t).split(`
414
440
  `).filter(e=>{let t=e.trim();return t.startsWith(`- `)?/^- (feat|fix)[:(]/.test(t):!0}).join(`
415
441
  `),[{marked:r},i]=await Promise.all([L(()=>import(`./marked.esm-BOXuzyNF.js`),[]),L(()=>import(`./purify.es-y41lKIN9.js`),[])]),a=i.default.sanitize(r.parse(n)),o=e.querySelector(`#c64-changelog-content`);o.innerHTML=a}catch{let t=e.querySelector(`#c64-changelog-content`);t.innerHTML=`<p>No changelog found.</p>`}}createHamburger(){let e=document.createElement(`button`);e.className=`c64-hamburger`,e.innerHTML=`&#9776;`,e.title=`Menu`,e.addEventListener(`click`,()=>this.toggleMenu()),document.body.appendChild(e)}createMenu(){let e=document.createElement(`div`);e.className=`c64-menu-overlay`,e.addEventListener(`click`,t=>{t.target===e&&this.closeMenu()});let t=[{id:`load`,label:`Load`},{id:`input`,label:`Input`},{id:`display`,label:`Display`},{id:`audio`,label:`Audio`},{id:`system`,label:`System`}],n=y.map(e=>`<option value="${e.type}">${e.label}</option>`).join(``),r=document.createElement(`div`);r.className=`c64-menu-panel`,r.innerHTML=`
416
442
  <div class="c64-menu-header">
@@ -450,6 +476,16 @@
450
476
  <button class="c64-btn" id="c64-load-btn">Load</button>
451
477
  <button class="c64-btn" id="c64-close-menu">Close</button>
452
478
  </div>
479
+ <div class="c64-tools-section">
480
+ <label class="c64-section-label">Tools</label>
481
+ <div class="c64-form-row">
482
+ <select id="c64-tool-select" class="c64-select c64-tool-select" disabled>
483
+ <option value="">No tools found</option>
484
+ </select>
485
+ <button class="c64-btn" id="c64-load-tool-btn" disabled>Load Tool</button>
486
+ </div>
487
+ <div class="c64-section-hint" id="c64-tools-status">Loading tools…</div>
488
+ </div>
453
489
  </section>
454
490
 
455
491
  <section class="c64-settings-section" data-settings-section="input" hidden>
@@ -460,11 +496,11 @@
460
496
  </div>
461
497
  <label class="c64-section-label">Input Mode</label>
462
498
  <div class="c64-radio-row c64-radio-row-wrap">
463
- <label><input type="radio" name="c64-input-mode" value="joystick" checked /> Joystick</label>
499
+ <label><input type="radio" name="c64-input-mode" value="joystick" /> Joystick</label>
464
500
  <label><input type="radio" name="c64-input-mode" value="keyboard" /> Keyboard</label>
465
- <label><input type="radio" name="c64-input-mode" value="mixed" /> Mixed</label>
501
+ <label><input type="radio" name="c64-input-mode" value="mixed" checked /> Mixed</label>
466
502
  </div>
467
- <div id="c64-input-mode-hint" class="c64-section-hint">Arrows + Ctrl = joystick</div>
503
+ <div id="c64-input-mode-hint" class="c64-section-hint">Arrows + Z + Ctrl = joystick &amp; all other keys &rarr; C64 keyboard</div>
468
504
  </section>
469
505
 
470
506
  <section class="c64-settings-section" data-settings-section="display" hidden>
@@ -489,11 +525,11 @@
489
525
  </section>
490
526
  </div>
491
527
  </div>
492
- `,r.querySelector(`.c64-menu-close`).addEventListener(`click`,()=>this.closeMenu()),r.querySelector(`#c64-close-menu`).addEventListener(`click`,()=>this.closeMenu()),e.appendChild(r),document.body.appendChild(e),this.settingsOverlay=e;let i=r.querySelectorAll(`[data-settings-tab]`),a=r.querySelectorAll(`[data-settings-section]`),o=e=>{i.forEach(t=>{let n=t.dataset.settingsTab===e;t.classList.toggle(`active`,n),t.setAttribute(`aria-selected`,n?`true`:`false`)}),a.forEach(t=>{t.hidden=t.dataset.settingsSection!==e})};i.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.settingsTab;t&&o(t)})}),this.fileInput=r.querySelector(`#c64-file-input`);let s=r.querySelector(`#c64-dragarea`),c=r.querySelector(`#c64-dragarea-copy`),l=r.querySelector(`#c64-browse`),u=r.querySelector(`#c64-load-format`),d=r.querySelector(`#c64-cart-preview`),f=r.querySelector(`#c64-cart-filename`),p=r.querySelector(`#c64-cart-type`),m=()=>{let e=u.value??`auto`;this.fileInput.accept=w(e),e===`auto`?c.textContent=`Drop a game file here or`:c.textContent=`Drop a ${T(e)} file here or`};m(),u.addEventListener(`change`,m);let h=e=>{let t=C(u.value??`auto`,e.name);d.hidden=!1,f.textContent=e.name,p.textContent=T(t);let n=new CustomEvent(`c64-load-file`,{detail:{file:e,type:t}});window.dispatchEvent(n)};s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`dragover`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`dragover`)}),s.addEventListener(`drop`,e=>{e.preventDefault(),s.classList.remove(`dragover`);let t=e.dataTransfer?.files?.[0];t&&h(t)}),l.addEventListener(`click`,()=>this.fileInput?.click()),this.fileInput.addEventListener(`change`,()=>{let e=this.fileInput?.files?.[0];e&&h(e)}),r.querySelector(`#c64-load-btn`).addEventListener(`click`,()=>{let e=this.fileInput?.files?.[0];e?h(e):this.fileInput?.click()});let g=r.querySelector(`[data-settings-section="system"]`),_=g?.querySelector(`#c64-detach-btn`),v=g?.querySelector(`#c64-reset-btn`);_&&_.addEventListener(`click`,()=>{if(!this.player||!confirm(`Detach cartridge?`))return;this.player.detachCartridge();let e=document.getElementById(`status`);e&&(e.textContent=`Cartridge detached`)}),v&&v.addEventListener(`click`,()=>{if(!this.player||!confirm(`Perform hard reset? This will restart the emulator.`))return;this.player.hardReset();let e=document.getElementById(`status`);e&&(e.textContent=`Hard reset performed`)});let b=r.querySelector(`#c64-audio-section-anchor`);this.createAudioSection(b);let x=r.querySelectorAll(`input[name="c64-joy-port"]`),S=e=>{if(window.dispatchEvent(new CustomEvent(`c64-set-keyboard-joy-port`,{detail:{port:e}})),this.player&&typeof this.player.setKeyboardJoystickPort==`function`)try{this.player.setKeyboardJoystickPort(e)}catch{}};x.forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&S(Number(e.value))})});let E={joystick:`Arrows + Ctrl = joystick only`,keyboard:`All keys &rarr; C64 keyboard matrix`,mixed:`Arrows + Z + Ctrl = joystick &amp; all other keys &rarr; C64 keyboard`},D=r.querySelectorAll(`input[name="c64-input-mode"]`),O=r.querySelector(`#c64-input-mode-hint`),k=e=>{if(O&&(O.innerHTML=E[e]??``),window.dispatchEvent(new CustomEvent(`c64-set-input-mode`,{detail:{mode:e}})),this.player&&typeof this.player.setInputMode==`function`)try{this.player.setInputMode(e)}catch{}};D.forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&k(e.value)})});let A=r.querySelectorAll(`input[name="c64-display-mode"]`),j=document.getElementById(`c64-screen`),M=e=>{j&&(j.style.width=``,j.style.height=``,j.style.objectFit=``,j.removeAttribute(`data-display-mode`),e===`standard`?(j.style.width=``,j.style.height=``,j.style.border=``,this.savedHtmlOverflow===null?document.documentElement.style.overflow=``:(document.documentElement.style.overflow=this.savedHtmlOverflow,this.savedHtmlOverflow=null),this.savedBodyOverflow===null?document.body.style.overflow=``:(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)):e===`full`?(j.style.height=`100vh`,j.style.width=`auto`,j.style.objectFit=`contain`,j.style.border=`none`,this.savedHtmlOverflow===null&&(this.savedHtmlOverflow=document.documentElement.style.overflow),this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow),document.documentElement.style.overflow=`hidden`,document.body.style.overflow=`hidden`):e===`stretch`&&(j.style.width=`100vw`,j.style.height=`100vh`,j.style.objectFit=`fill`,j.style.border=`none`,this.savedHtmlOverflow===null&&(this.savedHtmlOverflow=document.documentElement.style.overflow),this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow),document.documentElement.style.overflow=`hidden`,document.body.style.overflow=`hidden`),j.setAttribute(`data-display-mode`,e),window.dispatchEvent(new CustomEvent(`c64-display-mode-changed`,{detail:{mode:e}})))};A.forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&M(e.value)})}),window.addEventListener(`c64-close-dialog`,()=>{this.closeMenu()}),window.addEventListener(`c64-load-error`,()=>{this.settingsOverlay?.classList.remove(`visible`)})}createUnmuteButton(){let e=document.createElement(`button`);e.className=`c64-unmute-btn hidden`,e.innerHTML=`&#128263;`,e.title=`Click to enable audio`,e.addEventListener(`click`,async()=>{this.player&&(await this.player.audio.resume(),this.player.audio.suspended||e.classList.add(`hidden`))}),document.body.appendChild(e),window.addEventListener(`c64-audio-suspended`,()=>{e.classList.remove(`hidden`)}),window.addEventListener(`c64-audio-state`,(t=>{let n=t.detail;n.suspended||e.classList.add(`hidden`),this.syncAudioControls(n)}))}createAudioSection(e){let t=document.createElement(`div`);t.className=`c64-audio-section`,t.innerHTML=`
528
+ `,r.querySelector(`.c64-menu-close`).addEventListener(`click`,()=>this.closeMenu()),r.querySelector(`#c64-close-menu`).addEventListener(`click`,()=>this.closeMenu()),e.appendChild(r),document.body.appendChild(e),this.settingsOverlay=e;let i=r.querySelectorAll(`[data-settings-tab]`),a=r.querySelectorAll(`[data-settings-section]`),o=e=>{i.forEach(t=>{let n=t.dataset.settingsTab===e;t.classList.toggle(`active`,n),t.setAttribute(`aria-selected`,n?`true`:`false`)}),a.forEach(t=>{t.hidden=t.dataset.settingsSection!==e})};i.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.settingsTab;t&&o(t)})}),this.fileInput=r.querySelector(`#c64-file-input`);let s=r.querySelector(`#c64-dragarea`),c=r.querySelector(`#c64-dragarea-copy`),l=r.querySelector(`#c64-browse`),u=r.querySelector(`#c64-load-format`),d=r.querySelector(`#c64-tool-select`),f=r.querySelector(`#c64-load-tool-btn`),p=r.querySelector(`#c64-tools-status`),m=r.querySelector(`#c64-cart-preview`),h=r.querySelector(`#c64-cart-filename`),g=r.querySelector(`#c64-cart-type`),_=()=>{let e=u.value??`auto`;this.fileInput.accept=w(e),e===`auto`?c.textContent=`Drop a game file here or`:c.textContent=`Drop a ${T(e)} file here or`};_(),u.addEventListener(`change`,_);let v=e=>{let t=C(u.value??`auto`,e.name);m.hidden=!1,h.textContent=e.name,g.textContent=T(t);let n=new CustomEvent(`c64-load-file`,{detail:{file:e,type:t}});window.dispatchEvent(n)};s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`dragover`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`dragover`)}),s.addEventListener(`drop`,e=>{e.preventDefault(),s.classList.remove(`dragover`);let t=e.dataTransfer?.files?.[0];t&&v(t)}),l.addEventListener(`click`,()=>this.fileInput?.click()),this.fileInput.addEventListener(`change`,()=>{let e=this.fileInput?.files?.[0];e&&v(e)}),r.querySelector(`#c64-load-btn`).addEventListener(`click`,()=>{let e=this.fileInput?.files?.[0];e?v(e):this.fileInput?.click()});let b=[],x=()=>{if(d.innerHTML=``,b.length===0){let e=document.createElement(`option`);e.value=``,e.textContent=`No tools found`,d.appendChild(e),d.disabled=!0,f.disabled=!0;return}b.forEach((e,t)=>{let n=document.createElement(`option`);n.value=String(t),n.textContent=e.name,d.appendChild(n)}),d.disabled=!1,f.disabled=!1},E=e=>(Array.isArray(e)?e:e&&typeof e==`object`&&Array.isArray(e.tools)?e.tools:[]).map(e=>{let t=typeof e==`string`?e:e&&typeof e==`object`?e.path:void 0;if(!t||typeof t!=`string`)return null;let n=t.split(`/`).pop()??t,r=S(n);return r?{name:n,url:`/c64-ready/tools/${t.split(`/`).map(e=>encodeURIComponent(e)).join(`/`).replace(/^\/+/,``)}`.replace(/([^:]\/)\/+/,`$1`),type:r}:null}).filter(e=>!!e);f.addEventListener(`click`,()=>{let e=Number(d.value);if(!Number.isFinite(e))return;let t=b[e];t&&window.dispatchEvent(new CustomEvent(`c64-load-tool`,{detail:t}))}),(async()=>{try{let e=`/c64-ready/tools/tools.json`.replace(/([^:]\/)\/+/,`$1`),t=await fetch(e,{cache:`no-store`});if(!t.ok)throw Error(`HTTP ${t.status}`);b=E(await t.json()),x(),p.textContent=b.length>0?`Found ${b.length} tool${b.length===1?``:`s`} in /public/tools`:`No compatible tools found in manifest`}catch(e){b=[],x(),p.textContent=`Unable to load tools manifest: ${String(e?.message??e)}`}})().catch(()=>{});let D=r.querySelector(`[data-settings-section="system"]`),O=D?.querySelector(`#c64-detach-btn`),k=D?.querySelector(`#c64-reset-btn`);O&&O.addEventListener(`click`,()=>{if(!this.player||!confirm(`Detach cartridge?`))return;this.player.detachCartridge();let e=document.getElementById(`status`);e&&(e.textContent=`Cartridge detached`)}),k&&k.addEventListener(`click`,()=>{if(!this.player||!confirm(`Perform hard reset? This will restart the emulator.`))return;this.player.hardReset();let e=document.getElementById(`status`);e&&(e.textContent=`Hard reset performed`)});let A=r.querySelector(`#c64-audio-section-anchor`);this.createAudioSection(A);let j=r.querySelectorAll(`input[name="c64-joy-port"]`),M=e=>{if(window.dispatchEvent(new CustomEvent(`c64-set-keyboard-joy-port`,{detail:{port:e}})),this.player&&typeof this.player.setKeyboardJoystickPort==`function`)try{this.player.setKeyboardJoystickPort(e)}catch{}};j.forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&M(Number(e.value))})});let N={joystick:`Arrows + Ctrl = joystick only`,keyboard:`All keys &rarr; C64 keyboard matrix`,mixed:`Arrows + Z + Ctrl = joystick &amp; all other keys &rarr; C64 keyboard`},P=r.querySelectorAll(`input[name="c64-input-mode"]`),F=r.querySelector(`#c64-input-mode-hint`),I=e=>{if(F&&(F.innerHTML=N[e]??``),window.dispatchEvent(new CustomEvent(`c64-set-input-mode`,{detail:{mode:e}})),this.player&&typeof this.player.setInputMode==`function`)try{this.player.setInputMode(e)}catch{}};P.forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&I(e.value)})});let L=r.querySelectorAll(`input[name="c64-display-mode"]`),R=document.getElementById(`c64-screen`),z=e=>{R&&(R.style.width=``,R.style.height=``,R.style.objectFit=``,R.removeAttribute(`data-display-mode`),e===`standard`?(R.style.width=``,R.style.height=``,R.style.border=``,this.savedHtmlOverflow===null?document.documentElement.style.overflow=``:(document.documentElement.style.overflow=this.savedHtmlOverflow,this.savedHtmlOverflow=null),this.savedBodyOverflow===null?document.body.style.overflow=``:(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)):e===`full`?(R.style.height=`100vh`,R.style.width=`auto`,R.style.objectFit=`contain`,R.style.border=`none`,this.savedHtmlOverflow===null&&(this.savedHtmlOverflow=document.documentElement.style.overflow),this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow),document.documentElement.style.overflow=`hidden`,document.body.style.overflow=`hidden`):e===`stretch`&&(R.style.width=`100vw`,R.style.height=`100vh`,R.style.objectFit=`fill`,R.style.border=`none`,this.savedHtmlOverflow===null&&(this.savedHtmlOverflow=document.documentElement.style.overflow),this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow),document.documentElement.style.overflow=`hidden`,document.body.style.overflow=`hidden`),R.setAttribute(`data-display-mode`,e),window.dispatchEvent(new CustomEvent(`c64-display-mode-changed`,{detail:{mode:e}})))};L.forEach(e=>{e.addEventListener(`change`,()=>{e.checked&&z(e.value)})}),window.addEventListener(`c64-close-dialog`,()=>{this.closeMenu()}),window.addEventListener(`c64-load-error`,()=>{this.settingsOverlay?.classList.remove(`visible`)})}createUnmuteButton(){let e=document.createElement(`button`);e.className=`c64-unmute-btn hidden`,e.innerHTML=`&#128263;`,e.title=`Click to enable audio`,e.addEventListener(`click`,async()=>{this.player&&(await this.player.audio.resume(),this.player.audio.suspended||e.classList.add(`hidden`))}),document.body.appendChild(e),window.addEventListener(`c64-audio-suspended`,()=>{e.classList.remove(`hidden`)}),window.addEventListener(`c64-audio-state`,(t=>{let n=t.detail;n.suspended||e.classList.add(`hidden`),this.syncAudioControls(n)}))}createAudioSection(e){let t=document.createElement(`div`);t.className=`c64-audio-section`,t.innerHTML=`
493
529
  <label>Audio</label>
494
530
  <div class="c64-audio-row">
495
531
  <button class="c64-mute-btn" id="c64-mute-btn" title="Toggle mute">&#128264;</button>
496
532
  <input type="range" class="c64-volume-slider" id="c64-volume-slider" min="0" max="100" value="75" />
497
533
  <span class="c64-volume-label" id="c64-volume-label">75%</span>
498
534
  </div>
499
- `,e.appendChild(t);let n=t.querySelector(`#c64-mute-btn`),r=t.querySelector(`#c64-volume-slider`),i=t.querySelector(`#c64-volume-label`);n.addEventListener(`click`,()=>{this.player&&(this.player.audio.toggleMute(),this.player.audio.suspended&&this.player.audio.resume())}),r.addEventListener(`input`,()=>{if(!this.player)return;let e=Number(r.value)/100;this.player.audio.setVolume(e),i.textContent=`${r.value}%`,this.player.audio.suspended&&this.player.audio.resume()})}syncAudioControls(e){let t=document.getElementById(`c64-mute-btn`),n=document.getElementById(`c64-volume-slider`),r=document.getElementById(`c64-volume-label`);t&&(t.innerHTML=e.muted?`&#128263;`:`&#128264;`,t.classList.toggle(`muted`,e.muted)),n&&(n.value=String(Math.round(e.volume*100))),r&&(r.textContent=`${Math.round(e.volume*100)}%`)}toggleMenu(){this.settingsOverlay?.classList.toggle(`visible`)}closeMenu(){this.settingsOverlay?.classList.remove(`visible`)}open(){this.helpOverlay?.classList.add(`visible`)}close(){this.helpOverlay?.classList.remove(`visible`)}},B=document.getElementById(`status`),V=new M(`c64-screen`),H=`/c64-ready/`,U=new URLSearchParams(window.location.search);function W(e,t){if(!e)return`${t}games/cartridges/legend-of-wilf.crt`;let n=e.trim();return n?n.toLowerCase()===`null`?``:/^https?:\/\//i.test(n)||n.startsWith(`/`)?n:`${t}${n.replace(/^\/+/,``)}`:`${t}games/cartridges/legend-of-wilf.crt`}var G=W(U.get(`game`),H),K=S(G||``)??`crt`,q=new E({wasmUrl:`${H}c64.wasm`,gameUrl:G,gameType:K,renderer:V,onProgress:(e,t)=>V.setProgress(e,t)});new z().init(q),q.start().then(()=>{G||(B.textContent=`Autoload disabled (?game=null)`,B.style.color=`#9ecbff`),V.hideLoader()}).catch(e=>{console.error(e),V.setError(`ERROR`),B.textContent=`Error: ${e}`,B.style.color=`#f44`});var J=()=>{let e=document.hidden,t=document.querySelector(`link[rel~='icon']`),n=`${H}${e?`led-off.svg`:`led-on.svg`}`.replace(/\/+/g,`/`);t&&(t.href=n)};document.addEventListener(`visibilitychange`,J),window.addEventListener(`focus`,J),window.addEventListener(`blur`,J),J(),window.addEventListener(`c64-load-file`,async e=>{let t=e.detail,n=t.file,r=t.type,i=r===`auto`?void 0:r;if(n)try{V.showLoader(),await q.loadFile(n,x(i)?i:void 0),V.hideLoader()}catch(e){console.error(e),V.setError(`LOAD ERROR`),B.textContent=`Load error: ${e}`,B.style.color=`#f44`}}),window.addEventListener(`c64-load-error`,e=>{let t=e.detail,n=t?.error??`Unknown load error`;console.error(`C64 load error event:`,t),V.setError(`LOAD ERROR`),B.textContent=`Load error: ${n}`,B.style.color=`#f44`}),window.addEventListener(`c64-load-info`,e=>{let t=e.detail;t?.message&&(B.textContent=t.message,B.style.color=t.mode===`warning`?`#f9c74f`:`#9ecbff`,console.info(`C64 load info event:`,t))});
535
+ `,e.appendChild(t);let n=t.querySelector(`#c64-mute-btn`),r=t.querySelector(`#c64-volume-slider`),i=t.querySelector(`#c64-volume-label`);n.addEventListener(`click`,()=>{this.player&&(this.player.audio.toggleMute(),this.player.audio.suspended&&this.player.audio.resume())}),r.addEventListener(`input`,()=>{if(!this.player)return;let e=Number(r.value)/100;this.player.audio.setVolume(e),i.textContent=`${r.value}%`,this.player.audio.suspended&&this.player.audio.resume()})}syncAudioControls(e){let t=document.getElementById(`c64-mute-btn`),n=document.getElementById(`c64-volume-slider`),r=document.getElementById(`c64-volume-label`);t&&(t.innerHTML=e.muted?`&#128263;`:`&#128264;`,t.classList.toggle(`muted`,e.muted)),n&&(n.value=String(Math.round(e.volume*100))),r&&(r.textContent=`${Math.round(e.volume*100)}%`)}toggleMenu(){this.settingsOverlay?.classList.toggle(`visible`)}closeMenu(){this.settingsOverlay?.classList.remove(`visible`)}open(){this.helpOverlay?.classList.add(`visible`)}close(){this.helpOverlay?.classList.remove(`visible`)}},V=document.getElementById(`status`),H=new M(`c64-screen`),U=`/c64-ready/`,W=new URLSearchParams(window.location.search);function G(e,t){if(!e)return`${t}games/cartridges/legend-of-wilf.crt`;let n=e.trim();return n?n.toLowerCase()===`null`?``:/^https?:\/\//i.test(n)||n.startsWith(`/`)?n:`${t}${n.replace(/^\/+/,``)}`:`${t}games/cartridges/legend-of-wilf.crt`}var K=G(W.get(`game`),U),q=S(K||``)??`crt`,J=new E({wasmUrl:`${U}c64.wasm`,gameUrl:K,gameType:q,renderer:H,onProgress:(e,t)=>H.setProgress(e,t)});new B().init(J),J.start().then(()=>{K||(V.textContent=`Autoload disabled (?game=null)`,V.style.color=`#9ecbff`),H.hideLoader()}).catch(e=>{console.error(e),H.setError(`ERROR`),V.textContent=`Error: ${e}`,V.style.color=`#f44`});var Y=()=>{let e=document.hidden,t=document.querySelector(`link[rel~='icon']`),n=`${U}${e?`led-off.svg`:`led-on.svg`}`.replace(/\/+/g,`/`);t&&(t.href=n)};document.addEventListener(`visibilitychange`,Y),window.addEventListener(`focus`,Y),window.addEventListener(`blur`,Y),Y(),window.addEventListener(`c64-load-file`,async e=>{let t=e.detail,n=t.file,r=t.type,i=r===`auto`?void 0:r;if(n)try{H.showLoader(),await J.loadFile(n,x(i)?i:void 0),H.hideLoader()}catch(e){console.error(e),H.setError(`LOAD ERROR`),V.textContent=`Load error: ${e}`,V.style.color=`#f44`}}),window.addEventListener(`c64-load-tool`,async e=>{let t=e.detail;if(!t?.url)return;let n=x(t.type)?t.type:void 0;try{V.textContent=`Loading tool: ${t.name??t.url}`,V.style.color=`#9ecbff`,H.showLoader(),await J.loadTool(t.url,n),H.hideLoader()}catch(e){console.error(e),H.setError(`LOAD ERROR`),V.textContent=`Tool load error: ${e}`,V.style.color=`#f44`}}),window.addEventListener(`c64-load-error`,e=>{let t=e.detail,n=t?.error??`Unknown load error`;console.error(`C64 load error event:`,t),H.setError(`LOAD ERROR`),V.textContent=`Load error: ${n}`,V.style.color=`#f44`}),window.addEventListener(`c64-load-info`,e=>{let t=e.detail;t?.message&&(V.textContent=t.message,V.style.color=t.mode===`warning`?`#f9c74f`:`#9ecbff`,console.info(`C64 load info event:`,t))});
package/dist/index.html CHANGED
@@ -29,7 +29,7 @@
29
29
  font-size: 13px;
30
30
  }
31
31
  </style>
32
- <script type="module" crossorigin src="/c64-ready/assets/index-CeQto0sd.js"></script>
32
+ <script type="module" crossorigin src="/c64-ready/assets/index-Ckbi7gQo.js"></script>
33
33
  </head>
34
34
  <body>
35
35
  <canvas id="c64-screen" width="384" height="272"></canvas>
Binary file
@@ -0,0 +1,6 @@
1
+ {
2
+ "tools": [
3
+ "Keyboard-Test.prg",
4
+ "anykey-c64.prg"
5
+ ]
6
+ }
package/package.json CHANGED
@@ -10,7 +10,7 @@
10
10
  "retro"
11
11
  ],
12
12
  "license": "MIT",
13
- "version": "0.11.0",
13
+ "version": "1.0.0",
14
14
  "type": "module",
15
15
  "engines": {
16
16
  "node": ">=24.14"
@@ -21,7 +21,7 @@ export const JOYSTICK_KEY_CODES: Array<keyof typeof KEY_TO_JOYSTICK> = Object.ke
21
21
 
22
22
  /**
23
23
  * Input modes:
24
- * - 'joystick' — arrow keys + ControlLeft map to joystick only (default)
24
+ * - 'joystick' — arrow keys + ControlLeft map to joystick only
25
25
  * - 'keyboard' — all keys route to the C64 keyboard matrix; no joystick
26
26
  * - 'mixed' — arrow keys + Z + ControlLeft drive the joystick AND all
27
27
  * other keys route to the C64 keyboard matrix
@@ -414,6 +414,9 @@ export function domKeyToC64Actions(
414
414
  case 'home':
415
415
  main(C64_KEY.CLEAR_HOME);
416
416
  break;
417
+ case 'pageup':
418
+ main(C64_KEY.RESTORE);
419
+ break;
417
420
 
418
421
  // ── Function keys ────────────────────────────────────────────────────────
419
422
  case 'f1':
@@ -482,7 +485,7 @@ export class EmulatorInput {
482
485
  private readonly target: EventTarget;
483
486
  // Which joystick port keyboard events map to (1 or 2). Default is port 2.
484
487
  private keyboardJoystickPort: JoystickPort;
485
- private inputMode: InputMode = 'joystick';
488
+ private inputMode: InputMode = 'mixed';
486
489
  private readonly pressedControls = new Set<MappedControl>();
487
490
  private readonly keyDownHandler = (event: KeyboardEvent): void => {
488
491
  this.handleKeyDown(event);
@@ -212,6 +212,7 @@ export function domKeyToC64Actions(domKey, shiftKey, eventType) {
212
212
  case 'control': main(C64_KEY.COMMODORE); break; // Ctrl → CBM key
213
213
  case 'capslock': main(C64_KEY.COMMODORE); break; // CapsLock → CBM key
214
214
  case 'home': main(C64_KEY.CLEAR_HOME); break;
215
+ case 'pageup': main(C64_KEY.RESTORE); break;
215
216
 
216
217
  // ── Function keys ────────────────────────────────────────────────────────
217
218
  case 'f1': main(C64_KEY.F1); break;
@@ -251,4 +252,3 @@ export function domKeyToC64Actions(domKey, shiftKey, eventType) {
251
252
 
252
253
  return actions;
253
254
  }
254
-
@@ -585,8 +585,6 @@ export async function runHeadless(options = {}) {
585
585
  exports.c64_loadPRG(ptr, byteLen, 1);
586
586
  await typeCommandText(exports, 'run\n');
587
587
  } else if (loadType === 'd64') {
588
- exports.c64_removeCartridge();
589
- exports.c64_reset();
590
588
  exports.c64_setDriveEnabled(1);
591
589
  exports.c64_insertDisk(ptr, byteLen);
592
590
  } else if (loadType === 'snapshot') {
@@ -808,7 +806,9 @@ export async function runHeadless(options = {}) {
808
806
  const EVENT_LOOP_LOG_MS = 5000;
809
807
  eventLoopLogTimer = setInterval(() => {
810
808
  const lag = eventLoopMonitor ? eventLoopMonitor.min / 1e6 : 0; // ms
811
- if (lag > 5 && (logEvents || verbose)) { // only log if >5ms lag
809
+ // Keep event-loop lag diagnostics behind --verbose only. These can be
810
+ // noisy in steady-state and are intended for performance debugging.
811
+ if (lag > 5 && verbose) { // only log if >5ms lag
812
812
  console.error(`[event] event-loop-lag min=${lag.toFixed(2)}ms`);
813
813
  }
814
814
  if (eventLoopMonitor) eventLoopMonitor.reset();
@@ -1130,7 +1130,8 @@ export async function runHeadless(options = {}) {
1130
1130
  if (driftPct > 10) {
1131
1131
  console.error(`[event] drift fps-actual=${actualFps.toFixed(1)} fps-target=${targetFps} drift=${drift > 0 ? '+' : ''}${drift.toFixed(1)} (${driftPct.toFixed(0)}%)`);
1132
1132
  }
1133
- if (videoFramesDroppedLateWindow > 0 || videoFramesDroppedCapWindow > 0) {
1133
+ // Keep per-window drop telemetry behind --verbose only.
1134
+ if (verbose && (videoFramesDroppedLateWindow > 0 || videoFramesDroppedCapWindow > 0)) {
1134
1135
  console.error(`[event] webrtc-video-drop sent=${videoFramesSent} late=${videoFramesDroppedLateWindow} cap=${videoFramesDroppedCapWindow} totalLate=${videoFramesDroppedLate} totalCap=${videoFramesDroppedCap} fpsCap=${webrtcSendFps}`);
1135
1136
  }
1136
1137
  }
@@ -119,6 +119,7 @@ export function createInputServer(opts = {}) {
119
119
 
120
120
  const wss = new WebSocketServer({ port });
121
121
  const HOST_RECONNECT_GRACE = opts.hostReconnectGraceMs ?? 8_000;
122
+ const P2_RECONNECT_GRACE = opts.p2ReconnectGraceMs ?? HOST_RECONNECT_GRACE;
122
123
 
123
124
  // ── Room state ────────────────────────────────────────────────────────────
124
125
  let hostClient = null;
@@ -140,6 +141,8 @@ export function createInputServer(opts = {}) {
140
141
  // HOST_RECONNECT_GRACE ms, giving the host a chance to refresh and reclaim.
141
142
  let graceTimer = null;
142
143
  let pendingHostUsername = null; // username of the disconnected host
144
+ let p2GraceTimer = null;
145
+ let pendingP2Username = null;
143
146
  // Currently loaded cartridge filename (for hello message to late joiners).
144
147
  // Seeded from opts.initialCartFilename when a default game is pre-loaded.
145
148
  let currentCartFilename = opts.initialCartFilename ?? null;
@@ -188,6 +191,7 @@ export function createInputServer(opts = {}) {
188
191
  setWsIdentity(p2Client, 'spectator', null);
189
192
  p2Client = null;
190
193
  p2Username = null;
194
+ clearP2Grace();
191
195
  clearP2Timeout();
192
196
  broadcastAll({ type: 'player2-left', username: leaving, reason: 'timeout' });
193
197
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
@@ -199,6 +203,11 @@ export function createInputServer(opts = {}) {
199
203
  pendingHostUsername = null;
200
204
  }
201
205
 
206
+ function clearP2Grace() {
207
+ if (p2GraceTimer) { clearTimeout(p2GraceTimer); p2GraceTimer = null; }
208
+ pendingP2Username = null;
209
+ }
210
+
202
211
  // Called when grace expires without the host reconnecting.
203
212
  function expireGrace() {
204
213
  graceTimer = null;
@@ -221,6 +230,24 @@ export function createInputServer(opts = {}) {
221
230
  graceTimer = setTimeout(expireGrace, HOST_RECONNECT_GRACE);
222
231
  }
223
232
 
233
+ function expireP2Grace() {
234
+ p2GraceTimer = null;
235
+ const leaving = pendingP2Username;
236
+ pendingP2Username = null;
237
+ if (verbose) console.error(`[input-server] p2 grace expired for ${leaving}`);
238
+ logEv('p2-grace-expired', { username: leaving });
239
+ broadcastAll({ type: 'player2-left', username: leaving, reason: 'disconnect' });
240
+ broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
241
+ }
242
+
243
+ function onP2Disconnect(leaving) {
244
+ clearP2Grace();
245
+ pendingP2Username = leaving;
246
+ if (verbose) console.error(`[input-server] player2 ${leaving} disconnected — grace ${P2_RECONNECT_GRACE}ms`);
247
+ logEv('p2-disconnected', { username: leaving, graceMs: P2_RECONNECT_GRACE });
248
+ p2GraceTimer = setTimeout(expireP2Grace, P2_RECONNECT_GRACE);
249
+ }
250
+
224
251
  function kickHostForInactivity() {
225
252
  if (!hostClient) return;
226
253
  if (verbose) console.error(`[input-server] host ${hostUsername} timed out due to inactivity`);
@@ -279,6 +306,7 @@ export function createInputServer(opts = {}) {
279
306
  try { targetWs.send(JSON.stringify({ type: 'kicked', reason })); } catch (_) {}
280
307
  }
281
308
  clearP2Timeout();
309
+ clearP2Grace();
282
310
  p2Client = null;
283
311
  p2Username = null;
284
312
  setWsIdentity(targetWs, 'spectator', null);
@@ -304,7 +332,8 @@ export function createInputServer(opts = {}) {
304
332
  // True when the P2 slot is available for open joining
305
333
  function isP2SlotOpen() {
306
334
  return !!(hostClient && hostClient.readyState === hostClient.OPEN)
307
- && !(p2Client && p2Client.readyState === p2Client.OPEN);
335
+ && !(p2Client && p2Client.readyState === p2Client.OPEN)
336
+ && !p2GraceTimer;
308
337
  }
309
338
 
310
339
  let clientCount = 0;
@@ -559,7 +588,7 @@ export function createInputServer(opts = {}) {
559
588
  // ── Host issues a player-2 invite ─────────────────────────────────────
560
589
  if (msg.type === 'invite-p2') {
561
590
  if (ws !== hostClient) return;
562
- if (p2Client && p2Client.readyState === p2Client.OPEN) {
591
+ if ((p2Client && p2Client.readyState === p2Client.OPEN) || p2GraceTimer) {
563
592
  ws.send(JSON.stringify({ type: 'invite-p2-error', reason: 'slot-taken' }));
564
593
  logEv('invite-p2-rejected', { reason: 'slot-taken' });
565
594
  return;
@@ -583,12 +612,24 @@ export function createInputServer(opts = {}) {
583
612
  logEv('p2-join-rejected', { reason: 'slot-taken', username: msg.username ?? 'player2' });
584
613
  return;
585
614
  }
615
+ const requestedUsername = msg.username ?? 'player2';
616
+ const isRejoin = !!p2GraceTimer && pendingP2Username === requestedUsername;
617
+ if (p2GraceTimer && !isRejoin) {
618
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'slot-taken' }));
619
+ logEv('p2-join-rejected', {
620
+ reason: 'slot-pending-rejoin',
621
+ username: requestedUsername,
622
+ pending: pendingP2Username ?? '-',
623
+ });
624
+ return;
625
+ }
626
+ if (isRejoin) clearP2Grace();
586
627
  if (ws === hostClient) {
587
628
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'already-host' }));
588
629
  return;
589
630
  }
590
631
  p2Client = ws;
591
- p2Username = msg.username ?? 'player2';
632
+ p2Username = requestedUsername;
592
633
  inviteToken = null;
593
634
  setWsIdentity(ws, 'p2', p2Username);
594
635
  ws.send(JSON.stringify({
@@ -597,8 +638,14 @@ export function createInputServer(opts = {}) {
597
638
  broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
598
639
  // Notify all clients that the slot is now taken
599
640
  broadcastAll({ type: 'p2-slot-status', open: false });
600
- if (verbose) console.error(`[input-server] player2 open-joined: ${p2Username}`);
601
- logEv('p2-joined', { username: p2Username, joystickPort: p2Port(), method: 'open' });
641
+ if (verbose) {
642
+ console.error(`[input-server] player2 ${isRejoin ? 're' : ''}joined (open): ${p2Username}`);
643
+ }
644
+ logEv(isRejoin ? 'p2-rejoined' : 'p2-joined', {
645
+ username: p2Username,
646
+ joystickPort: p2Port(),
647
+ method: 'open',
648
+ });
602
649
  resetP2Timeout();
603
650
  return;
604
651
  }
@@ -614,8 +661,20 @@ export function createInputServer(opts = {}) {
614
661
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'slot-taken' }));
615
662
  return;
616
663
  }
664
+ const requestedUsername = msg.username ?? 'player2';
665
+ const isRejoin = !!p2GraceTimer && pendingP2Username === requestedUsername;
666
+ if (p2GraceTimer && !isRejoin) {
667
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'slot-taken' }));
668
+ logEv('p2-join-rejected', {
669
+ reason: 'slot-pending-rejoin',
670
+ username: requestedUsername,
671
+ pending: pendingP2Username ?? '-',
672
+ });
673
+ return;
674
+ }
675
+ if (isRejoin) clearP2Grace();
617
676
  p2Client = ws;
618
- p2Username = msg.username ?? 'player2';
677
+ p2Username = requestedUsername;
619
678
  inviteToken = null;
620
679
  setWsIdentity(ws, 'p2', p2Username);
621
680
  ws.send(JSON.stringify({
@@ -623,8 +682,14 @@ export function createInputServer(opts = {}) {
623
682
  }));
624
683
  broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
625
684
  broadcastAll({ type: 'p2-slot-status', open: false });
626
- if (verbose) console.error(`[input-server] player2 joined: ${p2Username}`);
627
- logEv('p2-joined', { username: p2Username, joystickPort: p2Port(), method: 'token' });
685
+ if (verbose) {
686
+ console.error(`[input-server] player2 ${isRejoin ? 're' : ''}joined (token): ${p2Username}`);
687
+ }
688
+ logEv(isRejoin ? 'p2-rejoined' : 'p2-joined', {
689
+ username: p2Username,
690
+ joystickPort: p2Port(),
691
+ method: 'token',
692
+ });
628
693
  resetP2Timeout();
629
694
  return;
630
695
  }
@@ -637,11 +702,15 @@ export function createInputServer(opts = {}) {
637
702
  p2Client.send(JSON.stringify({ type: 'kicked' }));
638
703
  }
639
704
  const leaving = p2Username;
705
+ const pendingLeaving = pendingP2Username;
640
706
  clearP2Timeout();
707
+ clearP2Grace();
641
708
  p2Client = null;
642
709
  p2Username = null;
643
710
  setWsIdentity(ws, 'spectator', null);
644
- if (leaving) broadcastAll({ type: 'player2-left', username: leaving });
711
+ if (leaving || pendingLeaving) {
712
+ broadcastAll({ type: 'player2-left', username: leaving ?? pendingLeaving, reason: 'revoked' });
713
+ }
645
714
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
646
715
  if (verbose) console.error(`[input-server] p2 revoked by host`);
647
716
  logEv('p2-kicked', { username: leaving ?? '?', by: 'host' });
@@ -948,10 +1017,7 @@ export function createInputServer(opts = {}) {
948
1017
  p2Client = null;
949
1018
  const leaving = p2Username;
950
1019
  p2Username = null;
951
- if (verbose) console.error(`[input-server] player2 ${leaving} disconnected`);
952
- logEv('p2-disconnected', { username: leaving, total: clientCount });
953
- broadcastExcept(ws, { type: 'player2-left', username: leaving });
954
- broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
1020
+ onP2Disconnect(leaving);
955
1021
  }
956
1022
  clientMeta.delete(ws);
957
1023
  });
@@ -974,6 +1040,7 @@ export function createInputServer(opts = {}) {
974
1040
  hostTaken: hostActive,
975
1041
  hostPendingRejoin: !hostActive && !!graceTimer ? { username: pendingHostUsername, graceMs: HOST_RECONNECT_GRACE } : null,
976
1042
  host: hostActive ? { username: hostUsername, joystickPort: hostPort() } : null,
1043
+ p2PendingRejoin: !p2Client && !!p2GraceTimer ? { username: pendingP2Username, graceMs: P2_RECONNECT_GRACE } : null,
977
1044
  player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
978
1045
  p2SlotOpen: isP2SlotOpen(),
979
1046
  portOverride: {
@@ -999,6 +1066,7 @@ export function createInputServer(opts = {}) {
999
1066
  clearHostTimeout();
1000
1067
  clearP2Timeout();
1001
1068
  clearGrace();
1069
+ clearP2Grace();
1002
1070
  if (_inputLogTimer) { clearInterval(_inputLogTimer); _inputLogTimer = null; }
1003
1071
  if (_latencyLogTimer) { clearInterval(_latencyLogTimer); _latencyLogTimer = null; }
1004
1072
  if (_networkStatsTimer) { clearInterval(_networkStatsTimer); _networkStatsTimer = null; }
@@ -25,6 +25,54 @@ import wrtc from '@roamhq/wrtc';
25
25
 
26
26
  const { RTCPeerConnection } = wrtc;
27
27
 
28
+ function parseCsvList(raw) {
29
+ return String(raw ?? '')
30
+ .split(',')
31
+ .map((part) => part.trim())
32
+ .filter(Boolean);
33
+ }
34
+
35
+ function buildIceServers({
36
+ iceStunUrls,
37
+ iceTurnUrls,
38
+ iceTurnUsername,
39
+ iceTurnPassword,
40
+ verbose = false,
41
+ } = {}) {
42
+ const stunUrls = parseCsvList(iceStunUrls ?? process.env.ICE_STUN_URLS);
43
+ const turnUrls = parseCsvList(iceTurnUrls ?? process.env.ICE_TURN_URLS);
44
+ const turnUsername = String(iceTurnUsername ?? process.env.ICE_TURN_USERNAME ?? '').trim();
45
+ const turnPassword = String(iceTurnPassword ?? process.env.ICE_TURN_PASSWORD ?? '').trim();
46
+
47
+ const iceServers = [];
48
+ if (stunUrls.length > 0) {
49
+ iceServers.push({ urls: stunUrls });
50
+ }
51
+
52
+ if (turnUrls.length > 0 && turnUsername && turnPassword) {
53
+ iceServers.push({
54
+ urls: turnUrls,
55
+ username: turnUsername,
56
+ credential: turnPassword,
57
+ });
58
+ } else if (turnUrls.length > 0 && verbose) {
59
+ console.error('[webrtc] ICE_TURN_URLS provided without ICE_TURN_USERNAME/ICE_TURN_PASSWORD; skipping TURN');
60
+ }
61
+
62
+ if (iceServers.length === 0) {
63
+ iceServers.push({ urls: 'stun:stun.l.google.com:19302' });
64
+ }
65
+
66
+ if (verbose) {
67
+ const stunCount = stunUrls.length;
68
+ const turnCount = turnUrls.length;
69
+ const turnEnabled = turnUrls.length > 0 && turnUsername && turnPassword;
70
+ console.error(`[webrtc] ICE config stunUrls=${stunCount} turnUrls=${turnCount} turnEnabled=${turnEnabled ? 'yes' : 'no'}`);
71
+ }
72
+
73
+ return iceServers;
74
+ }
75
+
28
76
  /**
29
77
  * @param {object} opts
30
78
  * @param {number} [opts.port=9002] HTTP + WS listen port
@@ -38,6 +86,10 @@ const { RTCPeerConnection } = wrtc;
38
86
  * a { type: 'capacity-full' } message.
39
87
  * @param {number} [opts.minBitrateKbps=200] SDP x-google-min-bitrate for VP8 answer
40
88
  * @param {number} [opts.maxBitrateKbps=600] SDP x-google-max-bitrate for VP8 answer
89
+ * @param {string|string[]} [opts.iceStunUrls] Optional STUN URL list
90
+ * @param {string|string[]} [opts.iceTurnUrls] Optional TURN URL list
91
+ * @param {string} [opts.iceTurnUsername] Optional TURN username
92
+ * @param {string} [opts.iceTurnPassword] Optional TURN credential/password
41
93
  * @param {(pc: RTCPeerConnection) => void} opts.onOffer
42
94
  * Called synchronously when an SDP offer arrives, BEFORE createAnswer().
43
95
  * Attach tracks here: pc.addTrack(videoTrack, stream)
@@ -53,9 +105,21 @@ export function createWebRTCServer({
53
105
  maxSpectators = 3,
54
106
  minBitrateKbps = 200,
55
107
  maxBitrateKbps = 600,
108
+ iceStunUrls,
109
+ iceTurnUrls,
110
+ iceTurnUsername,
111
+ iceTurnPassword,
56
112
  onOffer,
57
113
  onPeerConnected,
58
114
  } = {}) {
115
+ const iceServers = buildIceServers({
116
+ iceStunUrls,
117
+ iceTurnUrls,
118
+ iceTurnUsername,
119
+ iceTurnPassword,
120
+ verbose,
121
+ });
122
+
59
123
  /** Emit a structured [event] line — same format as input-server.mjs. */
60
124
  function logEv(tag, fields = {}) {
61
125
  if (!logEvents) return;
@@ -333,7 +397,7 @@ export function createWebRTCServer({
333
397
  const httpServer = http.createServer((req, res) => {
334
398
  if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
335
399
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
336
- res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe));
400
+ res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe, iceServers));
337
401
  } else if (req.url === '/favicon.ico') {
338
402
  // Return a minimal 1×1 transparent ICO so browsers don't log a 404
339
403
  res.writeHead(204);
@@ -406,9 +470,7 @@ export function createWebRTCServer({
406
470
  logEv('webrtc-peer-connected', { addr: remoteAddr });
407
471
  logLoadSnapshot('webrtc-load-change', { reason: 'peer-connected' });
408
472
 
409
- const pc = new RTCPeerConnection({
410
- iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
411
- });
473
+ const pc = new RTCPeerConnection({ iceServers });
412
474
  const controller = {
413
475
  pc,
414
476
  ws,
@@ -717,9 +779,10 @@ export function createWebRTCServer({
717
779
  }
718
780
 
719
781
  // ─── Embedded browser-side player page ──────────────────────────────────────
720
- function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600) {
782
+ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600, iceServers = [{ urls: 'stun:stun.l.google.com:19302' }]) {
721
783
  const minKbps = Math.max(50, Math.round(minBitrateKbps));
722
784
  const maxKbps = Math.max(minKbps, Math.round(maxBitrateKbps));
785
+ const iceServersJson = JSON.stringify(iceServers).replace(/</g, '\\u003c');
723
786
  return /* html */ `<!DOCTYPE html>
724
787
  <html lang="en">
725
788
  <head>
@@ -851,6 +914,7 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600)
851
914
  const syncBtn = document.getElementById('sync-btn');
852
915
  const modeBtn = document.getElementById('mode-btn');
853
916
  const fileInput = document.getElementById('file-input');
917
+ const ICE_SERVERS = ${iceServersJson};
854
918
 
855
919
  function setBadge(el, text, cls) {
856
920
  el.textContent = text;
@@ -994,7 +1058,7 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600)
994
1058
  const sigUrl = new URL('ws://' + location.host);
995
1059
  sigUrl.searchParams.set('sid', rtcSessionId);
996
1060
  sigWs = new WebSocket(sigUrl.toString());
997
- pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] });
1061
+ pc = new RTCPeerConnection({ iceServers: ICE_SERVERS });
998
1062
  let offerSent = false;
999
1063
  const pendingLocalCandidates = [];
1000
1064
  const pendingRemoteCandidates = [];
package/src/main.ts CHANGED
@@ -89,6 +89,26 @@ window.addEventListener('c64-load-file', async (e: Event) => {
89
89
  }
90
90
  });
91
91
 
92
+ window.addEventListener('c64-load-tool', async (e: Event) => {
93
+ const detail = (e as CustomEvent).detail as
94
+ | { name?: string; url?: string; type?: string }
95
+ | undefined;
96
+ if (!detail?.url) return;
97
+ const loadType = isSupportedLoadType(detail.type) ? detail.type : undefined;
98
+ try {
99
+ status.textContent = `Loading tool: ${detail.name ?? detail.url}`;
100
+ status.style.color = '#9ecbff';
101
+ renderer.showLoader();
102
+ await player.loadTool(detail.url, loadType);
103
+ renderer.hideLoader();
104
+ } catch (err) {
105
+ console.error(err);
106
+ renderer.setError('LOAD ERROR');
107
+ status.textContent = `Tool load error: ${err}`;
108
+ status.style.color = '#f44';
109
+ }
110
+ });
111
+
92
112
  // Global listener for load errors dispatched by C64Player
93
113
  window.addEventListener('c64-load-error', (e: Event) => {
94
114
  const detail = (e as CustomEvent).detail as
@@ -204,6 +204,24 @@ export class C64Player {
204
204
  }
205
205
  }
206
206
 
207
+ async loadTool(url: string, type?: GameLoadOptions['type']): Promise<void> {
208
+ if (!this.emulator) throw new Error('Emulator not initialised — call start() first');
209
+ const onProgress = this.options.onProgress;
210
+ const resolvedType = type ?? inferLoadTypeFromFilename(url) ?? 'prg';
211
+
212
+ onProgress?.(10, 'PREPARING TOOL...');
213
+ try {
214
+ this.emulator.removeCartridge();
215
+ } catch {
216
+ // ignore if no cartridge is mounted
217
+ }
218
+ this.emulator.reset();
219
+ this.emulator.start();
220
+ await waitMs(120);
221
+
222
+ await this.loadGame(url, resolvedType, onProgress);
223
+ }
224
+
207
225
  // Expose cartridge / reset controls for UI
208
226
  detachCartridge(): void {
209
227
  if (!this.emulator) return;
@@ -250,7 +268,7 @@ export class C64Player {
250
268
 
251
269
  private async autoRunPrgIfRunning(): Promise<void> {
252
270
  if (!this.emulator || !this.emulator.isRunning()) return;
253
- await waitMs(120);
271
+ await waitMs(220);
254
272
  await this.typeCommand('run\n');
255
273
  }
256
274
 
@@ -91,6 +91,21 @@
91
91
  list-style: none;
92
92
  font-size: 13px;
93
93
  }
94
+ .c64-help-special {
95
+ margin: 0 0 12px;
96
+ padding: 0;
97
+ list-style: none;
98
+ font-size: 12px;
99
+ }
100
+ .c64-help-special li {
101
+ display: flex;
102
+ justify-content: space-between;
103
+ padding: 3px 0;
104
+ border-bottom: 1px solid #2a2a3e;
105
+ }
106
+ .c64-help-special li:last-child {
107
+ border-bottom: none;
108
+ }
94
109
  .c64-help-controls li {
95
110
  display: flex;
96
111
  justify-content: space-between;
@@ -305,6 +320,15 @@
305
320
  padding: 4px 8px;
306
321
  font-family: monospace;
307
322
  }
323
+ .c64-tool-select {
324
+ flex: 1;
325
+ min-width: 180px;
326
+ }
327
+ .c64-tools-section {
328
+ margin-top: 12px;
329
+ padding-top: 10px;
330
+ border-top: 1px solid #2a2a3e;
331
+ }
308
332
  .c64-radio-row {
309
333
  margin-top: 8px;
310
334
  display: flex;
@@ -6,7 +6,23 @@ const CONTROLS = [
6
6
  ['Move Down', '↓'],
7
7
  ['Move Left', '←'],
8
8
  ['Move Right', '→'],
9
- ['Fire', 'Left Ctrl'],
9
+ ['Fire', 'Z or Left Ctrl'],
10
+ ];
11
+
12
+ const SPECIAL_KEYS = [
13
+ ['Run/Stop', 'Esc'],
14
+ ['Restore', '(currently unsupported)'],
15
+ ['Insert/Delete', 'Backspace or Delete'],
16
+ ['Clear/Home', 'Home'],
17
+ ['Commodore', 'Ctrl or Caps Lock'],
18
+ ['Control', 'Tab'],
19
+ ['Arrow Left glyph', '`'],
20
+ ['Arrow Up glyph', '^ or ~'],
21
+ ['Pound', '\\'],
22
+ ['Colon / Semicolon', ': ; [ ]'],
23
+ ['Slash', '/ ?'],
24
+ ['Comma / Period', ', . < >'],
25
+ ['C64 function keys', 'F1-F8'],
10
26
  ];
11
27
 
12
28
  import type { C64Player } from './c64-player';
@@ -15,7 +31,9 @@ import {
15
31
  LOAD_FORMAT_OPTIONS,
16
32
  getAcceptForLoadTypeSelection,
17
33
  getLoadTypeLabel,
34
+ inferLoadTypeFromFilename,
18
35
  resolveLoadTypeSelection,
36
+ type LoadType,
19
37
  type LoadTypeSelection,
20
38
  } from './load-formats';
21
39
 
@@ -66,6 +84,10 @@ export default class UIController {
66
84
  ([action, key]) => `<li><span>${action}</span><span class="c64-help-key">${key}</span></li>`,
67
85
  ).join('');
68
86
 
87
+ const specialItems = SPECIAL_KEYS.map(
88
+ ([action, key]) => `<li><span>${action}</span><span class="c64-help-key">${key}</span></li>`,
89
+ ).join('');
90
+
69
91
  overlay.innerHTML = `
70
92
  <div class="c64-help-dialog">
71
93
  <button class="c64-help-close">&times;</button>
@@ -74,6 +96,8 @@ export default class UIController {
74
96
  <p><a href="https://github.com/hayesmaker/c64-ready" target="_blank" rel="noopener">Source code on GitHub</a> · <a href="#" id="c64-view-changelog">View changelog</a></p>
75
97
  <h2>CONTROLS</h2>
76
98
  <ul class="c64-help-controls">${controlItems}</ul>
99
+ <h2>SPECIAL KEYS</h2>
100
+ <ul class="c64-help-special">${specialItems}</ul>
77
101
  <div class="c64-version">${
78
102
  'v' +
79
103
  (import.meta.env.VITE_APP_VERSION ?? '0.0.0') +
@@ -215,6 +239,16 @@ export default class UIController {
215
239
  <button class="c64-btn" id="c64-load-btn">Load</button>
216
240
  <button class="c64-btn" id="c64-close-menu">Close</button>
217
241
  </div>
242
+ <div class="c64-tools-section">
243
+ <label class="c64-section-label">Tools</label>
244
+ <div class="c64-form-row">
245
+ <select id="c64-tool-select" class="c64-select c64-tool-select" disabled>
246
+ <option value="">No tools found</option>
247
+ </select>
248
+ <button class="c64-btn" id="c64-load-tool-btn" disabled>Load Tool</button>
249
+ </div>
250
+ <div class="c64-section-hint" id="c64-tools-status">Loading tools…</div>
251
+ </div>
218
252
  </section>
219
253
 
220
254
  <section class="c64-settings-section" data-settings-section="input" hidden>
@@ -225,11 +259,11 @@ export default class UIController {
225
259
  </div>
226
260
  <label class="c64-section-label">Input Mode</label>
227
261
  <div class="c64-radio-row c64-radio-row-wrap">
228
- <label><input type="radio" name="c64-input-mode" value="joystick" checked /> Joystick</label>
262
+ <label><input type="radio" name="c64-input-mode" value="joystick" /> Joystick</label>
229
263
  <label><input type="radio" name="c64-input-mode" value="keyboard" /> Keyboard</label>
230
- <label><input type="radio" name="c64-input-mode" value="mixed" /> Mixed</label>
264
+ <label><input type="radio" name="c64-input-mode" value="mixed" checked /> Mixed</label>
231
265
  </div>
232
- <div id="c64-input-mode-hint" class="c64-section-hint">Arrows + Ctrl = joystick</div>
266
+ <div id="c64-input-mode-hint" class="c64-section-hint">Arrows + Z + Ctrl = joystick &amp; all other keys &rarr; C64 keyboard</div>
233
267
  </section>
234
268
 
235
269
  <section class="c64-settings-section" data-settings-section="display" hidden>
@@ -293,6 +327,9 @@ export default class UIController {
293
327
  const dragareaCopy = panel.querySelector('#c64-dragarea-copy') as HTMLElement;
294
328
  const browse = panel.querySelector('#c64-browse') as HTMLButtonElement;
295
329
  const loadTypeSelect = panel.querySelector('#c64-load-format') as HTMLSelectElement;
330
+ const toolSelect = panel.querySelector('#c64-tool-select') as HTMLSelectElement;
331
+ const loadToolBtn = panel.querySelector('#c64-load-tool-btn') as HTMLButtonElement;
332
+ const toolsStatus = panel.querySelector('#c64-tools-status') as HTMLElement;
296
333
  const preview = panel.querySelector('#c64-cart-preview') as HTMLElement;
297
334
  const previewName = panel.querySelector('#c64-cart-filename') as HTMLElement;
298
335
  const previewType = panel.querySelector('#c64-cart-type') as HTMLElement;
@@ -347,6 +384,90 @@ export default class UIController {
347
384
  else this.fileInput?.click();
348
385
  });
349
386
 
387
+ type ToolItem = { name: string; url: string; type: LoadType };
388
+ let toolItems: ToolItem[] = [];
389
+
390
+ const renderToolSelect = () => {
391
+ toolSelect.innerHTML = '';
392
+ if (toolItems.length === 0) {
393
+ const opt = document.createElement('option');
394
+ opt.value = '';
395
+ opt.textContent = 'No tools found';
396
+ toolSelect.appendChild(opt);
397
+ toolSelect.disabled = true;
398
+ loadToolBtn.disabled = true;
399
+ return;
400
+ }
401
+ toolItems.forEach((tool, i) => {
402
+ const opt = document.createElement('option');
403
+ opt.value = String(i);
404
+ opt.textContent = tool.name;
405
+ toolSelect.appendChild(opt);
406
+ });
407
+ toolSelect.disabled = false;
408
+ loadToolBtn.disabled = false;
409
+ };
410
+
411
+ const parseManifest = (raw: unknown): ToolItem[] => {
412
+ const entries: unknown[] =
413
+ Array.isArray(raw)
414
+ ? raw
415
+ : raw && typeof raw === 'object' && Array.isArray((raw as { tools?: unknown[] }).tools)
416
+ ? (raw as { tools: unknown[] }).tools
417
+ : [];
418
+
419
+ return entries
420
+ .map((entry) => {
421
+ const path =
422
+ typeof entry === 'string'
423
+ ? entry
424
+ : entry && typeof entry === 'object'
425
+ ? ((entry as { path?: unknown }).path as string | undefined)
426
+ : undefined;
427
+ if (!path || typeof path !== 'string') return null;
428
+ const filename = path.split('/').pop() ?? path;
429
+ const type = inferLoadTypeFromFilename(filename);
430
+ if (!type) return null;
431
+ const encodedPath = path
432
+ .split('/')
433
+ .map((part) => encodeURIComponent(part))
434
+ .join('/');
435
+ const normalizedPath = encodedPath.replace(/^\/+/, '');
436
+ const url = `${import.meta.env.BASE_URL}tools/${normalizedPath}`.replace(/([^:]\/)\/+/, '$1');
437
+ return { name: filename, url, type } satisfies ToolItem;
438
+ })
439
+ .filter((v): v is ToolItem => !!v);
440
+ };
441
+
442
+ const loadToolsManifest = async () => {
443
+ try {
444
+ const url = `${import.meta.env.BASE_URL}tools/tools.json`.replace(/([^:]\/)\/+/, '$1');
445
+ const res = await fetch(url, { cache: 'no-store' });
446
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
447
+ const raw = await res.json();
448
+ toolItems = parseManifest(raw);
449
+ renderToolSelect();
450
+ toolsStatus.textContent =
451
+ toolItems.length > 0
452
+ ? `Found ${toolItems.length} tool${toolItems.length === 1 ? '' : 's'} in /public/tools`
453
+ : 'No compatible tools found in manifest';
454
+ } catch (err) {
455
+ toolItems = [];
456
+ renderToolSelect();
457
+ toolsStatus.textContent = `Unable to load tools manifest: ${String((err as Error)?.message ?? err)}`;
458
+ }
459
+ };
460
+
461
+ loadToolBtn.addEventListener('click', () => {
462
+ const idx = Number(toolSelect.value);
463
+ if (!Number.isFinite(idx)) return;
464
+ const tool = toolItems[idx];
465
+ if (!tool) return;
466
+ window.dispatchEvent(new CustomEvent('c64-load-tool', { detail: tool }));
467
+ });
468
+
469
+ loadToolsManifest().catch(() => {});
470
+
350
471
  const section = panel.querySelector('[data-settings-section="system"]');
351
472
  // Detach cartridge / hard reset controls
352
473
  const detachBtn = section?.querySelector('#c64-detach-btn') as HTMLButtonElement | null;