diff --git a/CMakeLists.txt b/CMakeLists.txt index 96191a1..7da7e18 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,6 +47,7 @@ if (NOT EMSCRIPTEN) src/options.c src/emulator.c src/host.c + src/host-input.c src/host-gl.c src/host-ui-simple.c src/joypad.c @@ -71,6 +72,7 @@ if (NOT EMSCRIPTEN) src/options.c src/emulator-debug.c src/host.c + src/host-input.c src/host-gl.c src/host-ui-imgui.cc src/joypad.c diff --git a/README.md b/README.md index 1fa2b81..bf31341 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ A simple GB/GBC emulator. * **Rewind** and seek to specific cycle * Disable/enable each audio channel * Disable/enable BG, Window and Sprite layers +* **PS/2 keyboard** over link port emulation * Convenient Python test harness using hashes to validate * (WIP) **Debugger** with various visualizations (see below) @@ -62,6 +63,8 @@ A simple GB/GBC emulator. Copy the folowing files to your webserver: * `docs/binjgb.js` * `docs/binjgb.wasm` +* `docs/keyboard.js` +* `docs/binjgb.ini` * `docs/simple.html` * `docs/simple.js` * `docs/simple.css` @@ -199,6 +202,12 @@ Keys: | Pause | Space | | Step one frame | N | +Keys not reserved for the joypad or the shortcuts above are sent to an +emulated PS/2 keyboard attached to the link port. Each scan code is sent +as two externally-clocked serial bytes holding the 11-bit PS/2 frame. + +Use `--no-ps2-keyboard` to disconnect the keyboard. + ## INI file Binjgb tries to read from `binjgb.ini` on startup for configuration. The @@ -252,11 +261,54 @@ random-seed=0 # 0=Don't display SGB border # 1=Display SGB border, even if it doesn't exist. sgb-border=0 + +# Connect an emulated PS/2 keyboard to the serial port. +# 0=Disable +# 1=Enable +ps2-keyboard=1 + +# Which unreserved keys may be sent to PS/2: all, none, or a comma-separated +# list of physical key names (e.g. A,B,C,SPACE,RETURN). +ps2-keys=all ``` The INI file is loaded before parsing the command line flags, so you can use the command line to override the values in the INI file. +### Keyboard routing + +Keyboard input can only go to one destination. Emulator shortcut are mapped first, +followed by keyboard joypad binding, then PS/2 (if connected and allowed by `ps2-keys`). +Each binding accepts `none`, or a comma-separated list of key names. +Names are case-insensitive and use SDL scancode tokens without the `SDL_SCANCODE_` prefix: + +`A` through `Z`, `0` through `9`, `KP_0` through `KP_9`, `F1` through `F12`, +`UP`, `DOWN`, `LEFT`, `RIGHT`, `RETURN`, `ESCAPE`, +`BACKSPACE`, `TAB`, `SPACE`, `LSHIFT`, `RSHIFT`, `LCTRL`, `RCTRL`, `LALT`, +`RALT`, `LGUI`, `RGUI`, `APPLICATION`, `CAPSLOCK`, `NUMLOCKCLEAR`, `SCROLLLOCK`, +`INSERT`, `DELETE`, `HOME`, `END`, `PAGEUP`, `PAGEDOWN`, `MINUS`, `EQUALS`, +`LEFTBRACKET`, `RIGHTBRACKET`, `BACKSLASH`, `SEMICOLON`, `APOSTROPHE`, `GRAVE`, +`COMMA`, `PERIOD`, `SLASH`, `KP_PERIOD`, `KP_MULTIPLY`, +`KP_MINUS`, `KP_PLUS`, `KP_DIVIDE`, and `KP_ENTER`. + +| Setting | Default | +| --- | --- | +| `joypad-up`, `joypad-down`, `joypad-left`, `joypad-right` | `UP`, `DOWN`, `LEFT`, `RIGHT` | +| `joypad-b`, `joypad-a`, `joypad-start`, `joypad-select` | `Z`, `X`, `RETURN`, `TAB` | +| `shortcut-quit` | `ESCAPE` | +| `shortcut-save-state`, `shortcut-load-state` | `F6`, `F9` | +| `shortcut-fullscreen` | `F11` | +| `shortcut-audio-1` through `shortcut-audio-4` | `1` through `4` | +| `shortcut-bg`, `shortcut-window`, `shortcut-obj` | `B`, `W`, `O` | +| `shortcut-fast-forward`, `shortcut-rewind` | `LSHIFT`, `BACKSPACE` | +| `shortcut-pause`, `shortcut-step` | `SPACE`, `N` | +| `shortcut-volume-down`, `shortcut-volume-up` | `MINUS`, `EQUALS` | +| `shortcut-palette-prev`, `shortcut-palette-next` | `LEFTBRACKET`, `RIGHTBRACKET` | + +Use `joypad=none` or `shortcuts=none` to clear a whole group before assigning +individual bindings. `joypad=default` and `shortcuts=default` restore the +respective defaults. + ## Running tests Run `scripts/build_tests.py` to download and build the necessary testsuites. diff --git a/docs/binjgb.ini b/docs/binjgb.ini new file mode 100644 index 0000000..27fbf28 --- /dev/null +++ b/docs/binjgb.ini @@ -0,0 +1,19 @@ +# Keyboard configuration shared by index.html and simple.html. +# Reload the page after editing. Physical key names match the native INI. +ps2-keyboard=1 +ps2-keys=all + +# Defaults preserve each page's existing joypad and shortcut bindings. +# For a typing profile, uncomment the following block. Physical controllers +# and the simple page's touch controls remain available. +# joypad=none +# shortcuts=none +# shortcut-pause=F5 +# shortcut-save-state=F6 +# shortcut-rewind=F8 +# shortcut-load-state=F9 +# shortcut-fullscreen=F11 + +# Leave Ctrl/Alt/Meta combinations to the browser by default. Set to 1 to +# forward supported combinations to the emulator instead. +capture-browser-shortcuts=0 diff --git a/docs/binjgb.js b/docs/binjgb.js index 5cdd583..12564ec 100644 --- a/docs/binjgb.js +++ b/docs/binjgb.js @@ -1,2 +1,21 @@ -var Binjgb=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["e"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("binjgb.wasm")}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var abortOnCannotGrowMemory=requestedSize=>{abort("OOM")};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;abortOnCannotGrowMemory(requestedSize)};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var printCharBuffers=[null,[],[]];var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var printChar=(stream,curr)=>{var buffer=printCharBuffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer));buffer.length=0}else{buffer.push(curr)}};var _fd_write=(fd,iov,iovcnt,pnum)=>{var num=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j>2]=num;return 0};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_file_data_delete,_free,_emulator_set_builtin_palette,_emulator_was_ext_ram_updated,_emulator_read_state,_emulator_write_state,_emulator_read_ext_ram,_emulator_write_ext_ram,_emulator_delete,_emulator_get_PC,_emulator_get_A,_emulator_get_BC,_emulator_get_DE,_emulator_get_HL,_emulator_get_F,_emulator_get_SP,_emulator_set_PC,_emulator_get_wram_ptr,_emulator_get_hram_ptr,_emulator_read_mem,_emulator_write_mem,_emulator_set_breakpoint,_emulator_clear_breakpoints,_emulator_render_vram,_emulator_render_background,_emulator_get_banked_PC,_set_audio_channel_mute,_joypad_new,_joypad_delete,_rewind_append,_rewind_delete,_emulator_new_simple,_emulator_get_ticks_f64,_emulator_run_until_f64,_rewind_get_newest_ticks_f64,_rewind_get_oldest_ticks_f64,_emulator_set_default_joypad_callback,_emulator_set_bw_palette_simple,_rewind_new_simple,_rewind_begin,_emulator_set_rewind_joypad_callback,_rewind_to_ticks_wrapper,_rewind_end,_set_joyp_up,_set_joyp_down,_set_joyp_left,_set_joyp_right,_set_joyp_B,_set_joyp_A,_set_joyp_start,_set_joyp_select,_get_frame_buffer_ptr,_get_frame_buffer_size,_get_sgb_frame_buffer_ptr,_get_sgb_frame_buffer_size,_get_audio_buffer_ptr,_get_audio_buffer_capacity,_ext_ram_file_data_new,_state_file_data_new,_get_file_data_ptr,_get_file_data_size,_set_log_apu_writes,_get_apu_log_data_size,_get_apu_log_data_ptr,_reset_apu_log,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["f"];_file_data_delete=Module["_file_data_delete"]=wasmExports["g"];_free=Module["_free"]=wasmExports["h"];_emulator_set_builtin_palette=Module["_emulator_set_builtin_palette"]=wasmExports["i"];_emulator_was_ext_ram_updated=Module["_emulator_was_ext_ram_updated"]=wasmExports["j"];_emulator_read_state=Module["_emulator_read_state"]=wasmExports["k"];_emulator_write_state=Module["_emulator_write_state"]=wasmExports["l"];_emulator_read_ext_ram=Module["_emulator_read_ext_ram"]=wasmExports["m"];_emulator_write_ext_ram=Module["_emulator_write_ext_ram"]=wasmExports["n"];_emulator_delete=Module["_emulator_delete"]=wasmExports["o"];_emulator_get_PC=Module["_emulator_get_PC"]=wasmExports["p"];_emulator_get_A=Module["_emulator_get_A"]=wasmExports["q"];_emulator_get_BC=Module["_emulator_get_BC"]=wasmExports["r"];_emulator_get_DE=Module["_emulator_get_DE"]=wasmExports["s"];_emulator_get_HL=Module["_emulator_get_HL"]=wasmExports["t"];_emulator_get_F=Module["_emulator_get_F"]=wasmExports["u"];_emulator_get_SP=Module["_emulator_get_SP"]=wasmExports["v"];_emulator_set_PC=Module["_emulator_set_PC"]=wasmExports["w"];_emulator_get_wram_ptr=Module["_emulator_get_wram_ptr"]=wasmExports["x"];_emulator_get_hram_ptr=Module["_emulator_get_hram_ptr"]=wasmExports["y"];_emulator_read_mem=Module["_emulator_read_mem"]=wasmExports["z"];_emulator_write_mem=Module["_emulator_write_mem"]=wasmExports["A"];_emulator_set_breakpoint=Module["_emulator_set_breakpoint"]=wasmExports["B"];_emulator_clear_breakpoints=Module["_emulator_clear_breakpoints"]=wasmExports["C"];_emulator_render_vram=Module["_emulator_render_vram"]=wasmExports["D"];_emulator_render_background=Module["_emulator_render_background"]=wasmExports["E"];_emulator_get_banked_PC=Module["_emulator_get_banked_PC"]=wasmExports["F"];_set_audio_channel_mute=Module["_set_audio_channel_mute"]=wasmExports["G"];_joypad_new=Module["_joypad_new"]=wasmExports["H"];_joypad_delete=Module["_joypad_delete"]=wasmExports["I"];_rewind_append=Module["_rewind_append"]=wasmExports["J"];_rewind_delete=Module["_rewind_delete"]=wasmExports["K"];_emulator_new_simple=Module["_emulator_new_simple"]=wasmExports["L"];_emulator_get_ticks_f64=Module["_emulator_get_ticks_f64"]=wasmExports["M"];_emulator_run_until_f64=Module["_emulator_run_until_f64"]=wasmExports["N"];_rewind_get_newest_ticks_f64=Module["_rewind_get_newest_ticks_f64"]=wasmExports["O"];_rewind_get_oldest_ticks_f64=Module["_rewind_get_oldest_ticks_f64"]=wasmExports["P"];_emulator_set_default_joypad_callback=Module["_emulator_set_default_joypad_callback"]=wasmExports["Q"];_emulator_set_bw_palette_simple=Module["_emulator_set_bw_palette_simple"]=wasmExports["R"];_rewind_new_simple=Module["_rewind_new_simple"]=wasmExports["S"];_rewind_begin=Module["_rewind_begin"]=wasmExports["T"];_emulator_set_rewind_joypad_callback=Module["_emulator_set_rewind_joypad_callback"]=wasmExports["U"];_rewind_to_ticks_wrapper=Module["_rewind_to_ticks_wrapper"]=wasmExports["V"];_rewind_end=Module["_rewind_end"]=wasmExports["W"];_set_joyp_up=Module["_set_joyp_up"]=wasmExports["X"];_set_joyp_down=Module["_set_joyp_down"]=wasmExports["Y"];_set_joyp_left=Module["_set_joyp_left"]=wasmExports["Z"];_set_joyp_right=Module["_set_joyp_right"]=wasmExports["_"];_set_joyp_B=Module["_set_joyp_B"]=wasmExports["$"];_set_joyp_A=Module["_set_joyp_A"]=wasmExports["aa"];_set_joyp_start=Module["_set_joyp_start"]=wasmExports["ba"];_set_joyp_select=Module["_set_joyp_select"]=wasmExports["ca"];_get_frame_buffer_ptr=Module["_get_frame_buffer_ptr"]=wasmExports["da"];_get_frame_buffer_size=Module["_get_frame_buffer_size"]=wasmExports["ea"];_get_sgb_frame_buffer_ptr=Module["_get_sgb_frame_buffer_ptr"]=wasmExports["fa"];_get_sgb_frame_buffer_size=Module["_get_sgb_frame_buffer_size"]=wasmExports["ga"];_get_audio_buffer_ptr=Module["_get_audio_buffer_ptr"]=wasmExports["ha"];_get_audio_buffer_capacity=Module["_get_audio_buffer_capacity"]=wasmExports["ia"];_ext_ram_file_data_new=Module["_ext_ram_file_data_new"]=wasmExports["ja"];_state_file_data_new=Module["_state_file_data_new"]=wasmExports["ka"];_get_file_data_ptr=Module["_get_file_data_ptr"]=wasmExports["la"];_get_file_data_size=Module["_get_file_data_size"]=wasmExports["ma"];_set_log_apu_writes=Module["_set_log_apu_writes"]=wasmExports["na"];_get_apu_log_data_size=Module["_get_apu_log_data_size"]=wasmExports["oa"];_get_apu_log_data_ptr=Module["_get_apu_log_data_ptr"]=wasmExports["pa"];_reset_apu_log=Module["_reset_apu_log"]=wasmExports["qa"];memory=wasmMemory=wasmExports["d"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={c:_emscripten_resize_heap,b:_exit,a:_fd_write};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run(); -;return Module}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=Binjgb;module.exports.default=Binjgb}else if(typeof define==="function"&&define["amd"])define([],()=>Binjgb); + +var Binjgb = (() => { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + + return ( +function(Binjgb) { + Binjgb = Binjgb || {}; + +var Module=typeof Binjgb!="undefined"?Binjgb:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=(url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText});if(ENVIRONMENT_IS_WORKER){readBinary=(url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)})}readAsync=((url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=(()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()});xhr.onerror=onerror;xhr.send(null)})}setWindowTitle=(title=>document.title=title)}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;var runtimeKeepaliveCounter=0;function keepRuntimeAlive(){return noExitRuntime||runtimeKeepaliveCounter>0}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){{if(Module["onAbort"]){Module["onAbort"](what)}}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}var wasmBinaryFile;wasmBinaryFile="binjgb.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["g"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["O"];addOnInit(Module["asm"]["h"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(wasmBinaryFile)&&typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func=="number"){if(callback.arg===undefined){getWasmTableEntry(func)()}else{getWasmTableEntry(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var wasmTableMirror=[];function getWasmTableEntry(funcPtr){var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function abortOnCannotGrowMemory(requestedSize){abort("OOM")}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;abortOnCannotGrowMemory(requestedSize)}function _exit(status){exit(status)}var SYSCALLS={buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAP32[iov+4>>2];iov+=8;for(var j=0;j>2]=num;return 0}var asmLibraryArg={"f":_emscripten_memcpy_big,"d":_emscripten_resize_heap,"b":_exit,"e":_fd_close,"c":_fd_seek,"a":_fd_write};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["h"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["i"]).apply(null,arguments)};var _file_data_delete=Module["_file_data_delete"]=function(){return(_file_data_delete=Module["_file_data_delete"]=Module["asm"]["j"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["k"]).apply(null,arguments)};var _emulator_set_builtin_palette=Module["_emulator_set_builtin_palette"]=function(){return(_emulator_set_builtin_palette=Module["_emulator_set_builtin_palette"]=Module["asm"]["l"]).apply(null,arguments)};var _emulator_was_ext_ram_updated=Module["_emulator_was_ext_ram_updated"]=function(){return(_emulator_was_ext_ram_updated=Module["_emulator_was_ext_ram_updated"]=Module["asm"]["m"]).apply(null,arguments)};var _emulator_read_state=Module["_emulator_read_state"]=function(){return(_emulator_read_state=Module["_emulator_read_state"]=Module["asm"]["n"]).apply(null,arguments)};var _emulator_write_state=Module["_emulator_write_state"]=function(){return(_emulator_write_state=Module["_emulator_write_state"]=Module["asm"]["o"]).apply(null,arguments)};var _emulator_read_ext_ram=Module["_emulator_read_ext_ram"]=function(){return(_emulator_read_ext_ram=Module["_emulator_read_ext_ram"]=Module["asm"]["p"]).apply(null,arguments)};var _emulator_write_ext_ram=Module["_emulator_write_ext_ram"]=function(){return(_emulator_write_ext_ram=Module["_emulator_write_ext_ram"]=Module["asm"]["q"]).apply(null,arguments)};var _emulator_delete=Module["_emulator_delete"]=function(){return(_emulator_delete=Module["_emulator_delete"]=Module["asm"]["r"]).apply(null,arguments)};var _emulator_queue_ps2_scan_code=Module["_emulator_queue_ps2_scan_code"]=function(){return(_emulator_queue_ps2_scan_code=Module["_emulator_queue_ps2_scan_code"]=Module["asm"]["s"]).apply(null,arguments)};var _emulator_clear_ps2_queue=Module["_emulator_clear_ps2_queue"]=function(){return(_emulator_clear_ps2_queue=Module["_emulator_clear_ps2_queue"]=Module["asm"]["t"]).apply(null,arguments)};var _emulator_set_ps2_keyboard_connected=Module["_emulator_set_ps2_keyboard_connected"]=function(){return(_emulator_set_ps2_keyboard_connected=Module["_emulator_set_ps2_keyboard_connected"]=Module["asm"]["u"]).apply(null,arguments)};var _emulator_get_ps2_keyboard_connected=Module["_emulator_get_ps2_keyboard_connected"]=function(){return(_emulator_get_ps2_keyboard_connected=Module["_emulator_get_ps2_keyboard_connected"]=Module["asm"]["v"]).apply(null,arguments)};var _emulator_get_PC=Module["_emulator_get_PC"]=function(){return(_emulator_get_PC=Module["_emulator_get_PC"]=Module["asm"]["w"]).apply(null,arguments)};var _emulator_get_A=Module["_emulator_get_A"]=function(){return(_emulator_get_A=Module["_emulator_get_A"]=Module["asm"]["x"]).apply(null,arguments)};var _emulator_get_BC=Module["_emulator_get_BC"]=function(){return(_emulator_get_BC=Module["_emulator_get_BC"]=Module["asm"]["y"]).apply(null,arguments)};var _emulator_get_DE=Module["_emulator_get_DE"]=function(){return(_emulator_get_DE=Module["_emulator_get_DE"]=Module["asm"]["z"]).apply(null,arguments)};var _emulator_get_HL=Module["_emulator_get_HL"]=function(){return(_emulator_get_HL=Module["_emulator_get_HL"]=Module["asm"]["A"]).apply(null,arguments)};var _emulator_get_F=Module["_emulator_get_F"]=function(){return(_emulator_get_F=Module["_emulator_get_F"]=Module["asm"]["B"]).apply(null,arguments)};var _emulator_get_SP=Module["_emulator_get_SP"]=function(){return(_emulator_get_SP=Module["_emulator_get_SP"]=Module["asm"]["C"]).apply(null,arguments)};var _emulator_set_PC=Module["_emulator_set_PC"]=function(){return(_emulator_set_PC=Module["_emulator_set_PC"]=Module["asm"]["D"]).apply(null,arguments)};var _emulator_get_wram_ptr=Module["_emulator_get_wram_ptr"]=function(){return(_emulator_get_wram_ptr=Module["_emulator_get_wram_ptr"]=Module["asm"]["E"]).apply(null,arguments)};var _emulator_get_hram_ptr=Module["_emulator_get_hram_ptr"]=function(){return(_emulator_get_hram_ptr=Module["_emulator_get_hram_ptr"]=Module["asm"]["F"]).apply(null,arguments)};var _emulator_read_mem=Module["_emulator_read_mem"]=function(){return(_emulator_read_mem=Module["_emulator_read_mem"]=Module["asm"]["G"]).apply(null,arguments)};var _emulator_write_mem=Module["_emulator_write_mem"]=function(){return(_emulator_write_mem=Module["_emulator_write_mem"]=Module["asm"]["H"]).apply(null,arguments)};var _emulator_set_breakpoint=Module["_emulator_set_breakpoint"]=function(){return(_emulator_set_breakpoint=Module["_emulator_set_breakpoint"]=Module["asm"]["I"]).apply(null,arguments)};var _emulator_clear_breakpoints=Module["_emulator_clear_breakpoints"]=function(){return(_emulator_clear_breakpoints=Module["_emulator_clear_breakpoints"]=Module["asm"]["J"]).apply(null,arguments)};var _emulator_render_vram=Module["_emulator_render_vram"]=function(){return(_emulator_render_vram=Module["_emulator_render_vram"]=Module["asm"]["K"]).apply(null,arguments)};var _emulator_render_background=Module["_emulator_render_background"]=function(){return(_emulator_render_background=Module["_emulator_render_background"]=Module["asm"]["L"]).apply(null,arguments)};var _emulator_get_banked_PC=Module["_emulator_get_banked_PC"]=function(){return(_emulator_get_banked_PC=Module["_emulator_get_banked_PC"]=Module["asm"]["M"]).apply(null,arguments)};var _set_audio_channel_mute=Module["_set_audio_channel_mute"]=function(){return(_set_audio_channel_mute=Module["_set_audio_channel_mute"]=Module["asm"]["N"]).apply(null,arguments)};var _joypad_new=Module["_joypad_new"]=function(){return(_joypad_new=Module["_joypad_new"]=Module["asm"]["P"]).apply(null,arguments)};var _joypad_delete=Module["_joypad_delete"]=function(){return(_joypad_delete=Module["_joypad_delete"]=Module["asm"]["Q"]).apply(null,arguments)};var _rewind_append=Module["_rewind_append"]=function(){return(_rewind_append=Module["_rewind_append"]=Module["asm"]["R"]).apply(null,arguments)};var _rewind_delete=Module["_rewind_delete"]=function(){return(_rewind_delete=Module["_rewind_delete"]=Module["asm"]["S"]).apply(null,arguments)};var _emulator_new_simple=Module["_emulator_new_simple"]=function(){return(_emulator_new_simple=Module["_emulator_new_simple"]=Module["asm"]["T"]).apply(null,arguments)};var _emulator_get_ticks_f64=Module["_emulator_get_ticks_f64"]=function(){return(_emulator_get_ticks_f64=Module["_emulator_get_ticks_f64"]=Module["asm"]["U"]).apply(null,arguments)};var _emulator_run_until_f64=Module["_emulator_run_until_f64"]=function(){return(_emulator_run_until_f64=Module["_emulator_run_until_f64"]=Module["asm"]["V"]).apply(null,arguments)};var _rewind_get_newest_ticks_f64=Module["_rewind_get_newest_ticks_f64"]=function(){return(_rewind_get_newest_ticks_f64=Module["_rewind_get_newest_ticks_f64"]=Module["asm"]["W"]).apply(null,arguments)};var _rewind_get_oldest_ticks_f64=Module["_rewind_get_oldest_ticks_f64"]=function(){return(_rewind_get_oldest_ticks_f64=Module["_rewind_get_oldest_ticks_f64"]=Module["asm"]["X"]).apply(null,arguments)};var _emulator_set_default_joypad_callback=Module["_emulator_set_default_joypad_callback"]=function(){return(_emulator_set_default_joypad_callback=Module["_emulator_set_default_joypad_callback"]=Module["asm"]["Y"]).apply(null,arguments)};var _emulator_set_bw_palette_simple=Module["_emulator_set_bw_palette_simple"]=function(){return(_emulator_set_bw_palette_simple=Module["_emulator_set_bw_palette_simple"]=Module["asm"]["Z"]).apply(null,arguments)};var _rewind_new_simple=Module["_rewind_new_simple"]=function(){return(_rewind_new_simple=Module["_rewind_new_simple"]=Module["asm"]["_"]).apply(null,arguments)};var _rewind_begin=Module["_rewind_begin"]=function(){return(_rewind_begin=Module["_rewind_begin"]=Module["asm"]["$"]).apply(null,arguments)};var _emulator_set_rewind_joypad_callback=Module["_emulator_set_rewind_joypad_callback"]=function(){return(_emulator_set_rewind_joypad_callback=Module["_emulator_set_rewind_joypad_callback"]=Module["asm"]["aa"]).apply(null,arguments)};var _rewind_to_ticks_wrapper=Module["_rewind_to_ticks_wrapper"]=function(){return(_rewind_to_ticks_wrapper=Module["_rewind_to_ticks_wrapper"]=Module["asm"]["ba"]).apply(null,arguments)};var _rewind_end=Module["_rewind_end"]=function(){return(_rewind_end=Module["_rewind_end"]=Module["asm"]["ca"]).apply(null,arguments)};var _set_joyp_up=Module["_set_joyp_up"]=function(){return(_set_joyp_up=Module["_set_joyp_up"]=Module["asm"]["da"]).apply(null,arguments)};var _set_joyp_down=Module["_set_joyp_down"]=function(){return(_set_joyp_down=Module["_set_joyp_down"]=Module["asm"]["ea"]).apply(null,arguments)};var _set_joyp_left=Module["_set_joyp_left"]=function(){return(_set_joyp_left=Module["_set_joyp_left"]=Module["asm"]["fa"]).apply(null,arguments)};var _set_joyp_right=Module["_set_joyp_right"]=function(){return(_set_joyp_right=Module["_set_joyp_right"]=Module["asm"]["ga"]).apply(null,arguments)};var _set_joyp_B=Module["_set_joyp_B"]=function(){return(_set_joyp_B=Module["_set_joyp_B"]=Module["asm"]["ha"]).apply(null,arguments)};var _set_joyp_A=Module["_set_joyp_A"]=function(){return(_set_joyp_A=Module["_set_joyp_A"]=Module["asm"]["ia"]).apply(null,arguments)};var _set_joyp_start=Module["_set_joyp_start"]=function(){return(_set_joyp_start=Module["_set_joyp_start"]=Module["asm"]["ja"]).apply(null,arguments)};var _set_joyp_select=Module["_set_joyp_select"]=function(){return(_set_joyp_select=Module["_set_joyp_select"]=Module["asm"]["ka"]).apply(null,arguments)};var _get_frame_buffer_ptr=Module["_get_frame_buffer_ptr"]=function(){return(_get_frame_buffer_ptr=Module["_get_frame_buffer_ptr"]=Module["asm"]["la"]).apply(null,arguments)};var _get_frame_buffer_size=Module["_get_frame_buffer_size"]=function(){return(_get_frame_buffer_size=Module["_get_frame_buffer_size"]=Module["asm"]["ma"]).apply(null,arguments)};var _get_sgb_frame_buffer_ptr=Module["_get_sgb_frame_buffer_ptr"]=function(){return(_get_sgb_frame_buffer_ptr=Module["_get_sgb_frame_buffer_ptr"]=Module["asm"]["na"]).apply(null,arguments)};var _get_sgb_frame_buffer_size=Module["_get_sgb_frame_buffer_size"]=function(){return(_get_sgb_frame_buffer_size=Module["_get_sgb_frame_buffer_size"]=Module["asm"]["oa"]).apply(null,arguments)};var _get_audio_buffer_ptr=Module["_get_audio_buffer_ptr"]=function(){return(_get_audio_buffer_ptr=Module["_get_audio_buffer_ptr"]=Module["asm"]["pa"]).apply(null,arguments)};var _get_audio_buffer_capacity=Module["_get_audio_buffer_capacity"]=function(){return(_get_audio_buffer_capacity=Module["_get_audio_buffer_capacity"]=Module["asm"]["qa"]).apply(null,arguments)};var _ext_ram_file_data_new=Module["_ext_ram_file_data_new"]=function(){return(_ext_ram_file_data_new=Module["_ext_ram_file_data_new"]=Module["asm"]["ra"]).apply(null,arguments)};var _state_file_data_new=Module["_state_file_data_new"]=function(){return(_state_file_data_new=Module["_state_file_data_new"]=Module["asm"]["sa"]).apply(null,arguments)};var _get_file_data_ptr=Module["_get_file_data_ptr"]=function(){return(_get_file_data_ptr=Module["_get_file_data_ptr"]=Module["asm"]["ta"]).apply(null,arguments)};var _get_file_data_size=Module["_get_file_data_size"]=function(){return(_get_file_data_size=Module["_get_file_data_size"]=Module["asm"]["ua"]).apply(null,arguments)};var _set_log_apu_writes=Module["_set_log_apu_writes"]=function(){return(_set_log_apu_writes=Module["_set_log_apu_writes"]=Module["asm"]["va"]).apply(null,arguments)};var _get_apu_log_data_size=Module["_get_apu_log_data_size"]=function(){return(_get_apu_log_data_size=Module["_get_apu_log_data_size"]=Module["asm"]["wa"]).apply(null,arguments)};var _get_apu_log_data_ptr=Module["_get_apu_log_data_ptr"]=function(){return(_get_apu_log_data_ptr=Module["_get_apu_log_data_ptr"]=Module["asm"]["xa"]).apply(null,arguments)};var _reset_apu_log=Module["_reset_apu_log"]=function(){return(_reset_apu_log=Module["_reset_apu_log"]=Module["asm"]["ya"]).apply(null,arguments)};var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;function exit(status,implicit){EXITSTATUS=status;if(keepRuntimeAlive()){}else{exitRuntime()}procExit(status)}function procExit(code){EXITSTATUS=code;if(!keepRuntimeAlive()){if(Module["onExit"])Module["onExit"](code);ABORT=true}quit_(code,new ExitStatus(code))}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run(); + + + return Binjgb.ready +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') + module.exports = Binjgb; +else if (typeof define === 'function' && define['amd']) + define([], function() { return Binjgb; }); +else if (typeof exports === 'object') + exports["Binjgb"] = Binjgb; diff --git a/docs/binjgb.wasm b/docs/binjgb.wasm index e73aa4e..7b73b77 100644 Binary files a/docs/binjgb.wasm and b/docs/binjgb.wasm differ diff --git a/docs/demo.js b/docs/demo.js index 344492a..621c696 100644 --- a/docs/demo.js +++ b/docs/demo.js @@ -37,6 +37,7 @@ const $ = document.querySelector.bind(document); let emulator = null; const binjgbPromise = Binjgb(); +const keyboardConfigPromise = BinjgbKeyboard.loadConfig('binjgb.ini'); const dbPromise = idb.open('db', 1, upgradeDb => { const objectStore = upgradeDb.createObjectStore('games', {keyPath : 'sha1'}); @@ -201,7 +202,7 @@ let vm = new Vue({ this.files.show = false; this.loadedFile = file; this.needsReload = false; - Emulator.start(await binjgbPromise, romBuffer, extRamBuffer); + Emulator.start(await binjgbPromise, romBuffer, extRamBuffer, await keyboardConfigPromise); emulator.setBuiltinPalette(this.pal); }, deleteFile: async function(file) { @@ -310,6 +311,7 @@ let vm = new Vue({ toggleOpenDialog: function() { this.files.show = !this.files.show; if (this.files.show) { + if (emulator) emulator.keyboard.releaseAll(); this.paused = true; } }, @@ -368,9 +370,9 @@ function makeWasmBuffer(module, ptr, size) { } class Emulator { - static start(module, romBuffer, extRamBuffer) { + static start(module, romBuffer, extRamBuffer, keyboardConfig) { Emulator.stop(); - emulator = new Emulator(module, romBuffer, extRamBuffer); + emulator = new Emulator(module, romBuffer, extRamBuffer, keyboardConfig); emulator.run(); } @@ -381,7 +383,7 @@ class Emulator { } } - constructor(module, romBuffer, extRamBuffer) { + constructor(module, romBuffer, extRamBuffer, keyboardConfig) { this.module = module; // Align size up to 32k. const size = (romBuffer.byteLength + 0x7fff) & ~0x7fff; @@ -396,7 +398,8 @@ class Emulator { throw new Error('Invalid ROM.'); } - this.gamepad = new Gamepad(module, this.e); + this.joypad = new BinjgbJoypad(module, this.e); + this.gamepad = new Gamepad(this.joypad); this.audio = new Audio(module, this.e); this.video = new Video(module, this.e, $('canvas')); this.rewind = new Rewind(module, this.e); @@ -411,7 +414,7 @@ class Emulator { this.loadExtRam(extRamBuffer); } - this.bindKeys(); + this.bindKeys(keyboardConfig); this.gamepad.init(); } @@ -568,10 +571,12 @@ class Emulator { } runUntil(untilTicks) { + this.keyboard.flush(); let next60hzTicks = this.getNext60HzTicks(this.ticks); while (true) { const event = this.module._emulator_run_until_f64( this.e, Math.min(untilTicks, next60hzTicks)); + this.keyboard.flush(); if (event & EVENT_NEW_FRAME) { this.rewind.pushBuffer(); this.video.uploadTexture(); @@ -613,45 +618,36 @@ class Emulator { this.video.renderTexture(); } - bindKeys() { - this.keyFuncs = { - 'ArrowDown': this.module._set_joyp_down.bind(null, this.e), - 'ArrowLeft': this.module._set_joyp_left.bind(null, this.e), - 'ArrowRight': this.module._set_joyp_right.bind(null, this.e), - 'ArrowUp': this.module._set_joyp_up.bind(null, this.e), - 'KeyZ': this.module._set_joyp_B.bind(null, this.e), - 'KeyX': this.module._set_joyp_A.bind(null, this.e), - 'Enter': this.module._set_joyp_start.bind(null, this.e), - 'Tab': this.module._set_joyp_select.bind(null, this.e), - 'Backspace': this.keyRewind.bind(this), - 'Space': this.keyPause.bind(this), - 'F6': vm.saveState.bind(vm), - 'F9': vm.loadState.bind(vm), - }; - this.boundKeyDown = this.keyDown.bind(this); - this.boundKeyUp = this.keyUp.bind(this); - - window.addEventListener('keydown', this.boundKeyDown); - window.addEventListener('keyup', this.boundKeyUp); - } - - unbindKeys() { - window.removeEventListener('keydown', this.boundKeyDown); - window.removeEventListener('keyup', this.boundKeyUp); - } - - keyDown(event) { - if (event.code in this.keyFuncs) { - this.keyFuncs[event.code](true); - event.preventDefault(); + bindKeys(config) { + const handlers = {}; + for (const [name, button, key] of [ + ['up', 'up', 'UP'], ['down', 'down', 'DOWN'], + ['left', 'left', 'LEFT'], ['right', 'right', 'RIGHT'], + ['a', 'A', 'X'], ['b', 'B', 'Z'], + ['start', 'start', 'RETURN'], ['select', 'select', 'TAB'], + ]) { + handlers[`joypad-${name}`] = { + keys: key, held: true, + callback: down => this.joypad.set(button, 'keyboard', down), + }; } + Object.assign(handlers, { + 'shortcut-rewind': {keys: 'BACKSPACE', held: true, callback: this.keyRewind.bind(this)}, + 'shortcut-pause': {keys: 'SPACE', callback: this.keyPause.bind(this)}, + 'shortcut-save-state': {keys: 'F6', callback: vm.saveState.bind(vm)}, + 'shortcut-load-state': {keys: 'F9', callback: vm.loadState.bind(vm)}, + 'shortcut-fullscreen': {keys: '', callback: () => { + if (document.fullscreenElement) document.exitFullscreen(); + else vm.toggleFullscreen(); + }}, + }); + this.keyboard = new BinjgbKeyboard(this.module, this.e, config, handlers, { + isCaptured: () => vm.files.show, + }); } - keyUp(event) { - if (event.code in this.keyFuncs) { - this.keyFuncs[event.code](false); - event.preventDefault(); - } + unbindKeys() { + this.keyboard.destroy(); } keyRewind(isKeyDown) { @@ -672,33 +668,27 @@ class Emulator { } class Gamepad { - constructor(module, e) { - this.module = module; - this.e = e; + constructor(joypad) { + this.joypad = joypad; } // Load a key map for gamepad-to-gameboy buttons bindKeys(strMapping) { + const bind = (gb_key, gp_button, type = 'button') => { + const button = gb_key === 'a' || gb_key === 'b' ? gb_key.toUpperCase() : gb_key; + return { + gb_key, gp_button, type, + gp_bind: down => this.joypad.set(button, `gamepad:${type}:${gp_button}`, down), + }; + }; this.GAMEPAD_KEYMAP_STANDARD = [ - {gb_key: "b", gp_button: 0, type: "button", gp_bind:this.module._set_joyp_B.bind(null, this.e) }, - {gb_key: "a", gp_button: 1, type: "button", gp_bind:this.module._set_joyp_A.bind(null, this.e) }, - {gb_key: "select", gp_button: 8, type: "button", gp_bind:this.module._set_joyp_select.bind(null, this.e) }, - {gb_key: "start", gp_button: 9, type: "button", gp_bind:this.module._set_joyp_start.bind(null, this.e) }, - {gb_key: "up", gp_button: 12, type: "button", gp_bind:this.module._set_joyp_up.bind(null, this.e) }, - {gb_key: "down", gp_button: 13, type: "button", gp_bind:this.module._set_joyp_down.bind(null, this.e) }, - {gb_key: "left", gp_button: 14, type: "button", gp_bind:this.module._set_joyp_left.bind(null, this.e) }, - {gb_key: "right", gp_button: 15, type: "button", gp_bind:this.module._set_joyp_right.bind(null, this.e) } + bind('b', 0), bind('a', 1), bind('select', 8), bind('start', 9), + bind('up', 12), bind('down', 13), bind('left', 14), bind('right', 15), ]; - this.GAMEPAD_KEYMAP_DEFAULT = [ - {gb_key: "a", gp_button: 0, type: "button", gp_bind:this.module._set_joyp_A.bind(null, this.e) }, - {gb_key: "b", gp_button: 1, type: "button", gp_bind:this.module._set_joyp_B.bind(null, this.e) }, - {gb_key: "select", gp_button: 2, type: "button", gp_bind:this.module._set_joyp_select.bind(null, this.e) }, - {gb_key: "start", gp_button: 3, type: "button", gp_bind:this.module._set_joyp_start.bind(null, this.e) }, - {gb_key: "up", gp_button: 2, type: "axis", gp_bind:this.module._set_joyp_up.bind(null, this.e) }, - {gb_key: "down", gp_button: 3, type: "axis", gp_bind:this.module._set_joyp_down.bind(null, this.e) }, - {gb_key: "left", gp_button: 0, type: "axis", gp_bind:this.module._set_joyp_left.bind(null, this.e) }, - {gb_key: "right", gp_button: 1, type: "axis", gp_bind:this.module._set_joyp_right.bind(null, this.e) } + bind('a', 0), bind('b', 1), bind('select', 2), bind('start', 3), + bind('up', 2, 'axis'), bind('down', 3, 'axis'), + bind('left', 0, 'axis'), bind('right', 1, 'axis'), ]; // Try to use the w3c "standard" gamepad mapping if available @@ -821,6 +811,7 @@ class Gamepad { } releaseGamepad() { + this.joypad.clearSource('gamepad:'); // Stop polling the gamepad for input if (this.gp.timerID !== undefined) { clearInterval(this.gp.timerID); diff --git a/docs/index.html b/docs/index.html index d42bfab..ea6203c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -293,5 +293,6 @@ + diff --git a/docs/keyboard.js b/docs/keyboard.js new file mode 100644 index 0000000..256a74d --- /dev/null +++ b/docs/keyboard.js @@ -0,0 +1,327 @@ +/* Shared native-style keyboard configuration for the browser frontends. */ +"use strict"; + +// Physical key name: [KeyboardEvent.code, PS/2 set 2 code, extended prefix]. +const BINJGB_KEY_CODES = { + A: ['KeyA', 0x1c, false], + B: ['KeyB', 0x32, false], + C: ['KeyC', 0x21, false], + D: ['KeyD', 0x23, false], + E: ['KeyE', 0x24, false], + F: ['KeyF', 0x2b, false], + G: ['KeyG', 0x34, false], + H: ['KeyH', 0x33, false], + I: ['KeyI', 0x43, false], + J: ['KeyJ', 0x3b, false], + K: ['KeyK', 0x42, false], + L: ['KeyL', 0x4b, false], + M: ['KeyM', 0x3a, false], + N: ['KeyN', 0x31, false], + O: ['KeyO', 0x44, false], + P: ['KeyP', 0x4d, false], + Q: ['KeyQ', 0x15, false], + R: ['KeyR', 0x2d, false], + S: ['KeyS', 0x1b, false], + T: ['KeyT', 0x2c, false], + U: ['KeyU', 0x3c, false], + V: ['KeyV', 0x2a, false], + W: ['KeyW', 0x1d, false], + X: ['KeyX', 0x22, false], + Y: ['KeyY', 0x35, false], + Z: ['KeyZ', 0x1a, false], + 1: ['Digit1', 0x16, false], + 2: ['Digit2', 0x1e, false], + 3: ['Digit3', 0x26, false], + 4: ['Digit4', 0x25, false], + 5: ['Digit5', 0x2e, false], + 6: ['Digit6', 0x36, false], + 7: ['Digit7', 0x3d, false], + 8: ['Digit8', 0x3e, false], + 9: ['Digit9', 0x46, false], + 0: ['Digit0', 0x45, false], + ESCAPE: ['Escape', 0x76, false], + GRAVE: ['Backquote', 0x0e, false], + MINUS: ['Minus', 0x4e, false], + EQUALS: ['Equal', 0x55, false], + BACKSPACE: ['Backspace', 0x66, false], + TAB: ['Tab', 0x0d, false], + LEFTBRACKET: ['BracketLeft', 0x54, false], + RIGHTBRACKET: ['BracketRight', 0x5b, false], + BACKSLASH: ['Backslash', 0x5d, false], + SEMICOLON: ['Semicolon', 0x4c, false], + APOSTROPHE: ['Quote', 0x52, false], + RETURN: ['Enter', 0x5a, false], + LSHIFT: ['ShiftLeft', 0x12, false], + RSHIFT: ['ShiftRight', 0x59, false], + LCTRL: ['ControlLeft', 0x14, false], + LALT: ['AltLeft', 0x11, false], + SPACE: ['Space', 0x29, false], + COMMA: ['Comma', 0x41, false], + PERIOD: ['Period', 0x49, false], + SLASH: ['Slash', 0x4a, false], + F1: ['F1', 0x05, false], + F2: ['F2', 0x06, false], + F3: ['F3', 0x04, false], + F4: ['F4', 0x0c, false], + F5: ['F5', 0x03, false], + F6: ['F6', 0x0b, false], + F7: ['F7', 0x83, false], + F8: ['F8', 0x0a, false], + F9: ['F9', 0x01, false], + F10: ['F10', 0x09, false], + F11: ['F11', 0x78, false], + F12: ['F12', 0x07, false], + CAPSLOCK: ['CapsLock', 0x58, false], + SCROLLLOCK: ['ScrollLock', 0x7e, false], + NUMLOCKCLEAR: ['NumLock', 0x77, false], + KP_0: ['Numpad0', 0x70, false], + KP_1: ['Numpad1', 0x69, false], + KP_2: ['Numpad2', 0x72, false], + KP_3: ['Numpad3', 0x7a, false], + KP_4: ['Numpad4', 0x6b, false], + KP_5: ['Numpad5', 0x73, false], + KP_6: ['Numpad6', 0x74, false], + KP_7: ['Numpad7', 0x6c, false], + KP_8: ['Numpad8', 0x75, false], + KP_9: ['Numpad9', 0x7d, false], + KP_PERIOD: ['NumpadDecimal', 0x71, false], + KP_MULTIPLY: ['NumpadMultiply', 0x7c, false], + KP_MINUS: ['NumpadSubtract', 0x7b, false], + KP_PLUS: ['NumpadAdd', 0x79, false], + UP: ['ArrowUp', 0x75, true], + DOWN: ['ArrowDown', 0x72, true], + LEFT: ['ArrowLeft', 0x6b, true], + RIGHT: ['ArrowRight', 0x74, true], + KP_DIVIDE: ['NumpadDivide', 0x4a, true], + KP_ENTER: ['NumpadEnter', 0x5a, true], + INSERT: ['Insert', 0x70, true], + DELETE: ['Delete', 0x71, true], + HOME: ['Home', 0x6c, true], + END: ['End', 0x69, true], + PAGEUP: ['PageUp', 0x7d, true], + PAGEDOWN: ['PageDown', 0x7a, true], + RCTRL: ['ControlRight', 0x14, true], + RALT: ['AltRight', 0x11, true], + LGUI: ['MetaLeft', 0x1f, true], + RGUI: ['MetaRight', 0x27, true], + APPLICATION: ['ContextMenu', 0x2f, true], +}; + +class BinjgbJoypad { + constructor(module, emulator) { + this.module = module; + this.emulator = emulator; + this.sources = new Map(); + // The WASM wrapper stores joypad state globally across ROM instances. + for (const button of ['up', 'down', 'left', 'right', 'A', 'B', 'start', 'select']) { + this.module[`_set_joyp_${button}`](this.emulator, false); + } + } + + set(button, source, down) { + if (!this.sources.has(button)) this.sources.set(button, new Set()); + const sources = this.sources.get(button); + const wasDown = sources.size > 0; + if (down) sources.add(source); + else sources.delete(source); + if (wasDown !== (sources.size > 0)) { + this.module[`_set_joyp_${button}`](this.emulator, sources.size > 0); + } + } + + clearSource(prefix) { + for (const [button, sources] of this.sources) { + for (const source of [...sources]) { + if (source.startsWith(prefix)) this.set(button, source, false); + } + } + } +} + +class BinjgbKeyboard { + static parseConfig(text) { + const entries = []; + for (const [index, line] of text.split(/\r?\n/).entries()) { + const trimmed = line.trim(); + if (!trimmed || /^[#;]/.test(trimmed)) continue; + const equals = trimmed.indexOf('='); + if (equals < 0) throw new Error(`Invalid binjgb.ini line ${index + 1}`); + const name = trimmed.slice(0, equals).trim(); + const value = trimmed.slice(equals + 1).trim(); + // Other native emulator settings do not configure the browser frontend. + if (['joypad', 'shortcuts', 'ps2-keyboard', 'ps2-keys', + 'capture-browser-shortcuts'].includes(name) || + /^(joypad|shortcut)-/.test(name)) entries.push([name, value]); + } + return entries; + } + + static async loadConfig(url) { + const response = await fetch(url, {cache: 'no-cache'}); + if (response.status === 404) return []; + if (!response.ok) throw new Error(`Could not load ${url}: ${response.status}`); + return BinjgbKeyboard.parseConfig(await response.text()); + } + + constructor(module, emulator, config = [], handlers, options = {}) { + this.module = module; + this.emulator = emulator; + this.options = options; + this.held = new Map(); + this.counts = new Map(); + this.pending = []; + this.ps2Connected = true; + this.captureBrowserShortcuts = false; + this.ps2Keys = this.parseKeys('all', true); + this.actions = new Map(Object.entries(handlers).map(([name, action]) => [ + name, {...action, keys: this.parseKeys(action.keys), defaultKeys: action.keys}, + ])); + + for (const [name, value] of config) { + if (name === 'ps2-keyboard') this.ps2Connected = this.parseBool(value); + else if (name === 'capture-browser-shortcuts') { + this.captureBrowserShortcuts = this.parseBool(value); + } else if (name === 'ps2-keys') this.ps2Keys = this.parseKeys(value, true); + else if (name === 'joypad' || name === 'shortcuts') { + const mode = value.toLowerCase(); + if (!['none', 'default'].includes(mode)) throw new Error(`Invalid ${name}: ${value}`); + const prefix = name === 'joypad' ? 'joypad-' : 'shortcut-'; + for (const [actionName, action] of this.actions) { + if (actionName.startsWith(prefix)) { + action.keys = this.parseKeys(mode === 'none' ? '' : action.defaultKeys); + } + } + } else { + const action = this.actions.get(name); + if (!action) throw new Error(`Unsupported browser input setting: ${name}`); + action.keys = this.parseKeys(value); + } + } + + this.routes = new Map(); + for (const prefix of ['shortcut-', 'joypad-']) { + const group = new Map(); + for (const [name, action] of this.actions) { + if (!name.startsWith(prefix)) continue; + for (const key of action.keys) { + if (group.has(key)) throw new Error(`Conflicting input bindings: ${name} and ${group.get(key)}`); + group.set(key, name); + if (!this.routes.has(key)) this.routes.set(key, {name, action}); + } + } + } + this.keyNames = new Map(Object.entries(BINJGB_KEY_CODES).map(([name, [code]]) => [code, name])); + this.window = options.window || window; + this.document = options.document || document; + this.module._emulator_set_ps2_keyboard_connected(this.emulator, this.ps2Connected); + this.onKeyDown = event => this.keyDown(event); + this.onKeyUp = event => this.keyUp(event); + this.onBlur = () => this.releaseAll(); + this.onFocus = event => { if (this.isEditable(event.target)) this.releaseAll(); }; + this.onVisibility = () => { if (this.document.hidden) this.releaseAll(); }; + this.window.addEventListener('keydown', this.onKeyDown); + this.window.addEventListener('keyup', this.onKeyUp); + this.window.addEventListener('blur', this.onBlur); + this.document.addEventListener('focusin', this.onFocus); + this.document.addEventListener('visibilitychange', this.onVisibility); + } + + parseBool(value) { + if (value !== '0' && value !== '1') throw new Error(`Expected 0 or 1: ${value}`); + return value === '1'; + } + + parseKeys(value, allowAll = false) { + value = value.trim().toUpperCase(); + if (!value || value === 'NONE') return new Set(); + if (allowAll && value === 'ALL') return new Set(Object.keys(BINJGB_KEY_CODES)); + const keys = value.split(',').map(key => key.trim()); + for (const key of keys) { + if (!Object.hasOwn(BINJGB_KEY_CODES, key)) throw new Error(`Invalid keyboard key: ${key}`); + } + return new Set(keys); + } + + isEditable(target) { + return !!(target && (target.isContentEditable || target.closest && + target.closest('input, textarea, select, button, a[href], [contenteditable], [role="textbox"]'))); + } + + keyDown(event) { + if (event.defaultPrevented || event.isComposing || this.isEditable(event.target) || + this.options.isCaptured && this.options.isCaptured()) return; + // Leave browser/OS chords available unless the host explicitly opts in. + if (!this.captureBrowserShortcuts && (event.ctrlKey || event.metaKey || event.altKey)) { + this.releaseAll(); + return; + } + if (this.held.has(event.code)) { + event.preventDefault(); + return; + } + if (event.repeat) return; + const key = this.keyNames.get(event.code); + if (!key) return; + let route = this.routes.get(key); + if (!route && this.ps2Connected && this.ps2Keys.has(key)) route = {ps2: key}; + if (!route) return; + this.held.set(event.code, route); + event.preventDefault(); + if (this.options.onInput) this.options.onInput(); + if (route.ps2) this.sendScanCode(route.ps2, true); + else { + const count = this.counts.get(route.name) || 0; + this.counts.set(route.name, count + 1); + if (!count) route.action.callback(true); + } + } + + keyUp(event) { + if (!this.held.has(event.code)) return; + event.preventDefault(); + this.release(event.code); + } + + release(code) { + const route = this.held.get(code); + this.held.delete(code); + if (route.ps2) this.sendScanCode(route.ps2, false); + else { + const count = this.counts.get(route.name) - 1; + this.counts.set(route.name, count); + if (!count && route.action.held) route.action.callback(false); + } + } + + releaseAll() { + for (const code of [...this.held.keys()]) this.release(code); + } + + sendScanCode(key, down) { + const [, scan, extended] = BINJGB_KEY_CODES[key]; + if (extended) this.pending.push(0xe0); + if (!down) this.pending.push(0xf0); + this.pending.push(scan); + this.flush(); + } + + // The core queue is finite. Retry bytes in order as emulation advances, + // retaining prefixes and releases instead of dropping partial sequences. + flush() { + let sent = 0; + while (sent < this.pending.length && + this.module._emulator_queue_ps2_scan_code(this.emulator, this.pending[sent])) ++sent; + if (sent) this.pending.splice(0, sent); + } + + destroy() { + this.releaseAll(); + this.window.removeEventListener('keydown', this.onKeyDown); + this.window.removeEventListener('keyup', this.onKeyUp); + this.window.removeEventListener('blur', this.onBlur); + this.document.removeEventListener('focusin', this.onFocus); + this.document.removeEventListener('visibilitychange', this.onVisibility); + this.module._emulator_set_ps2_keyboard_connected(this.emulator, false); + this.pending.length = 0; + } +} diff --git a/docs/simple.html b/docs/simple.html index 2abae81..449b7f0 100644 --- a/docs/simple.html +++ b/docs/simple.html @@ -27,5 +27,6 @@
A
+ diff --git a/docs/simple.js b/docs/simple.js index ba463d7..8e7e0ab 100644 --- a/docs/simple.js +++ b/docs/simple.js @@ -73,6 +73,7 @@ const bEl = $('#controller_b'); const aEl = $('#controller_a'); const binjgbPromise = Binjgb(); +const keyboardConfigPromise = BinjgbKeyboard.loadConfig('binjgb.ini'); // Extract stuff from the vue.js implementation in demo.js. class VM { @@ -128,7 +129,7 @@ const vm = new VM(); let response = await fetch(ROM_FILENAME); let romBuffer = await response.arrayBuffer(); const extRam = new Uint8Array(JSON.parse(localStorage.getItem('extram'))); - Emulator.start(await binjgbPromise, romBuffer, extRam); + Emulator.start(await binjgbPromise, romBuffer, extRam, await keyboardConfigPromise); emulator.setBuiltinPalette(vm.palIdx); })(); @@ -139,9 +140,9 @@ function makeWasmBuffer(module, ptr, size) { } class Emulator { - static start(module, romBuffer, extRamBuffer) { + static start(module, romBuffer, extRamBuffer, keyboardConfig) { Emulator.stop(); - emulator = new Emulator(module, romBuffer, extRamBuffer); + emulator = new Emulator(module, romBuffer, extRamBuffer, keyboardConfig); emulator.run(); } @@ -152,7 +153,7 @@ class Emulator { } } - constructor(module, romBuffer, extRamBuffer) { + constructor(module, romBuffer, extRamBuffer, keyboardConfig) { this.module = module; // Align size up to 32k. const size = (romBuffer.byteLength + 0x7fff) & ~0x7fff; @@ -167,6 +168,7 @@ class Emulator { throw new Error('Invalid ROM.'); } + this.joypad = new BinjgbJoypad(module, this.e); this.audio = new Audio(module, this.e); this.video = new Video(module, this.e, $('canvas')); this.rewind = new Rewind(module, this.e); @@ -181,7 +183,7 @@ class Emulator { this.loadExtRam(extRamBuffer); } - this.bindKeys(); + this.bindKeys(keyboardConfig); this.bindTouch(); this.touchEnabled = 'ontouchstart' in document.documentElement; @@ -277,16 +279,14 @@ class Emulator { } get isRewinding() { - return ENABLE_REWIND && this.rewind.isRewinding; + return this.rewind.isRewinding; } beginRewind() { - if (!ENABLE_REWIND) { return; } this.rewind.beginRewind(); } rewindToTicks(ticks) { - if (!ENABLE_REWIND) { return; } if (this.rewind.rewindToTicks(ticks)) { this.runUntil(ticks); this.video.renderTexture(); @@ -294,7 +294,6 @@ class Emulator { } endRewind() { - if (!ENABLE_REWIND) { return; } this.rewind.endRewind(); this.lastRafSec = 0; this.leftoverTicks = 0; @@ -302,7 +301,6 @@ class Emulator { } set autoRewind(enabled) { - if (!ENABLE_REWIND) { return; } if (enabled) { this.rewindIntervalId = setInterval(() => { const oldest = this.rewind.oldestTicks; @@ -337,8 +335,10 @@ class Emulator { } runUntil(ticks) { + this.keyboard.flush(); while (true) { const event = this.module._emulator_run_until_f64(this.e, ticks); + this.keyboard.flush(); if (event & EVENT_NEW_FRAME) { this.rewind.pushBuffer(); this.video.uploadTexture(); @@ -500,56 +500,52 @@ class Emulator { this.updateOnscreenGamepad(); } - bindKeys() { - this.keyFuncs = { - 'ArrowDown': this.setJoypDown.bind(this), - 'ArrowLeft': this.setJoypLeft.bind(this), - 'ArrowRight': this.setJoypRight.bind(this), - 'ArrowUp': this.setJoypUp.bind(this), - 'KeyZ': this.setJoypB.bind(this), - 'KeyX': this.setJoypA.bind(this), - 'Enter': this.setJoypStart.bind(this), - 'Tab': this.setJoypSelect.bind(this), - 'Backspace': this.keyRewind.bind(this), - 'Space': this.keyPause.bind(this), - 'BracketLeft': this.keyPrevPalette.bind(this), - 'BracketRight': this.keyNextPalette.bind(this), - 'ShiftLeft': this.setFastForward.bind(this), - 'F6': this.saveState.bind(this), - 'F9': this.loadState.bind(this), - }; - this.boundKeyDown = this.keyDown.bind(this); - this.boundKeyUp = this.keyUp.bind(this); - - window.addEventListener('keydown', this.boundKeyDown); - window.addEventListener('keyup', this.boundKeyUp); - } - - unbindKeys() { - window.removeEventListener('keydown', this.boundKeyDown); - window.removeEventListener('keyup', this.boundKeyUp); - } - - keyDown(event) { - if (event.code in this.keyFuncs) { - if (this.touchEnabled) { - this.touchEnabled = false; - this.updateOnscreenGamepad(); - } - this.keyFuncs[event.code](true); - event.preventDefault(); + bindKeys(config) { + const handlers = {}; + for (const [name, button, key] of [ + ['up', 'up', 'UP'], ['down', 'down', 'DOWN'], + ['left', 'left', 'LEFT'], ['right', 'right', 'RIGHT'], + ['a', 'A', 'X'], ['b', 'B', 'Z'], + ['start', 'start', 'RETURN'], ['select', 'select', 'TAB'], + ]) { + handlers[`joypad-${name}`] = { + keys: key, held: true, + callback: down => this.joypad.set(button, 'keyboard', down), + }; } + Object.assign(handlers, { + 'shortcut-rewind': {keys: ENABLE_REWIND ? 'BACKSPACE' : '', held: true, + callback: this.keyRewind.bind(this)}, + 'shortcut-pause': {keys: ENABLE_PAUSE ? 'SPACE' : '', callback: this.keyPause.bind(this)}, + 'shortcut-palette-prev': {keys: ENABLE_SWITCH_PALETTES ? 'LEFTBRACKET' : '', + callback: this.keyPrevPalette.bind(this)}, + 'shortcut-palette-next': {keys: ENABLE_SWITCH_PALETTES ? 'RIGHTBRACKET' : '', + callback: this.keyNextPalette.bind(this)}, + 'shortcut-fast-forward': {keys: ENABLE_FAST_FORWARD ? 'LSHIFT' : '', held: true, + callback: this.setFastForward.bind(this)}, + 'shortcut-save-state': {keys: 'F6', callback: this.saveState.bind(this)}, + 'shortcut-load-state': {keys: 'F9', callback: this.loadState.bind(this)}, + 'shortcut-fullscreen': {keys: '', callback: () => { + if (document.fullscreenElement) document.exitFullscreen(); + else $('canvas').requestFullscreen(); + }}, + }); + this.keyboard = new BinjgbKeyboard(this.module, this.e, config, handlers, { + onInput: () => { + if (this.touchEnabled) { + this.touchEnabled = false; + this.updateOnscreenGamepad(); + this.joypad.clearSource('touch'); + } + }, + }); } - keyUp(event) { - if (event.code in this.keyFuncs) { - this.keyFuncs[event.code](false); - event.preventDefault(); - } + unbindKeys() { + this.keyboard.destroy(); } keyRewind(isKeyDown) { - if (!ENABLE_REWIND) { return; } if (this.isRewinding !== isKeyDown) { if (isKeyDown) { vm.paused = true; @@ -562,12 +558,10 @@ class Emulator { } keyPause(isKeyDown) { - if (!ENABLE_PAUSE) { return; } if (isKeyDown) vm.togglePause(); } keyPrevPalette(isKeyDown) { - if (!ENABLE_SWITCH_PALETTES) { return; } if (isKeyDown) { vm.palIdx = (vm.palIdx + PALETTES.length - 1) % PALETTES.length; emulator.setBuiltinPalette(vm.palIdx); @@ -575,7 +569,6 @@ class Emulator { } keyNextPalette(isKeyDown) { - if (!ENABLE_SWITCH_PALETTES) { return; } if (isKeyDown) { vm.palIdx = (vm.palIdx + 1) % PALETTES.length; emulator.setBuiltinPalette(vm.palIdx); @@ -583,18 +576,17 @@ class Emulator { } setFastForward(isKeyDown) { - if (!ENABLE_FAST_FORWARD) { return; } this.fastForward = isKeyDown; } - setJoypDown(set) { this.module._set_joyp_down(this.e, set); } - setJoypUp(set) { this.module._set_joyp_up(this.e, set); } - setJoypLeft(set) { this.module._set_joyp_left(this.e, set); } - setJoypRight(set) { this.module._set_joyp_right(this.e, set); } - setJoypSelect(set) { this.module._set_joyp_select(this.e, set); } - setJoypStart(set) { this.module._set_joyp_start(this.e, set); } - setJoypB(set) { this.module._set_joyp_B(this.e, set); } - setJoypA(set) { this.module._set_joyp_A(this.e, set); } + setJoypDown(set) { this.joypad.set('down', 'touch', set); } + setJoypUp(set) { this.joypad.set('up', 'touch', set); } + setJoypLeft(set) { this.joypad.set('left', 'touch', set); } + setJoypRight(set) { this.joypad.set('right', 'touch', set); } + setJoypSelect(set) { this.joypad.set('select', 'touch', set); } + setJoypStart(set) { this.joypad.set('start', 'touch', set); } + setJoypB(set) { this.joypad.set('B', 'touch', set); } + setJoypA(set) { this.joypad.set('A', 'touch', set); } } class Audio { diff --git a/src/binjgb.c b/src/binjgb.c index b4eddea..67c4c46 100644 --- a/src/binjgb.c +++ b/src/binjgb.c @@ -6,12 +6,14 @@ */ #include +#include #include #include #include #include "emulator.h" #include "host.h" +#include "host-input.h" #include "options.h" #define SAVE_EXTENSION ".sav" @@ -60,6 +62,8 @@ static u32 s_random_seed = 0xcabba6e5; static u32 s_builtin_palette; static Bool s_force_dmg; static Bool s_use_sgb_border; +static Bool s_ps2_keyboard = TRUE; +static HostInputConfig s_input; static u32 s_cgb_color_curve; static u32 s_render_scale = 4; @@ -318,7 +322,9 @@ static void usage(int argc, char** argv) { " 1: Sameboy (Emulate Hardware)\n" " 2: Gambatte/Gameboy Online\n" " --force-dmg force running as a DMG (original gameboy)\n" - " --sgb-border draw the super gameboy border\n", + " --sgb-border draw the super gameboy border\n" + " --no-ps2-keyboard don't send keys to an emulated PS/2 keyboard\n" + " on the serial port\n", argv[0]); } @@ -333,6 +339,7 @@ void parse_arguments(int argc, char** argv) { {'C', "cgb-color", 1}, {0, "force-dmg", 0}, {0, "sgb-border", 0}, + {0, "no-ps2-keyboard", 0}, }; struct OptionParser* parser = option_parser_new( @@ -391,6 +398,8 @@ void parse_arguments(int argc, char** argv) { s_force_dmg = TRUE; } else if (strcmp(result.option->long_name, "sgb-border") == 0) { s_use_sgb_border = TRUE; + } else if (strcmp(result.option->long_name, "no-ps2-keyboard") == 0) { + s_ps2_keyboard = FALSE; } else { abort(); } @@ -422,22 +431,31 @@ void parse_arguments(int argc, char** argv) { exit(1); } +static char* trim_ini_space(char* text) { + while (isspace((unsigned char)*text)) ++text; + char* end = text + strlen(text); + while (end > text && isspace((unsigned char)end[-1])) --end; + *end = 0; + return text; +} + void read_ini_file(void) { FILE* file = fopen("binjgb.ini", "r"); if (!file) { return; } while (1) { - char buffer[1024], *value, *equals, *newline; + char buffer[1024], *value, *equals; if (!fgets(buffer, sizeof(buffer), file)) { break; } - if (buffer[0] == '#' || buffer[0] == '\n') { + char* name = trim_ini_space(buffer); + if (!*name || *name == '#' || *name == ';') { continue; } - equals = strchr(buffer, '='); + equals = strchr(name, '='); if (!equals) { fprintf(stderr, "warning: bad ini line: %s\n", buffer); continue; @@ -445,37 +463,46 @@ void read_ini_file(void) { *equals = 0; value = equals + 1; - newline = strchr(value, '\n'); - if (newline) { - *newline = 0; + name = trim_ini_space(name); + value = trim_ini_space(value); + int input_result = host_input_parse(&s_input, name, value); + if (input_result != 0) { + if (input_result < 0) { + fprintf(stderr, "invalid input setting: %s=%s\n", name, value); + fclose(file); + exit(1); + } + continue; } - if (strcmp(buffer, "autoload") == 0) { + if (strcmp(name, "autoload") == 0) { s_rom_filename = xstrdup(value); - } else if (strcmp(buffer, "audio-frequency") == 0) { + } else if (strcmp(name, "audio-frequency") == 0) { s_audio_frequency = atoi(value); - } else if (strcmp(buffer, "audio-frames") == 0) { + } else if (strcmp(name, "audio-frames") == 0) { s_audio_frames = atoi(value); - } else if (strcmp(buffer, "builtin-palette") == 0) { + } else if (strcmp(name, "builtin-palette") == 0) { s_builtin_palette = atoi(value); - } else if (strcmp(buffer, "force-dmg") == 0) { + } else if (strcmp(name, "force-dmg") == 0) { s_force_dmg = atoi(value); - } else if (strcmp(buffer, "cgb-color") == 0) { + } else if (strcmp(name, "ps2-keyboard") == 0) { + s_ps2_keyboard = atoi(value); + } else if (strcmp(name, "cgb-color") == 0) { s_cgb_color_curve = atoi(value); - } else if (strcmp(buffer, "rewind-frames-per-base-state") == 0) { + } else if (strcmp(name, "rewind-frames-per-base-state") == 0) { s_rewind_frames_per_base_state = atoi(value); - } else if (strcmp(buffer, "rewind-buffer-capacity-megabytes") == 0) { + } else if (strcmp(name, "rewind-buffer-capacity-megabytes") == 0) { s_rewind_buffer_capacity_megabytes = atoi(value); - } else if (strcmp(buffer, "rewind-scale") == 0) { + } else if (strcmp(name, "rewind-scale") == 0) { s_rewind_scale = atof(value); - } else if (strcmp(buffer, "render-scale") == 0) { + } else if (strcmp(name, "render-scale") == 0) { s_render_scale = atoi(value); - } else if (strcmp(buffer, "random-seed") == 0) { + } else if (strcmp(name, "random-seed") == 0) { s_random_seed = atoi(value); - } else if (strcmp(buffer, "sgb-border") == 0) { + } else if (strcmp(name, "sgb-border") == 0) { s_use_sgb_border = atoi(value); } else { - fprintf(stderr, "warning: unknown ini key: %s\n", buffer); + fprintf(stderr, "warning: unknown ini key: %s\n", name); } } fclose(file); @@ -484,7 +511,9 @@ void read_ini_file(void) { int main(int argc, char** argv) { int result = 1; + host_input_defaults(&s_input); read_ini_file(); + if (!host_input_validate(&s_input)) return 1; parse_arguments(argc, argv); @@ -515,6 +544,8 @@ int main(int argc, char** argv) { host_init.rewind.buffer_capacity = s_rewind_buffer_capacity_megabytes * MEGABYTES(1); host_init.joypad_filename = s_read_joypad_filename; host_init.use_sgb_border = s_use_sgb_border; + host_init.ps2_keyboard = s_ps2_keyboard; + host_init.input = &s_input; host = host_new(&host_init, e); CHECK(host != NULL); diff --git a/src/emscripten/exported.json b/src/emscripten/exported.json index ff2b2ea..0101867 100644 --- a/src/emscripten/exported.json +++ b/src/emscripten/exported.json @@ -1,5 +1,6 @@ [ "_emulator_clear_breakpoints", +"_emulator_clear_ps2_queue", "_emulator_delete", "_emulator_get_A", "_emulator_get_BC", @@ -10,9 +11,11 @@ "_emulator_get_hram_ptr", "_emulator_get_PC", "_emulator_get_SP", +"_emulator_get_ps2_keyboard_connected", "_emulator_get_ticks_f64", "_emulator_get_wram_ptr", "_emulator_new_simple", +"_emulator_queue_ps2_scan_code", "_emulator_read_ext_ram", "_emulator_read_mem", "_emulator_read_state", @@ -24,6 +27,7 @@ "_emulator_set_bw_palette_simple", "_emulator_set_default_joypad_callback", "_emulator_set_PC", +"_emulator_set_ps2_keyboard_connected", "_emulator_set_rewind_joypad_callback", "_emulator_was_ext_ram_updated", "_emulator_write_ext_ram", diff --git a/src/emulator.c b/src/emulator.c index 77b41f4..a43fded 100644 --- a/src/emulator.c +++ b/src/emulator.c @@ -475,10 +475,24 @@ typedef struct { Ticks next_intr_ticks; /* Tick when the next intr will occur. */ SerialClock clock; Bool transferring; + Bool external_active; /* if a byte is being shifted in with external clock */ u8 sb; /* Serial transfer data. */ + u8 incoming; /* Remaining bits to shift in, MSB first. */ u8 transferred_bits; } Serial; +/* PS/2 keyboard attached to the serial port. Each scan code is sent as two + * externally-clocked serial bytes containing the 11-bit PS/2 frame (start + * bit, 8 data bits LSB first, odd parity, stop bit). This is host input, so + * it is not part of the save state. */ +#define PS2_QUEUE_SIZE 64 +typedef struct { + u8 queue[PS2_QUEUE_SIZE]; + u8 head; + u8 tail; + Bool connected; +} Ps2Keyboard; + typedef struct { Bool write; Bool read; @@ -716,6 +730,7 @@ struct Emulator { SgbFrameBuffer sgb_frame_buffer; AudioBuffer audio_buffer; JoypadCallbackInfo joypad_info; + Ps2Keyboard ps2_keyboard; /* color_to_rgba stores mappings from 4 DMG colors to RGBA colors. pal is a * cached copy of the current DMG palette (e.g. could be all COLOR_WHITE). */ PaletteRGBA color_to_rgba[PALETTE_TYPE_COUNT]; @@ -767,7 +782,7 @@ struct Emulator { #define VALUE_WRAPPED(X, MAX) \ (UNLIKELY((X) >= (MAX) ? ((X) -= (MAX), TRUE) : FALSE)) -#define SAVE_STATE_VERSION (2) +#define SAVE_STATE_VERSION (3) #define SAVE_STATE_HEADER (u32)(0x6b57a7e0 + SAVE_STATE_VERSION) #ifndef HOOK0 @@ -847,6 +862,7 @@ struct Emulator { #define DMA_TICKS 648 #define DMA_DELAY_TICKS 8 #define SERIAL_TICKS (CPU_TICKS_PER_SECOND / 8192) +#define PS2_TICKS 336 #define JOYP_INTERRUPT_WAIT_TICKS 10000 /* Arbitrary. */ /* Video */ @@ -1051,6 +1067,8 @@ static void serial_synchronize(Emulator*); static void timer_synchronize(Emulator*); static void calculate_next_ppu_intr(Emulator*); static void calculate_next_serial_intr(Emulator*); +static Bool serial_start_external_transfer(Emulator*); +static Bool ps2_pop(Emulator*, u8* byte); static MemoryTypeAddressPair make_pair(MemoryMapType type, Address addr) { MemoryTypeAddressPair result; @@ -2638,9 +2656,18 @@ static void write_io(Emulator* e, MaskedAddress addr, u8 value) { serial_synchronize(e); SERIAL.transferring = UNPACK(value, SC_TRANSFER_START); SERIAL.clock = UNPACK(value, SC_SHIFT_CLOCK); + SERIAL.external_active = FALSE; if (SERIAL.transferring) { SERIAL.tick_count = 0; SERIAL.transferred_bits = 0; + if (SERIAL.clock == SERIAL_CLOCK_INTERNAL) { + /* Nothing drives the data line unless the keyboard has data. */ + if (!ps2_pop(e, &SERIAL.incoming)) { + SERIAL.incoming = 0xff; + } + } else { + serial_start_external_transfer(e); + } } calculate_next_serial_intr(e); break; @@ -4041,7 +4068,7 @@ static void hdma_copy_byte(Emulator* e) { } static void calculate_next_serial_intr(Emulator* e) { - if (!SERIAL.transferring || SERIAL.clock != SERIAL_CLOCK_INTERNAL) { + if (!SERIAL.transferring || (SERIAL.clock == SERIAL_CLOCK_EXTERNAL && !SERIAL.external_active)) { SERIAL.next_intr_ticks = INVALID_TICKS; calculate_next_intr(e); return; @@ -4053,25 +4080,62 @@ static void calculate_next_serial_intr(Emulator* e) { SERIAL.next_intr_ticks = SERIAL.sync_ticks + SERIAL_TICKS * (CPU_SPEED.speed == SPEED_NORMAL ? 8 : 4); + + if (SERIAL.clock == SERIAL_CLOCK_EXTERNAL && emulator_get_ps2_keyboard_connected(e)) { + SERIAL.next_intr_ticks = SERIAL.sync_ticks + PS2_TICKS * 8; + } + calculate_next_intr(e); } +static Bool ps2_pop(Emulator* e, u8* byte) { + Ps2Keyboard* kb = &e->ps2_keyboard; + if (kb->head == kb->tail) { + return FALSE; + } + *byte = kb->queue[kb->head]; + kb->head = (kb->head + 1) % PS2_QUEUE_SIZE; + return TRUE; +} + +/* If the game is waiting on an externally-clocked transfer and the keyboard + * has data, start clocking the next byte in. */ +static Bool serial_start_external_transfer(Emulator* e) { + if (!SERIAL.transferring || SERIAL.clock != SERIAL_CLOCK_EXTERNAL || SERIAL.external_active) { + return FALSE; + } + if (!ps2_pop(e, &SERIAL.incoming)) { + return FALSE; + } + SERIAL.external_active = TRUE; + SERIAL.tick_count = 0; + SERIAL.transferred_bits = 0; + return TRUE; +} + static void serial_synchronize(Emulator* e) { if (TICKS > SERIAL.sync_ticks) { Ticks delta_ticks = TICKS - SERIAL.sync_ticks; if (UNLIKELY(SERIAL.transferring && - SERIAL.clock == SERIAL_CLOCK_INTERNAL)) { + (SERIAL.clock == SERIAL_CLOCK_INTERNAL || + SERIAL.external_active))) { Ticks cpu_tick = e->state.cpu_tick; + Ticks serial_ticks = SERIAL_TICKS; + if (emulator_get_ps2_keyboard_connected(e) && SERIAL.external_active) { + serial_ticks = PS2_TICKS; + } for (; delta_ticks > 0; delta_ticks -= cpu_tick) { SERIAL.tick_count += cpu_tick; - if (VALUE_WRAPPED(SERIAL.tick_count, SERIAL_TICKS)) { - /* Since we're never connected to another device, always shift in - * 0xff. */ - SERIAL.sb = (SERIAL.sb << 1) | 1; + if (VALUE_WRAPPED(SERIAL.tick_count, serial_ticks)) { + /* Shift in the next bit, MSB first. Once the incoming byte is + * exhausted the line idles high (1). */ + SERIAL.sb = (SERIAL.sb << 1) | (SERIAL.incoming >> 7); + SERIAL.incoming = (SERIAL.incoming << 1) | 1; SERIAL.transferred_bits++; if (VALUE_WRAPPED(SERIAL.transferred_bits, 8)) { SERIAL.transferring = 0; + SERIAL.external_active = FALSE; INTR.new_if |= IF_SERIAL; SERIAL.sync_ticks = TICKS - delta_ticks; calculate_next_serial_intr(e); @@ -4694,7 +4758,7 @@ static inline uint32_t emulator_get_banked_PC_inline(Emulator *e) { #endif } -static inline bool is_breakpoint(Emulator* e, uint32_t banked_pc) { +static inline Bool is_breakpoint(Emulator* e, uint32_t banked_pc) { uint32_t idx = banked_pc >> BREAKPOINTS_SHIFT; return (e->breakpoint[idx] & ((breakpoints_type)1 << (banked_pc & BREAKPOINTS_MASK))); } @@ -5112,6 +5176,80 @@ Emulator* emulator_new(const EmulatorInit* init) { return NULL; } +static Bool ps2_push(Ps2Keyboard* kb, u8 byte) { + u8 next_tail = (kb->tail + 1) % PS2_QUEUE_SIZE; + if (next_tail == kb->head) { + return FALSE; + } + kb->queue[kb->tail] = byte; + kb->tail = next_tail; + return TRUE; +} + +Bool emulator_queue_ps2_scan_code(Emulator* e, u8 scan_code) { + Ps2Keyboard* kb = &e->ps2_keyboard; + if (!kb->connected) { + return FALSE; + } + /* Each scan code needs two queue slots. */ + u32 used = (kb->tail + PS2_QUEUE_SIZE - kb->head) % PS2_QUEUE_SIZE; + if (used + 2 > PS2_QUEUE_SIZE - 1) { + return FALSE; + } + + /* Odd parity: the parity bit makes the total number of 1s odd. */ + u8 ones = 0; + int i; + for (i = 0; i < 8; ++i) { + ones += (scan_code >> i) & 1; + } + u8 parity = (ones & 1) ? 0 : 1; + + /* The serial port shifts MSB first, so the 11-bit frame is laid out as: + * byte 0: start(0) d0 d1 d2 d3 d4 d5 d6 + * byte 1: d7 parity stop(1) 0 0 0 0 0 */ + u8 frame0 = 0; + for (i = 0; i < 7; ++i) { + frame0 |= ((scan_code >> i) & 1) << (6 - i); + } + u8 frame1 = (scan_code & 0x80) | (parity << 6) | (1 << 5); + ps2_push(kb, frame0); + ps2_push(kb, frame1); + + /* The game may already be waiting for a byte. */ + serial_synchronize(e); + if (serial_start_external_transfer(e)) { + calculate_next_serial_intr(e); + } + return TRUE; +} + +void emulator_clear_ps2_queue(Emulator* e) { + e->ps2_keyboard.head = e->ps2_keyboard.tail = 0; +} + +void emulator_set_ps2_keyboard_connected(Emulator* e, Bool connected) { + Ps2Keyboard* kb = &e->ps2_keyboard; + if (kb->connected == connected) { + return; + } + kb->connected = connected; + if (!connected) { + emulator_clear_ps2_queue(e); + /* Unplugging stops the clock, so a byte that was being shifted in never + * finishes; the game keeps waiting, as on hardware. */ + serial_synchronize(e); + if (SERIAL.external_active) { + SERIAL.external_active = FALSE; + calculate_next_serial_intr(e); + } + } +} + +Bool emulator_get_ps2_keyboard_connected(Emulator* e) { + return e->ps2_keyboard.connected; +} + void emulator_delete(Emulator* e) { if (e) { xfree(e->audio_buffer.data); diff --git a/src/emulator.h b/src/emulator.h index 6d40ed4..27a2f7a 100644 --- a/src/emulator.h +++ b/src/emulator.h @@ -207,6 +207,15 @@ void emulator_delete(Emulator*); void emulator_set_joypad_buttons(Emulator*, JoypadButtons*); void emulator_set_joypad_callback(Emulator*, JoypadCallback, void* user_data); JoypadCallbackInfo emulator_get_joypad_callback(Emulator*); +/* A PS/2 keyboard can be attached to the serial port. It is disconnected by + * default. Disconnecting it clears its queue. */ +void emulator_set_ps2_keyboard_connected(Emulator*, Bool connected); +Bool emulator_get_ps2_keyboard_connected(Emulator*); +/* Queue a PS/2 (set 2) scan code byte to be sent over the serial port, e.g. + * 0xe0/0xf0 prefixes are queued as separate bytes. Returns FALSE if the + * keyboard is disconnected or the queue is full. */ +Bool emulator_queue_ps2_scan_code(Emulator*, u8 scan_code); +void emulator_clear_ps2_queue(Emulator*); void emulator_set_config(Emulator*, const EmulatorConfig*); EmulatorConfig emulator_get_config(Emulator*); FrameBuffer* emulator_get_frame_buffer(Emulator*); diff --git a/src/host-input.c b/src/host-input.c new file mode 100644 index 0000000..95ed0de --- /dev/null +++ b/src/host-input.c @@ -0,0 +1,140 @@ +#include "host-input.h" + +#include + +static const struct { + const char* name; + HostInputDestination destination; + HostKeycode key; +} s_bindings[] = { +#define V(id, name, destination, key) {name, HOST_INPUT_##destination, HOST_KEYCODE_##key}, + FOREACH_HOST_INPUT_BINDING(V) +#undef V +}; + +static const char* s_key_names[] = { + "UNKNOWN", +#define V(name) #name, + FOREACH_HOST_KEYCODE(V) +#undef V +}; + +static Bool name_equals(const char* a, size_t length, const char* b) { + if (length != strlen(b)) return FALSE; + size_t i; + for (i = 0; i < length; ++i) { + if (toupper((unsigned char)a[i]) != toupper((unsigned char)b[i])) return FALSE; + } + return TRUE; +} + +static Bool parse_keys(const char* value, u8* keys, Bool allow_all) { + memset(keys, 0, HOST_KEYCODE_COUNT); + const char* end = value + strlen(value); + while (isspace((unsigned char)*value)) ++value; + while (end > value && isspace((unsigned char)end[-1])) --end; + if (value == end || name_equals(value, end - value, "none")) return TRUE; + if (allow_all && name_equals(value, end - value, "all")) { + memset(keys + 1, 1, HOST_KEYCODE_COUNT - 1); + return TRUE; + } + while (value < end) { + const char* comma = memchr(value, ',', end - value); + const char* token_end = comma ? comma : end; + while (isspace((unsigned char)*value)) ++value; + while (token_end > value && isspace((unsigned char)token_end[-1])) --token_end; + HostKeycode key; + for (key = 1; key < HOST_KEYCODE_COUNT; ++key) { + if (name_equals(value, token_end - value, s_key_names[key])) break; + } + if (key == HOST_KEYCODE_COUNT) return FALSE; + keys[key] = 1; + if (!comma) break; + value = comma + 1; + if (value == end) return FALSE; + } + return TRUE; +} + +void host_input_defaults(HostInputConfig* config) { + ZERO_MEMORY(*config); + size_t i; + for (i = 0; i < ARRAY_SIZE(s_bindings); ++i) { + config->bindings[i][s_bindings[i].key] = 1; + } + parse_keys("all", config->ps2_keys, TRUE); +} + +int host_input_parse(HostInputConfig* config, const char* name, const char* value) { + u8 keys[HOST_KEYCODE_COUNT]; + if (strcmp(name, "ps2-keys") == 0) { + if (!parse_keys(value, keys, TRUE)) return -1; + memcpy(config->ps2_keys, keys, sizeof(keys)); + return 1; + } + /* Convenient starting points for a typing or controller-only profile. */ + HostInputDestination group = HOST_INPUT_NONE; + if (strcmp(name, "shortcuts") == 0) group = HOST_INPUT_SHORTCUT; + if (strcmp(name, "joypad") == 0) group = HOST_INPUT_JOYPAD; + if (group != HOST_INPUT_NONE) { + Bool defaults = name_equals(value, strlen(value), "default"); + if (!defaults && !name_equals(value, strlen(value), "none")) return -1; + size_t i; + for (i = 0; i < ARRAY_SIZE(s_bindings); ++i) { + if (s_bindings[i].destination != group) continue; + memset(config->bindings[i], 0, HOST_KEYCODE_COUNT); + if (defaults) config->bindings[i][s_bindings[i].key] = 1; + } + return 1; + } + size_t i; + for (i = 0; i < ARRAY_SIZE(s_bindings); ++i) { + if (strcmp(name, s_bindings[i].name) != 0) continue; + if (!parse_keys(value, keys, FALSE)) return -1; + memcpy(config->bindings[i], keys, sizeof(keys)); + return 1; + } + return 0; +} + +Bool host_input_validate(const HostInputConfig* config) { + Bool valid = TRUE; + size_t i, j; + HostKeycode key; + for (i = 0; i < ARRAY_SIZE(s_bindings); ++i) { + for (j = i + 1; j < ARRAY_SIZE(s_bindings); ++j) { + if (s_bindings[i].destination != s_bindings[j].destination) continue; + for (key = 1; key < HOST_KEYCODE_COUNT; ++key) { + if (config->bindings[i][key] && config->bindings[j][key]) { + fprintf(stderr, "conflicting input bindings: %s and %s both use %s\n", + s_bindings[i].name, s_bindings[j].name, s_key_names[key]); + valid = FALSE; + } + } + } + } + return valid; +} + +HostInputRoute host_input_route(const HostInputConfig* config, HostKeycode key, + Bool ps2_connected) { + HostInputRoute route = {HOST_INPUT_NONE, HOST_KEYCODE_UNKNOWN}; + if (key <= HOST_KEYCODE_UNKNOWN || key >= HOST_KEYCODE_COUNT) return route; + HostInputDestination destination; + for (destination = HOST_INPUT_SHORTCUT; destination <= HOST_INPUT_JOYPAD; + ++destination) { + size_t i; + for (i = 0; i < ARRAY_SIZE(s_bindings); ++i) { + if (s_bindings[i].destination == destination && config->bindings[i][key]) { + route.destination = destination; + route.key = s_bindings[i].key; + return route; + } + } + } + if (ps2_connected && config->ps2_keys[key]) { + route.destination = HOST_INPUT_PS2; + route.key = key; + } + return route; +} diff --git a/src/host-input.h b/src/host-input.h new file mode 100644 index 0000000..60f41b3 --- /dev/null +++ b/src/host-input.h @@ -0,0 +1,70 @@ +/* Native keyboard bindings and routing. */ +#ifndef BINJGB_HOST_INPUT_H_ +#define BINJGB_HOST_INPUT_H_ + +#include "host.h" + +typedef enum HostInputDestination { + HOST_INPUT_NONE, + HOST_INPUT_SHORTCUT, + HOST_INPUT_JOYPAD, + HOST_INPUT_PS2, + HOST_INPUT_RAW, +} HostInputDestination; + +/* The key is the logical key expected by existing joypad/shortcut handlers. */ +#define FOREACH_HOST_INPUT_BINDING(_) \ + _(UP, "joypad-up", JOYPAD, UP) \ + _(DOWN, "joypad-down", JOYPAD, DOWN) \ + _(LEFT, "joypad-left", JOYPAD, LEFT) \ + _(RIGHT, "joypad-right", JOYPAD, RIGHT) \ + _(B, "joypad-b", JOYPAD, Z) \ + _(A, "joypad-a", JOYPAD, X) \ + _(START, "joypad-start", JOYPAD, RETURN) \ + _(SELECT, "joypad-select", JOYPAD, TAB) \ + _(QUIT, "shortcut-quit", SHORTCUT, ESCAPE) \ + _(SAVE, "shortcut-save-state", SHORTCUT, F6) \ + _(LOAD, "shortcut-load-state", SHORTCUT, F9) \ + _(FULLSCREEN, "shortcut-fullscreen", SHORTCUT, F11) \ + _(AUDIO1, "shortcut-audio-1", SHORTCUT, 1) \ + _(AUDIO2, "shortcut-audio-2", SHORTCUT, 2) \ + _(AUDIO3, "shortcut-audio-3", SHORTCUT, 3) \ + _(AUDIO4, "shortcut-audio-4", SHORTCUT, 4) \ + _(BG, "shortcut-bg", SHORTCUT, B) \ + _(WINDOW, "shortcut-window", SHORTCUT, W) \ + _(OBJ, "shortcut-obj", SHORTCUT, O) \ + _(FAST_FORWARD, "shortcut-fast-forward", SHORTCUT, LSHIFT) \ + _(REWIND, "shortcut-rewind", SHORTCUT, BACKSPACE) \ + _(PAUSE, "shortcut-pause", SHORTCUT, SPACE) \ + _(STEP, "shortcut-step", SHORTCUT, N) \ + _(VOLUME_DOWN, "shortcut-volume-down", SHORTCUT, MINUS) \ + _(VOLUME_UP, "shortcut-volume-up", SHORTCUT, EQUALS) \ + _(PALETTE_PREV, "shortcut-palette-prev", SHORTCUT, LEFTBRACKET) \ + _(PALETTE_NEXT, "shortcut-palette-next", SHORTCUT, RIGHTBRACKET) + +typedef enum HostInputBinding { +#define V(id, name, destination, key) HOST_INPUT_BINDING_##id, + FOREACH_HOST_INPUT_BINDING(V) +#undef V + HOST_INPUT_BINDING_COUNT, +} HostInputBinding; + +typedef struct HostInputConfig { + u8 bindings[HOST_INPUT_BINDING_COUNT][HOST_KEYCODE_COUNT]; + u8 ps2_keys[HOST_KEYCODE_COUNT]; +} HostInputConfig; + +typedef struct HostInputRoute { + HostInputDestination destination; + HostKeycode key; +} HostInputRoute; + +void host_input_defaults(HostInputConfig*); +/* Returns 1 if handled, 0 if unknown, -1 if invalid (config unchanged). */ +int host_input_parse(HostInputConfig*, const char* name, const char* value); +/* Reports overlapping bindings within a destination. */ +Bool host_input_validate(const HostInputConfig*); +HostInputRoute host_input_route(const HostInputConfig*, HostKeycode, + Bool ps2_connected); + +#endif /* BINJGB_HOST_INPUT_H_ */ diff --git a/src/host.c b/src/host.c index 2ec17aa..dda9596 100644 --- a/src/host.c +++ b/src/host.c @@ -5,6 +5,7 @@ * of the MIT license. See the LICENSE file for details. */ #include "host.h" +#include "host-input.h" #include @@ -75,7 +76,10 @@ typedef struct Host { RewindState rewind_state; JoypadPlayback joypad_playback; Ticks last_ticks; - Bool key_state[HOST_KEYCODE_COUNT]; + u32 key_state[HOST_KEYCODE_COUNT]; + u32 shortcut_state[HOST_KEYCODE_COUNT]; + Bool physical_down[SDL_NUM_SCANCODES]; + HostInputRoute held_keys[SDL_NUM_SCANCODES]; } Host; static Emulator* host_get_emulator(Host* host) { @@ -155,6 +159,211 @@ static HostKeycode scancode_to_keycode(SDL_Scancode scancode) { return s_map[scancode]; } +/* Returns the PS/2 set 2 make code for |scancode|, or 0 if unmapped. Sets + * |*extended| if the key requires an 0xe0 prefix. */ +static u8 scancode_to_ps2(SDL_Scancode scancode, Bool* extended) { + *extended = FALSE; + switch (scancode) { + case SDL_SCANCODE_A: return 0x1c; + case SDL_SCANCODE_B: return 0x32; + case SDL_SCANCODE_C: return 0x21; + case SDL_SCANCODE_D: return 0x23; + case SDL_SCANCODE_E: return 0x24; + case SDL_SCANCODE_F: return 0x2b; + case SDL_SCANCODE_G: return 0x34; + case SDL_SCANCODE_H: return 0x33; + case SDL_SCANCODE_I: return 0x43; + case SDL_SCANCODE_J: return 0x3b; + case SDL_SCANCODE_K: return 0x42; + case SDL_SCANCODE_L: return 0x4b; + case SDL_SCANCODE_M: return 0x3a; + case SDL_SCANCODE_N: return 0x31; + case SDL_SCANCODE_O: return 0x44; + case SDL_SCANCODE_P: return 0x4d; + case SDL_SCANCODE_Q: return 0x15; + case SDL_SCANCODE_R: return 0x2d; + case SDL_SCANCODE_S: return 0x1b; + case SDL_SCANCODE_T: return 0x2c; + case SDL_SCANCODE_U: return 0x3c; + case SDL_SCANCODE_V: return 0x2a; + case SDL_SCANCODE_W: return 0x1d; + case SDL_SCANCODE_X: return 0x22; + case SDL_SCANCODE_Y: return 0x35; + case SDL_SCANCODE_Z: return 0x1a; + case SDL_SCANCODE_1: return 0x16; + case SDL_SCANCODE_2: return 0x1e; + case SDL_SCANCODE_3: return 0x26; + case SDL_SCANCODE_4: return 0x25; + case SDL_SCANCODE_5: return 0x2e; + case SDL_SCANCODE_6: return 0x36; + case SDL_SCANCODE_7: return 0x3d; + case SDL_SCANCODE_8: return 0x3e; + case SDL_SCANCODE_9: return 0x46; + case SDL_SCANCODE_0: return 0x45; + case SDL_SCANCODE_ESCAPE: return 0x76; + case SDL_SCANCODE_GRAVE: return 0x0e; + case SDL_SCANCODE_MINUS: return 0x4e; + case SDL_SCANCODE_EQUALS: return 0x55; + case SDL_SCANCODE_BACKSPACE: return 0x66; + case SDL_SCANCODE_TAB: return 0x0d; + case SDL_SCANCODE_LEFTBRACKET: return 0x54; + case SDL_SCANCODE_RIGHTBRACKET: return 0x5b; + case SDL_SCANCODE_BACKSLASH: return 0x5d; + case SDL_SCANCODE_SEMICOLON: return 0x4c; + case SDL_SCANCODE_APOSTROPHE: return 0x52; + case SDL_SCANCODE_RETURN: return 0x5a; + case SDL_SCANCODE_LSHIFT: return 0x12; + case SDL_SCANCODE_RSHIFT: return 0x59; + case SDL_SCANCODE_LCTRL: return 0x14; + case SDL_SCANCODE_LALT: return 0x11; + case SDL_SCANCODE_SPACE: return 0x29; + case SDL_SCANCODE_COMMA: return 0x41; + case SDL_SCANCODE_PERIOD: return 0x49; + case SDL_SCANCODE_SLASH: return 0x4a; + case SDL_SCANCODE_F1: return 0x05; + case SDL_SCANCODE_F2: return 0x06; + case SDL_SCANCODE_F3: return 0x04; + case SDL_SCANCODE_F4: return 0x0c; + case SDL_SCANCODE_F5: return 0x03; + case SDL_SCANCODE_F6: return 0x0b; + case SDL_SCANCODE_F7: return 0x83; + case SDL_SCANCODE_F8: return 0x0a; + case SDL_SCANCODE_F9: return 0x01; + case SDL_SCANCODE_F10: return 0x09; + case SDL_SCANCODE_F11: return 0x78; + case SDL_SCANCODE_F12: return 0x07; + case SDL_SCANCODE_CAPSLOCK: return 0x58; + case SDL_SCANCODE_SCROLLLOCK: return 0x7e; + case SDL_SCANCODE_NUMLOCKCLEAR: return 0x77; + case SDL_SCANCODE_KP_0: return 0x70; + case SDL_SCANCODE_KP_1: return 0x69; + case SDL_SCANCODE_KP_2: return 0x72; + case SDL_SCANCODE_KP_3: return 0x7a; + case SDL_SCANCODE_KP_4: return 0x6b; + case SDL_SCANCODE_KP_5: return 0x73; + case SDL_SCANCODE_KP_6: return 0x74; + case SDL_SCANCODE_KP_7: return 0x6c; + case SDL_SCANCODE_KP_8: return 0x75; + case SDL_SCANCODE_KP_9: return 0x7d; + case SDL_SCANCODE_KP_PERIOD: return 0x71; + case SDL_SCANCODE_KP_MULTIPLY: return 0x7c; + case SDL_SCANCODE_KP_MINUS: return 0x7b; + case SDL_SCANCODE_KP_PLUS: return 0x79; + default: break; + } + + *extended = TRUE; + switch (scancode) { + case SDL_SCANCODE_UP: return 0x75; + case SDL_SCANCODE_DOWN: return 0x72; + case SDL_SCANCODE_LEFT: return 0x6b; + case SDL_SCANCODE_RIGHT: return 0x74; + case SDL_SCANCODE_KP_DIVIDE: return 0x4a; + case SDL_SCANCODE_KP_ENTER: return 0x5a; + case SDL_SCANCODE_INSERT: return 0x70; + case SDL_SCANCODE_DELETE: return 0x71; + case SDL_SCANCODE_HOME: return 0x6c; + case SDL_SCANCODE_END: return 0x69; + case SDL_SCANCODE_PAGEUP: return 0x7d; + case SDL_SCANCODE_PAGEDOWN: return 0x7a; + case SDL_SCANCODE_RCTRL: return 0x14; + case SDL_SCANCODE_RALT: return 0x11; + case SDL_SCANCODE_LGUI: return 0x1f; + case SDL_SCANCODE_RGUI: return 0x27; + case SDL_SCANCODE_APPLICATION: return 0x2f; + default: break; + } + + *extended = FALSE; + return 0; +} + +/* The route is chosen on keydown and retained until release. */ +static void host_send_ps2_key(Host* host, SDL_Scancode scancode, Bool down) { + Emulator* e = host_get_emulator(host); + Bool extended; + u8 code = scancode_to_ps2(scancode, &extended); + if (!code) return; + if (extended) emulator_queue_ps2_scan_code(e, 0xe0); + if (!down) emulator_queue_ps2_scan_code(e, 0xf0); + emulator_queue_ps2_scan_code(e, code); +} + +static void host_dispatch_key(Host* host, SDL_Scancode scancode, + HostInputRoute route, Bool down, Bool cancel) { + switch (route.destination) { + case HOST_INPUT_PS2: + host_send_ps2_key(host, scancode, down); + break; + case HOST_INPUT_JOYPAD: + if (down) ++host->key_state[route.key]; + else --host->key_state[route.key]; + break; + case HOST_INPUT_SHORTCUT: + if (down) { + if (host->shortcut_state[route.key]++ == 0) HOOK(key_down, route.key); + } else if (--host->shortcut_state[route.key] == 0) { + /* Focus loss ends held actions without activating release shortcuts. */ + if (!cancel || route.key == HOST_KEYCODE_LSHIFT || + route.key == HOST_KEYCODE_BACKSPACE) HOOK(key_up, route.key); + } + break; + case HOST_INPUT_RAW: + if (down) { + ++host->key_state[route.key]; + HOOK(key_down, route.key); + } else { + --host->key_state[route.key]; + HOOK(key_up, route.key); + } + break; + default: break; + } +} + +static void host_key_event(Host* host, const SDL_KeyboardEvent* key) { + SDL_Scancode scancode = key->keysym.scancode; + if (scancode <= SDL_SCANCODE_UNKNOWN || scancode >= SDL_NUM_SCANCODES) return; + if (key->type == SDL_KEYUP) { + if (host->physical_down[scancode]) { + host_dispatch_key(host, scancode, host->held_keys[scancode], FALSE, FALSE); + host->physical_down[scancode] = FALSE; + ZERO_MEMORY(host->held_keys[scancode]); + } + return; + } + if (key->repeat || host->physical_down[scancode]) { + /* Preserve repeat-driven debugger navigation without repeating PS/2 or + * application shortcuts, or counting another held key. */ + HostInputRoute held = host->held_keys[scancode]; + if (key->repeat && host->physical_down[scancode] && + held.destination == HOST_INPUT_RAW && !host_ui_capture_keyboard(host->ui)) { + HOOK(key_down, held.key); + } + return; + } + host->physical_down[scancode] = TRUE; + if (host_ui_capture_keyboard(host->ui)) return; + HostKeycode code = scancode_to_keycode(scancode); + HostInputRoute route = {HOST_INPUT_RAW, code}; + if (host->init.input) { + route = host_input_route(host->init.input, code, + emulator_get_ps2_keyboard_connected(host_get_emulator(host))); + } + host->held_keys[scancode] = route; + host_dispatch_key(host, scancode, route, TRUE, FALSE); +} + +static void host_release_keys(Host* host) { + int scancode; + for (scancode = 1; scancode < SDL_NUM_SCANCODES; ++scancode) { + if (!host->physical_down[scancode]) continue; + host_dispatch_key(host, scancode, host->held_keys[scancode], FALSE, TRUE); + host->physical_down[scancode] = FALSE; + ZERO_MEMORY(host->held_keys[scancode]); + } +} + Bool host_poll_events(Host* host) { Emulator* e = host_get_emulator(host); Bool running = TRUE; @@ -164,18 +373,14 @@ Bool host_poll_events(Host* host) { switch (event.type) { case SDL_KEYDOWN: - case SDL_KEYUP: { - HostKeycode keycode = scancode_to_keycode(event.key.keysym.scancode); - if (!host_ui_capture_keyboard(host->ui)) { - host->key_state[keycode] = event.type == SDL_KEYDOWN; - } - if (event.type == SDL_KEYDOWN) { - HOOK(key_down, keycode); - } else { - HOOK(key_up, keycode); + case SDL_KEYUP: + host_key_event(host, &event.key); + break; + case SDL_WINDOWEVENT: + if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) { + host_release_keys(host); } break; - } case SDL_CONTROLLERDEVICEADDED: if (!host->controller) { host->controller = SDL_GameControllerOpen(event.cdevice.which); @@ -251,14 +456,14 @@ void host_render_audio(Host* host) { static void joypad_callback(JoypadButtons* joyp, void* user_data) { Host* host = user_data; - joyp->up = host->key_state[HOST_KEYCODE_UP]; - joyp->down = host->key_state[HOST_KEYCODE_DOWN]; - joyp->left = host->key_state[HOST_KEYCODE_LEFT]; - joyp->right = host->key_state[HOST_KEYCODE_RIGHT]; - joyp->B = host->key_state[HOST_KEYCODE_Z]; - joyp->A = host->key_state[HOST_KEYCODE_X]; - joyp->start = host->key_state[HOST_KEYCODE_RETURN]; - joyp->select = host->key_state[HOST_KEYCODE_TAB]; + joyp->up = host->key_state[HOST_KEYCODE_UP] != 0; + joyp->down = host->key_state[HOST_KEYCODE_DOWN] != 0; + joyp->left = host->key_state[HOST_KEYCODE_LEFT] != 0; + joyp->right = host->key_state[HOST_KEYCODE_RIGHT] != 0; + joyp->B = host->key_state[HOST_KEYCODE_Z] != 0; + joyp->A = host->key_state[HOST_KEYCODE_X] != 0; + joyp->start = host->key_state[HOST_KEYCODE_RETURN] != 0; + joyp->select = host->key_state[HOST_KEYCODE_TAB] != 0; /* Prefer controller input, if any */ if (host->controller) { @@ -462,6 +667,7 @@ Host* host_new(const HostInit *init, Emulator* e) { host->hook_ctx.e = e; host->hook_ctx.user_data = host->init.hooks.user_data; CHECK(SUCCESS(host_init(host, e))); + emulator_set_ps2_keyboard_connected(e, host->init.ps2_keyboard); return host; error: xfree(host); diff --git a/src/host.h b/src/host.h index 4b45499..f0cbcd5 100644 --- a/src/host.h +++ b/src/host.h @@ -89,7 +89,35 @@ extern "C" { _(LEFT) \ _(DOWN) \ _(UP) \ - _(LSHIFT) + _(LSHIFT) \ + _(RSHIFT) \ + _(LCTRL) \ + _(RCTRL) \ + _(LALT) \ + _(RALT) \ + _(LGUI) \ + _(RGUI) \ + _(APPLICATION) \ + _(CAPSLOCK) \ + _(NUMLOCKCLEAR) \ + _(SCROLLLOCK) \ + _(INSERT) \ + _(KP_0) \ + _(KP_1) \ + _(KP_2) \ + _(KP_3) \ + _(KP_4) \ + _(KP_5) \ + _(KP_6) \ + _(KP_7) \ + _(KP_8) \ + _(KP_9) \ + _(KP_PERIOD) \ + _(KP_MULTIPLY) \ + _(KP_MINUS) \ + _(KP_PLUS) \ + _(KP_DIVIDE) \ + _(KP_ENTER) typedef enum HostKeycode { HOST_KEYCODE_UNKNOWN, @@ -101,6 +129,7 @@ typedef enum HostKeycode { struct Emulator; struct Host; +struct HostInputConfig; typedef u32 EmulatorEvent; typedef struct HostHookContext { @@ -128,6 +157,10 @@ typedef struct HostInit { RewindInit rewind; const char* joypad_filename; Bool use_sgb_border; + /* Connect a PS/2 keyboard to the serial port at startup. */ + Bool ps2_keyboard; + /* NULL preserves raw keyboard hooks for the debugger. */ + const struct HostInputConfig* input; } HostInit; typedef struct HostConfig {