Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

WIIMOTE WORKSSSSSSSSS

Layle0697c3a43acc
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rs
index 8e182c9..7370f84 100644
--- a/crates/debugger/src/main.rs
+++ b/crates/debugger/src/main.rs
@@ -8,6 +8,7 @@ use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::{Window, WindowId};
+use gecko::HostInput;
use gecko::audio::WavAudioSink;
use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER};
use gecko::gamecube::GameCube;
@@ -29,17 +30,17 @@ enum EmulatorVariant {
}
impl EmulatorVariant {
- fn primary_controller_mut(&mut self) -> &mut PadStatus {
+ fn apply_host_input(&mut self, input: &HostInput) {
match self {
- Self::Gc(e) => e.primary_controller_mut(),
- Self::Wii(e) => e.primary_controller_mut(),
+ Self::Gc(e) => e.apply_host_input(input),
+ Self::Wii(e) => e.apply_host_input(input),
}
}
- fn add_primary_controller(&mut self, pad: PadStatus) {
+ fn neutral_input(&self) -> HostInput {
match self {
- Self::Gc(e) => e.add_primary_controller(pad),
- Self::Wii(e) => e.add_primary_controller(pad),
+ Self::Gc(_) => HostInput::gc_connected(),
+ Self::Wii(_) => HostInput::wii_neutral(),
}
}
@@ -89,6 +90,7 @@ impl EmulatorVariant {
struct App {
emulator: EmulatorVariant,
+ input: HostInput,
ui: DebuggerUi,
window: Option<Arc<Window>>,
state: Option<RenderState>,
@@ -229,7 +231,10 @@ impl ApplicationHandler for App {
}
if !egui_consumed {
- update_pad(self.emulator.primary_controller_mut(), key, pressed);
+ if let HostInput::Gc(pad) = &mut self.input {
+ update_pad(pad, key, pressed);
+ }
+ self.emulator.apply_host_input(&self.input);
}
}
}
@@ -390,10 +395,8 @@ fn main() {
.as_ref()
.map(|path| image::loader::load_symbols(std::path::Path::new(path)).expect("failed to load symbols"));
- emulator.add_primary_controller(PadStatus {
- connected: true,
- ..PadStatus::default()
- });
+ let input = emulator.neutral_input();
+ emulator.apply_host_input(&input);
// Debugger always dumps to WAV file
let emulated_rate = emulator.aid_sample_rate_hz();
@@ -435,6 +438,7 @@ fn main() {
let event_loop = EventLoop::new().unwrap();
let mut app = App {
emulator,
+ input,
ui,
window: None,
state: None,
diff --git a/crates/gecko/src/hollywood/ipc.rs b/crates/gecko/src/hollywood/ipc.rs
index 56f6310..0555be7 100644
--- a/crates/gecko/src/hollywood/ipc.rs
+++ b/crates/gecko/src/hollywood/ipc.rs
@@ -3,6 +3,7 @@ pub mod es;
pub mod fs;
pub mod sdio;
pub mod stm;
+pub mod sysconf;
pub mod usb;
use crate::dvd::DvdInterface;
@@ -76,6 +77,14 @@ pub trait IosDevice: Send {
);
IPC_EINVAL
}
+
+ fn set_wiimote_buttons(&mut self, _buttons: u16) -> bool {
+ false
+ }
+
+ fn set_nunchuk(&mut self, _buttons: u8, _stick_x: u8, _stick_y: u8) -> bool {
+ false
+ }
}
pub struct Ipc {
diff --git a/crates/gecko/src/hollywood/ipc/es.rs b/crates/gecko/src/hollywood/ipc/es.rs
index ced36aa..82296a4 100644
--- a/crates/gecko/src/hollywood/ipc/es.rs
+++ b/crates/gecko/src/hollywood/ipc/es.rs
@@ -1,5 +1,6 @@
use crate::hollywood::ipc::IosDevice;
+pub const IOCTL_GET_CONSUMPTION: u32 = 0x16;
pub const IOCTL_DI_GET_TICKET_VIEW: u32 = 0x1B;
pub const IOCTL_GET_DATA_DIR: u32 = 0x1D;
pub const IOCTL_GET_TITLE_ID: u32 = 0x20;
@@ -42,6 +43,10 @@ impl IosDevice for ETicketServices {
);
0
}
+ IOCTL_GET_CONSUMPTION => {
+ tracing::warn!(in_count, io_count, "ES_GetConsumption: stubbed");
+ 0
+ }
IOCTL_DI_GET_TICKET_VIEW => {
tracing::warn!(in_count, io_count, "ES_DIGetTicketView: stubbed");
0
diff --git a/crates/gecko/src/hollywood/ipc/sysconf.rs b/crates/gecko/src/hollywood/ipc/sysconf.rs
new file mode 100644
index 0000000..10227a7
--- /dev/null
+++ b/crates/gecko/src/hollywood/ipc/sysconf.rs
@@ -0,0 +1,199 @@
+use crate::hollywood::ipc::{IPC_EINVAL, IosDevice};
+
+const SYSCONF_SIZE: usize = 0x4000;
+const FOOTER_OFFSET: usize = 0x3FFC;
+
+const SEEK_SET: i32 = 0;
+const SEEK_CUR: i32 = 1;
+const SEEK_END: i32 = 2;
+
+const IOCTL_GET_FILE_STATS: u32 = 0xB;
+
+const TYPE_BIGARRAY: u8 = 1;
+const TYPE_BYTE: u8 = 3;
+const TYPE_LONG: u8 = 5;
+const TYPE_BOOL: u8 = 7;
+
+const BT_DINF_SLOT_SIZE: usize = 0x46;
+const BT_DINF_REGISTERED_SLOTS: usize = 10;
+const BT_DINF_ACTIVE_SLOTS: usize = 6;
+const BT_DINF_TOTAL_SLOTS: usize = BT_DINF_REGISTERED_SLOTS + BT_DINF_ACTIVE_SLOTS;
+
+pub struct SysConf {
+ blob: Vec<u8>,
+ pos: u64,
+}
+
+impl SysConf {
+ pub fn new() -> Self {
+ Self {
+ blob: self::build_blob(),
+ pos: 0,
+ }
+ }
+}
+
+impl IosDevice for SysConf {
+ fn open(&mut self, _ctx: &mut super::DeviceContext<'_>, _mode: u32) -> i32 {
+ self.pos = 0;
+ 0
+ }
+
+ fn read(&mut self, ctx: &mut super::DeviceContext<'_>, out_ptr: u32, out_len: u32) -> i32 {
+ let start = self.pos as usize;
+ let n = (out_len as usize).min(self.blob.len().saturating_sub(start));
+ if n == 0 {
+ return 0;
+ }
+
+ ctx.mmio
+ .phys_slice_mut(out_ptr, n)
+ .copy_from_slice(&self.blob[start..start + n]);
+ self.pos += n as u64;
+
+ n as i32
+ }
+
+ fn write(&mut self, _ctx: &mut super::DeviceContext<'_>, _in_ptr: u32, in_len: u32) -> i32 {
+ // what the fuck
+ in_len as i32
+ }
+
+ fn seek(&mut self, _ctx: &mut super::DeviceContext<'_>, offset: i32, whence: i32) -> i32 {
+ let new_pos: i64 = match whence {
+ SEEK_SET => offset as i64,
+ SEEK_CUR => self.pos as i64 + offset as i64,
+ SEEK_END => self.blob.len() as i64 + offset as i64,
+ _ => return IPC_EINVAL,
+ };
+
+ if new_pos < 0 || new_pos > self.blob.len() as i64 {
+ return IPC_EINVAL;
+ }
+
+ self.pos = new_pos as u64;
+ self.pos as i32
+ }
+
+ fn ioctl(
+ &mut self,
+ ctx: &mut super::DeviceContext<'_>,
+ cmd: u32,
+ _in_ptr: u32,
+ _in_len: u32,
+ out_ptr: u32,
+ _out_len: u32,
+ ) -> i32 {
+ if cmd == IOCTL_GET_FILE_STATS {
+ ctx.mmio.phys_write_u32(out_ptr, self.blob.len() as u32);
+ ctx.mmio.phys_write_u32(out_ptr + 4, self.pos as u32);
+ return 0;
+ }
+
+ tracing::warn!(
+ cmd = format!("{cmd:#010X}"),
+ out_buf = format!("{out_ptr:#010X}"),
+ "SysConf: unimplemented ioctl"
+ );
+ IPC_EINVAL
+ }
+}
+
+enum EntryData {
+ Byte(u8),
+ Bool(bool),
+ Long(u32),
+ BigArray(Vec<u8>),
+}
+
+impl EntryData {
+ fn type_code(&self) -> u8 {
+ match self {
+ EntryData::Byte(_) => TYPE_BYTE,
+ EntryData::Bool(_) => TYPE_BOOL,
+ EntryData::Long(_) => TYPE_LONG,
+ EntryData::BigArray(_) => TYPE_BIGARRAY,
+ }
+ }
+
+ fn write_into(&self, dst: &mut [u8]) -> usize {
+ match self {
+ EntryData::Byte(b) => {
+ dst[0] = *b;
+ 1
+ }
+ EntryData::Bool(b) => {
+ dst[0] = u8::from(*b);
+ 1
+ }
+ EntryData::Long(v) => {
+ dst[0..4].copy_from_slice(&v.to_be_bytes());
+ 4
+ }
+ EntryData::BigArray(data) => {
+ let prefix = ((data.len() - 1) as u16).to_be_bytes();
+ dst[0..2].copy_from_slice(&prefix);
+ dst[2..2 + data.len()].copy_from_slice(data);
+ 2 + data.len()
+ }
+ }
+ }
+}
+
+fn build_blob() -> Vec<u8> {
+ let entries: [(&[u8], EntryData); 11] = [
+ (b"BT.DINF", EntryData::BigArray(self::build_bt_dinf())),
+ (b"BT.MOT", EntryData::Byte(1)),
+ (b"BT.SENS", EntryData::Long(3)),
+ (b"BT.BAR", EntryData::Byte(1)),
+ (b"BT.SPKV", EntryData::Byte(0x58)),
+ (b"IPL.LNG", EntryData::Byte(1)),
+ (b"IPL.AR", EntryData::Byte(0)),
+ (b"IPL.E60", EntryData::Bool(false)),
+ (b"IPL.PGS", EntryData::Bool(false)),
+ (b"IPL.SND", EntryData::Byte(1)),
+ (b"IPL.CD", EntryData::Bool(true)),
+ ];
+
+ let mut blob = vec![0u8; SYSCONF_SIZE];
+ blob[0..4].copy_from_slice(b"SCv0");
+ blob[4..6].copy_from_slice(&(entries.len() as u16).to_be_bytes());
+
+ let dir_off = 0x06;
+ let mut entry_off = dir_off + entries.len() * 2 + 2;
+
+ for (i, (name, data)) in entries.iter().enumerate() {
+ let dir_pos = dir_off + i * 2;
+ blob[dir_pos..dir_pos + 2].copy_from_slice(&(entry_off as u16).to_be_bytes());
+
+ blob[entry_off] = self::encode_type_namelen(data.type_code(), name.len());
+ entry_off += 1;
+ blob[entry_off..entry_off + name.len()].copy_from_slice(name);
+ entry_off += name.len();
+ entry_off += data.write_into(&mut blob[entry_off..]);
+ }
+
+ let past_last = dir_off + entries.len() * 2;
+ blob[past_last..past_last + 2].copy_from_slice(&(entry_off as u16).to_be_bytes());
+
+ blob[FOOTER_OFFSET..FOOTER_OFFSET + 4].copy_from_slice(b"SCed");
+ blob
+}
+
+fn encode_type_namelen(type_code: u8, name_len: usize) -> u8 {
+ (type_code << 5) | ((name_len - 1) as u8 & 0x1F)
+}
+
+fn build_bt_dinf() -> Vec<u8> {
+ let mut wiimote_addr = super::usb::WIIMOTE_ADDR;
+ wiimote_addr.reverse();
+
+ let mut data = vec![0u8; 1 + BT_DINF_SLOT_SIZE * BT_DINF_TOTAL_SLOTS];
+ data[0] = 1;
+
+ let slot = &mut data[1..1 + BT_DINF_SLOT_SIZE];
+ slot[0..6].copy_from_slice(&wiimote_addr);
+ slot[6..6 + super::usb::WIIMOTE_NAME.len()].copy_from_slice(super::usb::WIIMOTE_NAME);
+
+ data
+}
diff --git a/crates/gecko/src/hollywood/ipc/usb.rs b/crates/gecko/src/hollywood/ipc/usb.rs
index 116f854..bb35df9 100644
--- a/crates/gecko/src/hollywood/ipc/usb.rs
+++ b/crates/gecko/src/hollywood/ipc/usb.rs
@@ -1,25 +1,48 @@
+mod bluetooth;
+mod l2cap;
+mod wiimote;
+
use crate::hollywood::ipc::{DeviceContext, IosDevice};
+pub(crate) use bluetooth::{WIIMOTE_ADDR, WIIMOTE_NAME};
use std::collections::VecDeque;
+pub use wiimote::{
+ BTN_A, BTN_B, BTN_DOWN, BTN_HOME, BTN_LEFT, BTN_MINUS, BTN_ONE, BTN_PLUS, BTN_RIGHT, BTN_TWO, BTN_UP,
+ NUNCHUK_BTN_C, NUNCHUK_BTN_Z,
+};
const USB_CTRL: u32 = 0;
const USB_BULK: u32 = 1;
const USB_INTR: u32 = 2;
const EP_INT_IN: u8 = 0x81;
+const EP_BULK_OUT: u8 = 0x02;
+const EP_BULK_IN: u8 = 0x82;
-const EV_COMMAND_COMPLETE: u8 = 0x0E;
-const OP_READ_LOCAL_VERSION: u16 = 0x1001;
-const OP_READ_LOCAL_FEATURES: u16 = 0x1003;
-const OP_READ_BUFFER_SIZE: u16 = 0x1005;
-const OP_READ_BD_ADDR: u16 = 0x1009;
+const MAX_PENDING_QUEUE: usize = 256;
pub struct Bluetooth {
- pending_hci: VecDeque<Vec<u8>>,
+ pub(self) pending_hci: VecDeque<Vec<u8>>,
+ pub(self) pending_acl: VecDeque<Vec<u8>>,
+ pub(self) wiimote: wiimote::WiimoteState,
+ pub(self) scanning: bool,
+ pub(self) connection_requested: bool,
+ pub(self) connected: bool,
+ pub(self) host_hid_control_cid: Option<u16>,
+ pub(self) host_hid_interrupt_cid: Option<u16>,
+ pub(self) next_l2cap_ident: u8,
}
impl Bluetooth {
pub fn new() -> Self {
Self {
pending_hci: VecDeque::new(),
+ pending_acl: VecDeque::new(),
+ wiimote: wiimote::WiimoteState::default(),
+ scanning: false,
+ connection_requested: false,
+ connected: false,
+ host_hid_control_cid: None,
+ host_hid_interrupt_cid: None,
+ next_l2cap_ident: 2,
}
}
}
@@ -33,6 +56,14 @@ impl IosDevice for Bluetooth {
_ => 0,
}
}
+
+ fn set_wiimote_buttons(&mut self, buttons: u16) -> bool {
+ Bluetooth::set_wiimote_buttons(self, buttons)
+ }
+
+ fn set_nunchuk(&mut self, buttons: u8, stick_x: u8, stick_y: u8) -> bool {
+ Bluetooth::set_nunchuk(self, buttons, stick_x, stick_y)
+ }
}
impl Bluetooth {
@@ -52,27 +83,54 @@ impl Bluetooth {
}
let data_ptr = self::vec_data(ctx.mmio, vec_ptr, 6);
- let opcode = u16::from_le_bytes([ctx.mmio.phys_read_u8(data_ptr), ctx.mmio.phys_read_u8(data_ptr + 1)]);
+ let packet = ctx.mmio.phys_slice(data_ptr, w_length as usize).to_vec();
+ if packet.len() < 2 {
+ return 0;
+ }
- self.queue_command_complete(opcode);
+ self.handle_hci_command(&packet);
0
}
- /// For bulk OUT (0x02) we currently drop whatever the SDK sends. We warn if
- /// there's any payload, since Bulk IN (0x82) just gets a length 0 reply
- /// since we don't have ACL frames queued.
fn handle_bulk(&mut self, ctx: &mut DeviceContext<'_>, vec_ptr: u32) -> i32 {
let endpoint = ctx.mmio.phys_read_u8(self::vec_data(ctx.mmio, vec_ptr, 0));
+ let len_p = self::vec_data(ctx.mmio, vec_ptr, 1);
+ let w_length = u16::from_le_bytes([ctx.mmio.phys_read_u8(len_p), ctx.mmio.phys_read_u8(len_p + 1)]);
+ let buf_ptr = self::vec_data(ctx.mmio, vec_ptr, 2);
- if endpoint == 0x02 {
- let len_p = self::vec_data(ctx.mmio, vec_ptr, 1);
- let w_length = u16::from_le_bytes([ctx.mmio.phys_read_u8(len_p), ctx.mmio.phys_read_u8(len_p + 1)]);
- if w_length > 0 {
- tracing::warn!(len = w_length, "no L2CAP yet");
+ match endpoint {
+ EP_BULK_OUT => {
+ let packet = ctx.mmio.phys_slice(buf_ptr, w_length as usize).to_vec();
+ tracing::debug!(
+ bytes = format!("{packet:02X?}"),
+ "received Bluetooth ACL frame from guest"
+ );
+ self.handle_acl_out(&packet);
+ // Without this the host's HCI tx-buffer fills up
+ // after 8? ACL packets and it disconnects the wiimote.
+ self.queue_number_of_completed_packets(1);
+ w_length as i32
+ }
+ EP_BULK_IN => {
+ let Some(packet) = self.pending_acl.pop_front() else {
+ return 0;
+ };
+
+ let delivered = packet.len().min(w_length as usize);
+ ctx.mmio
+ .phys_slice_mut(buf_ptr, delivered)
+ .copy_from_slice(&packet[..delivered]);
+
+ tracing::debug!(
+ len = delivered,
+ bytes = format!("{:02X?}", &packet[..delivered]),
+ "delivering Bluetooth ACL frame to guest"
+ );
+
+ delivered as i32
}
+ _ => 0,
}
-
- 0
}
/// HCI event receive (interrupt IN endpoint 0x81). Deliver the next
@@ -87,52 +145,52 @@ impl Bluetooth {
};
let buf_ptr = self::vec_data(ctx.mmio, vec_ptr, 2);
- for (i, b) in event.iter().enumerate() {
- ctx.mmio.phys_write_u8(buf_ptr + i as u32, *b);
- }
+ ctx.mmio.phys_slice_mut(buf_ptr, event.len()).copy_from_slice(&event);
+
+ tracing::debug!(
+ event = format!("{:02X?}", &event),
+ "delivering Bluetooth HCI event to guest"
+ );
event.len() as i32
}
- /// Build an HCI Command_Complete event for `opcode` and append it to the
- /// outgoing queue. The four init Read_* commands need real payloads so
- /// the SDK's BTM init state machine can advance to state 5; everything
- /// else is generic status=0.
- fn queue_command_complete(&mut self, opcode: u16) {
- let payload: &[u8] = match opcode {
- OP_READ_LOCAL_VERSION => &[
- 0x00, // status
- 0x03, // HCI v1.2
- 0x40, 0x0E, // HCI revision
- 0x03, // LMP v1.2
- 0x0F, 0x00, // manufacturer = Broadcom
- 0x40, 0x0E, // LMP subversion
- ],
- OP_READ_LOCAL_FEATURES => &[0x00, 0xBC, 0x02, 0x04, 0x38, 0x08, 0x08, 0x00, 0x00],
- OP_READ_BUFFER_SIZE => &[
- 0x00, 0x53, 0x01, // ACL packet length = 339
- 0x40, // SCO packet length = 64
- 0x08, 0x00, // num ACL packets
- 0x08, 0x00, // num SCO packets
- ],
- OP_READ_BD_ADDR => &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66],
- _ => &[0x00],
- };
+ fn set_wiimote_buttons(&mut self, buttons: u16) -> bool {
+ let changed = self.wiimote.set_buttons(buttons);
+
+ if changed {
+ tracing::debug!(buttons = format!("{buttons:#06x}"), "Wiimote button state changed");
+ }
+
+ if self.host_hid_interrupt_cid.is_none() {
+ return changed;
+ }
+
+ let report = self.wiimote.make_input_report();
+ self.queue_hid_input_report(report);
- let mut event = Vec::with_capacity(5 + payload.len());
- event.extend_from_slice(&[
- EV_COMMAND_COMPLETE,
- (3 + payload.len()) as u8,
- 0x01, // num_hci_command_packets
- opcode as u8,
- (opcode >> 8) as u8,
- ]);
- event.extend_from_slice(payload);
-
- self.pending_hci.push_back(event);
+ changed
}
+
+ fn set_nunchuk(&mut self, buttons: u8, stick_x: u8, stick_y: u8) -> bool {
+ self.wiimote.set_nunchuk(buttons, stick_x, stick_y)
+ }
+}
+
+#[inline(always)]
+fn push_capped(queue: &mut VecDeque<Vec<u8>>, frame: Vec<u8>) {
+ if queue.len() >= MAX_PENDING_QUEUE {
+ tracing::warn!(
+ cap = MAX_PENDING_QUEUE,
+ "Bluetooth pending queue full; dropping oldest frame"
+ );
+ queue.pop_front();
+ }
+
+ queue.push_back(frame);
}
+#[inline(always)]
fn vec_data<const SYS: crate::system::SystemId>(mmio: &crate::mmio::Mmio<SYS>, vec_ptr: u32, idx: u32) -> u32 {
mmio.phys_read_u32(vec_ptr + (idx * 8))
}
diff --git a/crates/gecko/src/hollywood/ipc/usb/bluetooth.rs b/crates/gecko/src/hollywood/ipc/usb/bluetooth.rs
new file mode 100644
index 0000000..85c3d0b
--- /dev/null
+++ b/crates/gecko/src/hollywood/ipc/usb/bluetooth.rs
@@ -0,0 +1,285 @@
+use super::Bluetooth;
+use super::l2cap::{L2CAP_CID_HID_CONTROL, L2CAP_PSM_HID_CONTROL};
+
+const EV_DISCONNECTION_COMPLETE: u8 = 0x05;
+const EV_NUMBER_OF_COMPLETED_PACKETS: u8 = 0x13;
+const EV_COMMAND_COMPLETE: u8 = 0x0E;
+const EV_COMMAND_STATUS: u8 = 0x0F;
+const EV_CONNECTION_COMPLETE: u8 = 0x03;
+const EV_CONNECTION_REQUEST: u8 = 0x04;
+const EV_AUTHENTICATION_COMPLETE: u8 = 0x06;
+const EV_REMOTE_NAME_REQUEST_COMPLETE: u8 = 0x07;
+const EV_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: u8 = 0x0B;
+const EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE: u8 = 0x0C;
+const EV_ROLE_CHANGE: u8 = 0x12;
+const EV_MODE_CHANGE: u8 = 0x14;
+const EV_RETURN_LINK_KEYS: u8 = 0x15;
+const EV_READ_CLOCK_OFFSET_COMPLETE: u8 = 0x1C;
+const EV_CONNECTION_PACKET_TYPE_CHANGED: u8 = 0x1D;
+
+const OP_DISCONNECT: u16 = 0x0406;
+const OP_RESET: u16 = 0x0C03;
+const OP_READ_LOCAL_VERSION: u16 = 0x1001;
+const OP_READ_LOCAL_FEATURES: u16 = 0x1003;
+const OP_READ_BUFFER_SIZE: u16 = 0x1005;
+const OP_READ_BD_ADDR: u16 = 0x1009;
+const OP_WRITE_LOCAL_NAME: u16 = 0x0C13;
+const OP_READ_STORED_LINK_KEY: u16 = 0x0C0D;
+const OP_DELETE_STORED_LINK_KEY: u16 = 0x0C12;
+const OP_WRITE_PIN_TYPE: u16 = 0x0C0A;
+const OP_WRITE_PAGE_TIMEOUT: u16 = 0x0C18;
+const OP_WRITE_SCAN_ENABLE: u16 = 0x0C1A;
+const OP_WRITE_CLASS_OF_DEVICE: u16 = 0x0C24;
+const OP_HOST_BUFFER_SIZE: u16 = 0x0C33;
+const OP_WRITE_LINK_SUPERVISION_TIMEOUT: u16 = 0x0C37;
+const OP_WRITE_INQUIRY_SCAN_TYPE: u16 = 0x0C43;
+const OP_WRITE_INQUIRY_MODE: u16 = 0x0C45;
+const OP_WRITE_PAGE_SCAN_TYPE: u16 = 0x0C47;
+const OP_ACCEPT_CONNECTION_REQUEST: u16 = 0x0409;
+const OP_CHANGE_CONNECTION_PACKET_TYPE: u16 = 0x040F;
+const OP_AUTHENTICATION_REQUESTED: u16 = 0x0411;
+const OP_REMOTE_NAME_REQUEST: u16 = 0x0419;
+const OP_READ_REMOTE_SUPPORTED_FEATURES: u16 = 0x041B;
+const OP_READ_REMOTE_VERSION_INFORMATION: u16 = 0x041D;
+const OP_READ_CLOCK_OFFSET: u16 = 0x041F;
+const OP_SNIFF_MODE: u16 = 0x0803;
+const OP_WRITE_LINK_POLICY_SETTINGS: u16 = 0x080D;
+const OP_VENDOR_SPECIFIC_4C: u16 = 0xFC4C;
+const OP_VENDOR_SPECIFIC_4F: u16 = 0xFC4F;
+
+pub(crate) const WIIMOTE_ADDR: [u8; 6] = [0x11, 0x02, 0x19, 0x79, 0x00, 0x00];
+const WIIMOTE_LINK_KEY: [u8; 16] = [
+ 0x41, 0x20, 0x76, 0x69, 0x72, 0x74, 0x75, 0x61, 0x6C, 0x20, 0x57, 0x69, 0x69, 0x6D, 0x6F, 0x74,
+];
+pub(crate) const WIIMOTE_NAME: &[u8] = b"Nintendo RVL-CNT-01";
+
+impl Bluetooth {
+ pub(super) fn handle_hci_command(&mut self, packet: &[u8]) {
+ let opcode = u16::from_le_bytes([packet[0], packet[1]]);
+ let params = packet.get(3..).unwrap_or(&[]);
+ tracing::debug!(
+ opcode = format!("{opcode:#06x}"),
+ params = format!("{params:02X?}"),
+ "received Bluetooth HCI command"
+ );
+
+ match opcode {
+ OP_WRITE_SCAN_ENABLE => {
+ let scan_enable = params.first().copied().unwrap_or(0);
+ self.scanning = (scan_enable & 0x02) != 0;
+ tracing::debug!(
+ scan_enable = format!("{scan_enable:#04x}"),
+ page_scan = self.scanning,
+ "Bluetooth scan enable"
+ );
+ self.queue_command_complete(opcode);
+ if self.scanning && !self.connection_requested && !self.connected {
+ self.queue_connection_request();
+ }
+ }
+ OP_ACCEPT_CONNECTION_REQUEST => {
+ tracing::debug!("guest accepted fake Wiimote Bluetooth connection");
+ self.queue_command_status(opcode);
+ self.queue_role_change();
+ self.queue_connection_complete();
+ self.connected = true;
+ self.queue_l2cap_connect_request(L2CAP_PSM_HID_CONTROL, L2CAP_CID_HID_CONTROL);
+ }
+ OP_REMOTE_NAME_REQUEST => {
+ self.queue_command_status(opcode);
+ self.queue_remote_name_request_complete();
+ }
+ OP_READ_REMOTE_SUPPORTED_FEATURES => {
+ self.queue_command_status(opcode);
+ self.queue_read_remote_supported_features_complete();
+ }
+ OP_READ_REMOTE_VERSION_INFORMATION => {
+ self.queue_command_status(opcode);
+ self.queue_read_remote_version_information_complete();
+ }
+ OP_READ_CLOCK_OFFSET => {
+ self.queue_command_status(opcode);
+ self.queue_read_clock_offset_complete();
+ }
+ OP_AUTHENTICATION_REQUESTED => {
+ self.queue_command_status(opcode);
+ self.queue_authentication_complete();
+ }
+ OP_CHANGE_CONNECTION_PACKET_TYPE => {
+ self.queue_command_status(opcode);
+ self.queue_connection_packet_type_changed();
+ }
+ OP_SNIFF_MODE => {
+ self.queue_command_status(opcode);
+ self.queue_mode_change();
+ }
+ OP_READ_STORED_LINK_KEY => {
+ self.queue_return_link_keys();
+ self.queue_command_complete(opcode);
+ }
+ OP_WRITE_LINK_SUPERVISION_TIMEOUT => {
+ self.queue_command_complete(opcode);
+ }
+ OP_DISCONNECT => {
+ let reason = params.get(2).copied().unwrap_or(0x13);
+ tracing::warn!(reason = format!("{reason:#04x}"), "guest requested HCI disconnect");
+ self.queue_command_status(opcode);
+ self.queue_disconnection_complete(reason);
+ self.connected = false;
+ self.host_hid_control_cid = None;
+ self.host_hid_interrupt_cid = None;
+ self.connection_requested = false;
+ }
+ _ => self.queue_command_complete(opcode),
+ }
+ }
+
+ fn queue_command_complete(&mut self, opcode: u16) {
+ let payload: &[u8] = match opcode {
+ OP_RESET
+ | OP_WRITE_LOCAL_NAME
+ | OP_DELETE_STORED_LINK_KEY
+ | OP_WRITE_PIN_TYPE
+ | OP_WRITE_PAGE_TIMEOUT
+ | OP_WRITE_SCAN_ENABLE
+ | OP_WRITE_CLASS_OF_DEVICE
+ | OP_HOST_BUFFER_SIZE
+ | OP_WRITE_INQUIRY_SCAN_TYPE
+ | OP_WRITE_INQUIRY_MODE
+ | OP_WRITE_PAGE_SCAN_TYPE
+ | OP_VENDOR_SPECIFIC_4C
+ | OP_VENDOR_SPECIFIC_4F => &[0x00],
+ OP_READ_STORED_LINK_KEY => &[
+ 0x00, // status
+ 0xFF, 0x00, // max_num_keys
+ 0x01, 0x00, // num_keys_read
+ ],
+ OP_WRITE_LINK_SUPERVISION_TIMEOUT | OP_WRITE_LINK_POLICY_SETTINGS => &[
+ 0x00, // status
+ 0x00, 0x01, // connection handle
+ ],
+ OP_READ_LOCAL_VERSION => &[
+ 0x00, // status
+ 0x03, // HCI v1.2
+ 0x40, 0x0E, // HCI revision
+ 0x03, // LMP v1.2
+ 0x0F, 0x00, // manufacturer = Broadcom
+ 0x40, 0x0E, // LMP subversion
+ ],
+ OP_READ_LOCAL_FEATURES => &[0x00, 0xBC, 0x02, 0x04, 0x38, 0x08, 0x08, 0x00, 0x00],
+ OP_READ_BUFFER_SIZE => &[
+ 0x00, 0x53, 0x01, // ACL packet length = 339
+ 0x40, // SCO packet length = 64
+ 0x08, 0x00, // num ACL packets
+ 0x08, 0x00, // num SCO packets
+ ],
+ OP_READ_BD_ADDR => &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66],
+ _ => &[0x00],
+ };
+
+ let mut buf = Vec::with_capacity(3 + payload.len());
+ buf.push(0x01); // num_hci_command_packets
+ buf.push(opcode as u8);
+ buf.push((opcode >> 8) as u8);
+ buf.extend_from_slice(payload);
+ self.queue_hci_event(EV_COMMAND_COMPLETE, &buf);
+ }
+
+ pub(super) fn queue_hci_event(&mut self, code: u8, payload: &[u8]) {
+ let mut event = Vec::with_capacity(2 + payload.len());
+ event.push(code);
+ event.push(payload.len() as u8);
+ event.extend_from_slice(payload);
+ super::push_capped(&mut self.pending_hci, event);
+ }
+
+ fn queue_command_status(&mut self, opcode: u16) {
+ self.queue_hci_event(EV_COMMAND_STATUS, &[0x00, 0x01, opcode as u8, (opcode >> 8) as u8]);
+ }
+
+ fn queue_return_link_keys(&mut self) {
+ tracing::debug!(
+ addr = format!("{WIIMOTE_ADDR:02X?}"),
+ "queueing fake Wiimote stored link key"
+ );
+ let mut payload = Vec::with_capacity(23);
+ payload.push(0x01);
+ payload.extend_from_slice(&WIIMOTE_ADDR);
+ payload.extend_from_slice(&WIIMOTE_LINK_KEY);
+ self.queue_hci_event(EV_RETURN_LINK_KEYS, &payload);
+ }
+
+ fn queue_connection_request(&mut self) {
+ self.connection_requested = true;
+ tracing::debug!("queueing fake Wiimote Bluetooth connection request");
+ let mut payload = Vec::with_capacity(10);
+ payload.extend_from_slice(&WIIMOTE_ADDR);
+ payload.extend_from_slice(&[0x04, 0x25, 0x00, 0x01]);
+ self.queue_hci_event(EV_CONNECTION_REQUEST, &payload);
+ }
+
+ fn queue_role_change(&mut self) {
+ let mut payload = Vec::with_capacity(8);
+ payload.push(0x00);
+ payload.extend_from_slice(&WIIMOTE_ADDR);
+ payload.push(0x00);
+ self.queue_hci_event(EV_ROLE_CHANGE, &payload);
+ }
+
+ pub(super) fn queue_number_of_completed_packets(&mut self, count: u16) {
+ self.queue_hci_event(
+ EV_NUMBER_OF_COMPLETED_PACKETS,
+ &[0x01, 0x00, 0x01, count as u8, (count >> 8) as u8],
+ );
+ }
+
+ fn queue_disconnection_complete(&mut self, reason: u8) {
+ self.queue_hci_event(EV_DISCONNECTION_COMPLETE, &[0x00, 0x00, 0x01, reason]);
+ }
+
+ fn queue_connection_complete(&mut self) {
+ let mut payload = Vec::with_capacity(11);
+ payload.extend_from_slice(&[0x00, 0x00, 0x01]);
+ payload.extend_from_slice(&WIIMOTE_ADDR);
+ payload.extend_from_slice(&[0x01, 0x00]);
+ self.queue_hci_event(EV_CONNECTION_COMPLETE, &payload);
+ }
+
+ fn queue_remote_name_request_complete(&mut self) {
+ let mut payload = vec![0u8; 255];
+ payload[0] = 0x00;
+ payload[1..7].copy_from_slice(&WIIMOTE_ADDR);
+ payload[7..7 + WIIMOTE_NAME.len()].copy_from_slice(WIIMOTE_NAME);
+ self.queue_hci_event(EV_REMOTE_NAME_REQUEST_COMPLETE, &payload);
+ }
+
+ fn queue_read_remote_supported_features_complete(&mut self) {
+ self.queue_hci_event(
+ EV_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE,
+ &[0x00, 0x00, 0x01, 0xBC, 0x02, 0x04, 0x38, 0x08, 0x00, 0x00, 0x00],
+ );
+ }
+
+ fn queue_read_remote_version_information_complete(&mut self) {
+ self.queue_hci_event(
+ EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE,
+ &[0x00, 0x00, 0x01, 0x02, 0x0F, 0x00, 0x29, 0x02],
+ );
+ }
+
+ fn queue_read_clock_offset_complete(&mut self) {
+ self.queue_hci_event(EV_READ_CLOCK_OFFSET_COMPLETE, &[0x00, 0x00, 0x01, 0x18, 0x38]);
+ }
+
+ fn queue_authentication_complete(&mut self) {
+ self.queue_hci_event(EV_AUTHENTICATION_COMPLETE, &[0x00, 0x00, 0x01]);
+ }
+
+ fn queue_connection_packet_type_changed(&mut self) {
+ self.queue_hci_event(EV_CONNECTION_PACKET_TYPE_CHANGED, &[0x00, 0x00, 0x01, 0x18, 0xCC]);
+ }
+
+ fn queue_mode_change(&mut self) {
+ self.queue_hci_event(EV_MODE_CHANGE, &[0x00, 0x00, 0x01, 0x00, 0x00, 0x00]);
+ }
+}
diff --git a/crates/gecko/src/hollywood/ipc/usb/l2cap.rs b/crates/gecko/src/hollywood/ipc/usb/l2cap.rs
new file mode 100644
index 0000000..648fb7c
--- /dev/null
+++ b/crates/gecko/src/hollywood/ipc/usb/l2cap.rs
@@ -0,0 +1,208 @@
+use super::Bluetooth;
+
+pub(super) const L2CAP_CID_SIGNALING: u16 = 0x0001;
+pub(super) const L2CAP_CID_HID_CONTROL: u16 = 0x0040;
+pub(super) const L2CAP_CID_HID_INTERRUPT: u16 = 0x0041;
+pub(super) const L2CAP_PSM_HID_CONTROL: u16 = 0x0011;
+pub(super) const L2CAP_PSM_HID_INTERRUPT: u16 = 0x0013;
+
+const L2CAP_CONNECT_REQ: u8 = 0x02;
+const L2CAP_CONNECT_RSP: u8 = 0x03;
+const L2CAP_CONFIG_REQ: u8 = 0x04;
+const L2CAP_CONFIG_RSP: u8 = 0x05;
+const L2CAP_DISCONNECT_REQ: u8 = 0x06;
+
+impl Bluetooth {
+ pub(super) fn handle_acl_out(&mut self, packet: &[u8]) {
+ if packet.len() < 8 {
+ return;
+ }
+
+ let l2cap_len = u16::from_le_bytes([packet[4], packet[5]]) as usize;
+ let cid = u16::from_le_bytes([packet[6], packet[7]]);
+ let Some(payload) = packet.get(8..8 + l2cap_len.min(packet.len().saturating_sub(8))) else {
+ return;
+ };
+
+ match cid {
+ L2CAP_CID_SIGNALING => self.handle_l2cap_signaling(payload),
+ L2CAP_CID_HID_CONTROL | L2CAP_CID_HID_INTERRUPT => self.handle_wiimote_hid(payload),
+ _ => tracing::debug!(
+ cid = format!("{cid:#06x}"),
+ "ignored ACL payload for unknown L2CAP channel"
+ ),
+ }
+ }
+
+ fn handle_l2cap_signaling(&mut self, mut payload: &[u8]) {
+ while payload.len() >= 4 {
+ let code = payload[0];
+ let ident = payload[1];
+ let len = u16::from_le_bytes([payload[2], payload[3]]) as usize;
+ if payload.len() < 4 + len {
+ return;
+ }
+
+ let data = &payload[4..4 + len];
+ match code {
+ L2CAP_CONNECT_REQ if data.len() >= 4 => {
+ let psm = u16::from_le_bytes([data[0], data[1]]);
+ let source_cid = u16::from_le_bytes([data[2], data[3]]);
+
+ match psm {
+ L2CAP_PSM_HID_CONTROL => {
+ self.host_hid_control_cid = Some(source_cid);
+ tracing::debug!(
+ host_cid = format!("{source_cid:#06x}"),
+ "guest connected Wiimote HID control channel"
+ );
+
+ self.queue_l2cap_connect_rsp(ident, source_cid, L2CAP_CID_HID_CONTROL, 0);
+ self.queue_l2cap_config_req(source_cid);
+ }
+ L2CAP_PSM_HID_INTERRUPT => {
+ self.host_hid_interrupt_cid = Some(source_cid);
+ tracing::debug!(
+ host_cid = format!("{source_cid:#06x}"),
+ "guest connected Wiimote HID interrupt channel"
+ );
+
+ self.queue_l2cap_connect_rsp(ident, source_cid, L2CAP_CID_HID_INTERRUPT, 0);
+ self.queue_l2cap_config_req(source_cid);
+ }
+ _ => {
+ tracing::debug!(psm = format!("{psm:#06x}"), "rejected unknown L2CAP PSM");
+ self.queue_l2cap_connect_rsp(ident, source_cid, 0, 2);
+ }
+ }
+ }
+ L2CAP_CONNECT_RSP if data.len() >= 8 => {
+ let dest_cid = u16::from_le_bytes([data[0], data[1]]);
+ let source_cid = u16::from_le_bytes([data[2], data[3]]);
+ let result = u16::from_le_bytes([data[4], data[5]]);
+ let status = u16::from_le_bytes([data[6], data[7]]);
+
+ if result == 0 {
+ if source_cid == L2CAP_CID_HID_CONTROL {
+ self.host_hid_control_cid = Some(dest_cid);
+ } else if source_cid == L2CAP_CID_HID_INTERRUPT {
+ self.host_hid_interrupt_cid = Some(dest_cid);
+ }
+
+ tracing::debug!(
+ source_cid = format!("{source_cid:#06x}"),
+ dest_cid = format!("{dest_cid:#06x}"),
+ "Wiimote L2CAP channel connected"
+ );
+
+ self.queue_l2cap_config_req(source_cid);
+ } else {
+ tracing::warn!(
+ source_cid = format!("{source_cid:#06x}"),
+ dest_cid = format!("{dest_cid:#06x}"),
+ result = format!("{result:#06x}"),
+ status = format!("{status:#06x}"),
+ "guest rejected Wiimote L2CAP connect request"
+ );
+ }
+ }
+ L2CAP_CONFIG_REQ if data.len() >= 4 => {
+ let channel = u16::from_le_bytes([data[0], data[1]]);
+ self.queue_l2cap_config_rsp(ident, channel);
+ }
+ L2CAP_CONFIG_RSP if data.len() >= 2 => {
+ let channel = u16::from_le_bytes([data[0], data[1]]);
+ if Some(channel) == self.host_hid_interrupt_cid {
+ tracing::debug!("Wiimote HID interrupt channel configured");
+ let report = self.wiimote.make_input_report();
+ self.queue_hid_input_report(report);
+ } else if Some(channel) == self.host_hid_control_cid {
+ tracing::debug!("Wiimote HID control channel configured");
+ if self.host_hid_interrupt_cid.is_none() {
+ self.queue_l2cap_connect_request(L2CAP_PSM_HID_INTERRUPT, L2CAP_CID_HID_INTERRUPT);
+ }
+ }
+ }
+ L2CAP_DISCONNECT_REQ => tracing::debug!("ignored Wiimote L2CAP disconnect request"),
+ _ => tracing::debug!(code = format!("{code:#04x}"), "ignored L2CAP signaling command"),
+ }
+
+ payload = &payload[4 + len..];
+ }
+ }
+
+ fn handle_wiimote_hid(&mut self, payload: &[u8]) {
+ if payload.len() < 2 {
+ return;
+ }
+
+ for report in self.wiimote.handle_output_report(payload) {
+ self.queue_hid_input_report(report);
+ }
+ }
+
+ pub(super) fn queue_hid_input_report(&mut self, report: Vec<u8>) {
+ tracing::debug!(
+ bytes = format!("{report:02X?}"),
+ "sending Wiimote input report to guest"
+ );
+
+ let cid = self.host_hid_interrupt_cid.unwrap_or(L2CAP_CID_HID_INTERRUPT);
+ self.queue_acl_l2cap(cid, &report);
+ }
+
+ fn queue_l2cap_connect_rsp(&mut self, ident: u8, source_cid: u16, dest_cid: u16, result: u16) {
+ let mut payload = Vec::with_capacity(12);
+ payload.extend_from_slice(&[L2CAP_CONNECT_RSP, ident, 0x08, 0x00]);
+ payload.extend_from_slice(&dest_cid.to_le_bytes());
+ payload.extend_from_slice(&source_cid.to_le_bytes());
+ payload.extend_from_slice(&result.to_le_bytes());
+ payload.extend_from_slice(&[0x00, 0x00]);
+ self.queue_acl_l2cap(L2CAP_CID_SIGNALING, &payload);
+ }
+
+ pub(super) fn queue_l2cap_connect_request(&mut self, psm: u16, source_cid: u16) {
+ let ident = self.next_l2cap_ident();
+ let mut payload = Vec::with_capacity(8);
+ payload.extend_from_slice(&[L2CAP_CONNECT_REQ, ident, 0x04, 0x00]);
+ payload.extend_from_slice(&psm.to_le_bytes());
+ payload.extend_from_slice(&source_cid.to_le_bytes());
+ self.queue_acl_l2cap(L2CAP_CID_SIGNALING, &payload);
+ }
+
+ fn queue_l2cap_config_req(&mut self, channel: u16) {
+ let ident = self.next_l2cap_ident();
+ let mut payload = Vec::with_capacity(12);
+ payload.extend_from_slice(&[L2CAP_CONFIG_REQ, ident, 0x08, 0x00]);
+ payload.extend_from_slice(&channel.to_le_bytes());
+ payload.extend_from_slice(&[0x00, 0x00, 0x01, 0x02, 0xB9, 0x00]);
+ self.queue_acl_l2cap(L2CAP_CID_SIGNALING, &payload);
+ }
+
+ fn queue_l2cap_config_rsp(&mut self, ident: u8, channel: u16) {
+ let mut payload = Vec::with_capacity(18);
+ payload.extend_from_slice(&[L2CAP_CONFIG_RSP, ident, 0x0E, 0x00]);
+ payload.extend_from_slice(&channel.to_le_bytes());
+ payload.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x80, 0x02, 0x02, 0x02, 0xFF, 0xFF]);
+ self.queue_acl_l2cap(L2CAP_CID_SIGNALING, &payload);
+ }
+
+ fn queue_acl_l2cap(&mut self, cid: u16, payload: &[u8]) {
+ let l2cap_len = payload.len() as u16;
+ let acl_len = l2cap_len + 4;
+ let mut frame = Vec::with_capacity(8 + payload.len());
+ frame.extend_from_slice(&[0x00, 0x21]);
+ frame.extend_from_slice(&acl_len.to_le_bytes());
+ frame.extend_from_slice(&l2cap_len.to_le_bytes());
+ frame.extend_from_slice(&cid.to_le_bytes());
+ frame.extend_from_slice(payload);
+ tracing::debug!(bytes = format!("{frame:02X?}"), "queued Bluetooth ACL frame");
+ super::push_capped(&mut self.pending_acl, frame);
+ }
+
+ fn next_l2cap_ident(&mut self) -> u8 {
+ let ident = self.next_l2cap_ident;
+ self.next_l2cap_ident = self.next_l2cap_ident.wrapping_add(1).max(1);
+ ident
+ }
+}
diff --git a/crates/gecko/src/hollywood/ipc/usb/wiimote.rs b/crates/gecko/src/hollywood/ipc/usb/wiimote.rs
new file mode 100644
index 0000000..ee36d16
--- /dev/null
+++ b/crates/gecko/src/hollywood/ipc/usb/wiimote.rs
@@ -0,0 +1,521 @@
+pub const BTN_TWO: u16 = 0x0001;
+pub const BTN_ONE: u16 = 0x0002;
+pub const BTN_B: u16 = 0x0004;
+pub const BTN_A: u16 = 0x0008;
+pub const BTN_MINUS: u16 = 0x0010;
+pub const BTN_HOME: u16 = 0x0080;
+pub const BTN_LEFT: u16 = 0x0100;
+pub const BTN_RIGHT: u16 = 0x0200;
+pub const BTN_DOWN: u16 = 0x0400;
+pub const BTN_UP: u16 = 0x0800;
+pub const BTN_PLUS: u16 = 0x1000;
+
+pub const NUNCHUK_BTN_C: u8 = 0x02;
+pub const NUNCHUK_BTN_Z: u8 = 0x01;
+
+const HID_PREFIX_INPUT: u8 = 0xA1;
+const HID_PREFIX_OUTPUT: u8 = 0xA2;
+
+/// Output reports the host writes on the HID interrupt channel.
+/// Values per <https://wiibrew.org/wiki/Wiimote#Output_Reports>.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+enum OutputReportId {
+ Rumble = 0x10,
+ PlayerLeds = 0x11,
+ DataReportingMode = 0x12,
+ IrCameraEnable = 0x13,
+ SpeakerEnable = 0x14,
+ StatusInformationRequest = 0x15,
+ WriteMemoryAndRegisters = 0x16,
+ ReadMemoryAndRegisters = 0x17,
+ SpeakerData = 0x18,
+ SpeakerMute = 0x19,
+ IrCameraEnable2 = 0x1A,
+}
+
+impl OutputReportId {
+ fn from_u8(id: u8) -> Option<Self> {
+ Some(match id {
+ 0x10 => Self::Rumble,
+ 0x11 => Self::PlayerLeds,
+ 0x12 => Self::DataReportingMode,
+ 0x13 => Self::IrCameraEnable,
+ 0x14 => Self::SpeakerEnable,
+ 0x15 => Self::StatusInformationRequest,
+ 0x16 => Self::WriteMemoryAndRegisters,
+ 0x17 => Self::ReadMemoryAndRegisters,
+ 0x18 => Self::SpeakerData,
+ 0x19 => Self::SpeakerMute,
+ 0x1A => Self::IrCameraEnable2,
+ _ => return None,
+ })
+ }
+}
+
+/// Data reporting modes the host selects via `DataReportingMode (0x12)`.
+/// Values and layouts per <https://wiibrew.org/wiki/Wiimote#Data_Reporting>.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+enum ReportMode {
+ /// Core buttons only.
+ Core = 0x30,
+ /// Core + 3-byte accelerometer.
+ CoreAccel = 0x31,
+ /// Core + 8-byte extension.
+ CoreExt8 = 0x32,
+ /// Core + accel + 12-byte IR.
+ CoreAccelIrExt = 0x33,
+ /// Core + 19-byte extension.
+ CoreExt19 = 0x34,
+ /// Core + accel + 16-byte extension.
+ CoreAccelExt16 = 0x35,
+ /// Core + accel + 10-byte basic IR + 6-byte extension.
+ CoreAccelIrBasicExt = 0x36,
+ /// Core + accel + 10-byte basic IR + 6-byte extension (alternate framing).
+ CoreAccelIrFullExt = 0x37,
+}
+
+impl ReportMode {
+ fn from_u8(mode: u8) -> Option<Self> {
+ Some(match mode {
+ 0x30 => Self::Core,
+ 0x31 => Self::CoreAccel,
+ 0x32 => Self::CoreExt8,
+ 0x33 => Self::CoreAccelIrExt,
+ 0x34 => Self::CoreExt19,
+ 0x35 => Self::CoreAccelExt16,
+ 0x36 => Self::CoreAccelIrBasicExt,
+ 0x37 => Self::CoreAccelIrFullExt,
+ _ => return None,
+ })
+ }
+}
+
+const WIIMOTE_EEPROM_SIZE: usize = 0x1700;
+const WIIMOTE_EEPROM_CALIBRATION: [u8; 42] = [
+ // IR sensor calibration #1 (0x00..0x0B): 4 reference dot positions + checksum
+ 0x7F, 0x5D, 0x03, 0x80, 0x5D, 0x80, 0xA2, 0xB8, 0x7F, 0xA2, 0x0C,
+ // IR sensor calibration #2 (0x0B..0x16): duplicate
+ 0x7F, 0x5D, 0x03, 0x80, 0x5D, 0x80, 0xA2, 0xB8, 0x7F, 0xA2, 0x0C,
+ // Accel calibration #1 (0x16..0x20)
+ 0x80, 0x80, 0x80, 0x00, // accel zero G (X, Y, Z, padding)
+ 0x9A, 0x9A, 0x9A, 0x00, // accel one G (X, Y, Z, padding)
+ 0x00, 0xA3, // padding, checksum
+ // Accel calibration #2 (0x20..0x2A): duplicate
+ 0x80, 0x80, 0x80, 0x00, 0x9A, 0x9A, 0x9A, 0x00, 0x00, 0xA3,
+];
+
+const NUNCHUK_ID: [u8; 6] = [0x00, 0x00, 0xA4, 0x20, 0x00, 0x00];
+const NUNCHUK_CALIBRATION: [u8; 16] = [
+ 0x80, 0x80, 0x80, 0x00, // accel zero G (X, Y, Z, padding)
+ 0xB3, 0xB3, 0xB3, 0x00, // accel one G (X, Y, Z, padding)
+ 0xFF, 0x00, 0x80, // stick X max, min, center
+ 0xFF, 0x00, 0x80, // stick Y max, min, center
+ 0x00, 0x00, // checksum (filled below at runtime)
+];
+
+#[derive(Debug, Clone)]
+pub(super) struct WiimoteState {
+ buttons: u16,
+ report_mode: ReportMode,
+ continuous: bool,
+ leds: u8,
+ ir_enabled_pin1: bool,
+ ir_enabled_pin2: bool,
+ eeprom: Vec<u8>,
+ nunchuk_attached: bool,
+ nunchuk_buttons: u8,
+ nunchuk_stick_x: u8,
+ nunchuk_stick_y: u8,
+ nunchuk_calibration: [u8; 16],
+}
+
+impl Default for WiimoteState {
+ fn default() -> Self {
+ let mut eeprom = vec![0u8; WIIMOTE_EEPROM_SIZE];
+ eeprom[0..WIIMOTE_EEPROM_CALIBRATION.len()].copy_from_slice(&WIIMOTE_EEPROM_CALIBRATION);
+
+ let mut nunchuk_calibration = NUNCHUK_CALIBRATION;
+ let (a, b) = self::compute_calibration_checksum(&nunchuk_calibration[..14]);
+ nunchuk_calibration[14] = a;
+ nunchuk_calibration[15] = b;
+
+ Self {
+ buttons: 0,
+ report_mode: ReportMode::Core,
+ continuous: false,
+ leds: 0,
+ ir_enabled_pin1: false,
+ ir_enabled_pin2: false,
+ eeprom,
+ nunchuk_attached: true,
+ nunchuk_buttons: 0,
+ nunchuk_stick_x: 0x80,
+ nunchuk_stick_y: 0x80,
+ nunchuk_calibration,
+ }
+ }
+}
+
+impl WiimoteState {
+ pub(super) fn set_buttons(&mut self, buttons: u16) -> bool {
+ let old = self.buttons;
+ self.buttons = buttons;
+ self.buttons != old
+ }
+
+ pub(super) fn set_nunchuk(&mut self, buttons: u8, stick_x: u8, stick_y: u8) -> bool {
+ let changed =
+ self.nunchuk_buttons != buttons || self.nunchuk_stick_x != stick_x || self.nunchuk_stick_y != stick_y;
+ self.nunchuk_buttons = buttons;
+ self.nunchuk_stick_x = stick_x;
+ self.nunchuk_stick_y = stick_y;
+ changed
+ }
+
+ fn button_bytes(&self) -> [u8; 2] {
+ self.buttons.to_be_bytes()
+ }
+
+ pub(super) fn make_input_report(&self) -> Vec<u8> {
+ let [bb0, bb1] = self.button_bytes();
+ let accel = [0x80u8, 0x80, 0xB3]; // X=0G, Y=0G, Z=+1G (gravity)
+ let ir_basic = [0xFF; 10];
+ let ir_extended = [0xFF; 12];
+ let mode = self.report_mode;
+
+ let mut r = vec![HID_PREFIX_INPUT, mode as u8, bb0, bb1];
+ match mode {
+ ReportMode::Core => {}
+ ReportMode::CoreAccel => r.extend_from_slice(&accel),
+ ReportMode::CoreExt8 => self.append_nunchuk_ext_padded(&mut r, 8),
+ ReportMode::CoreAccelIrExt => {
+ r.extend_from_slice(&accel);
+ r.extend_from_slice(&ir_extended);
+ }
+ ReportMode::CoreExt19 => self.append_nunchuk_ext_padded(&mut r, 19),
+ ReportMode::CoreAccelExt16 => {
+ r.extend_from_slice(&accel);
+ self.append_nunchuk_ext_padded(&mut r, 16);
+ }
+ ReportMode::CoreAccelIrBasicExt => {
+ r.extend_from_slice(&accel);
+ r.extend_from_slice(&ir_basic);
+ r.extend_from_slice(&self.nunchuk_extension_bytes());
+ }
+ ReportMode::CoreAccelIrFullExt => {
+ r.extend_from_slice(&accel);
+ r.extend_from_slice(&ir_extended);
+ r.extend_from_slice(&self.nunchuk_extension_bytes());
+ }
+ }
+ r
+ }
+
+ /// 6 extension bytes encoding the nunchuk's stick + accel + button state.
+ /// Per <https://wiibrew.org/wiki/Wiimote/Extension_Controllers/Nunchuk>.
+ fn nunchuk_extension_bytes(&self) -> [u8; 6] {
+ if !self.nunchuk_attached {
+ return [0xFF; 6];
+ }
+
+ // Bits 0,1 of the trailing byte are inverted: 1 = button NOT pressed.
+ let inv_buttons = (!self.nunchuk_buttons) & 0x03;
+ [
+ self.nunchuk_stick_x,
+ self.nunchuk_stick_y,
+ 0x80, // accel X high bits (zero G)
+ 0x80, // accel Y high bits (zero G)
+ 0xB3, // accel Z high bits (+1G gravity)
+ inv_buttons,
+ ]
+ }
+
+ /// Append the 6-byte nunchuk extension followed by 0xFF padding so the
+ /// report's extension slot is exactly `total_len` bytes.
+ fn append_nunchuk_ext_padded(&self, out: &mut Vec<u8>, total_len: usize) {
+ let target = out.len() + total_len;
+ out.extend_from_slice(&self.nunchuk_extension_bytes());
+ out.resize(target, 0xFF);
+ }
+
+ pub(super) fn handle_output_report(&mut self, packet: &[u8]) -> Vec<Vec<u8>> {
+ if packet.len() < 2 {
+ return Vec::new();
+ }
+
+ if packet[0] != HID_PREFIX_OUTPUT {
+ tracing::warn!(
+ packet = format!("{packet:02X?}"),
+ "unexpected Wiimote output packet prefix"
+ );
+ return Vec::new();
+ }
+
+ let raw_id = packet[1];
+ let body = &packet[2..];
+
+ let Some(report_id) = OutputReportId::from_u8(raw_id) else {
+ tracing::warn!(report_id = format!("{raw_id:#04x}"), "ignored Wiimote output report");
+ return Vec::new();
+ };
+
+ tracing::debug!(report_id = ?report_id, "received Wiimote output report");
+
+ match report_id {
+ OutputReportId::Rumble
+ | OutputReportId::SpeakerEnable
+ | OutputReportId::SpeakerData
+ | OutputReportId::SpeakerMute => self::trivial_ack(self.button_bytes(), raw_id),
+ OutputReportId::PlayerLeds => {
+ self.leds = body.first().copied().unwrap_or(0) >> 4;
+ self::trivial_ack(self.button_bytes(), raw_id)
+ }
+ OutputReportId::DataReportingMode if body.len() >= 2 => {
+ self.continuous = (body[0] & 0x04) != 0;
+ let Some(mode) = ReportMode::from_u8(body[1]) else {
+ tracing::warn!(
+ report_mode = format!("{:#04x}", body[1]),
+ "unsupported Wiimote report mode, ignoring"
+ );
+ return self::trivial_ack(self.button_bytes(), raw_id);
+ };
+ self.report_mode = mode;
+
+ tracing::debug!(
+ report_mode = ?mode,
+ continuous = self.continuous,
+ "Wiimote data reporting mode selected"
+ );
+
+ self::trivial_ack(self.button_bytes(), raw_id)
+ }
+ OutputReportId::IrCameraEnable => {
+ self.ir_enabled_pin1 = body.first().is_some_and(|&b| (b & 0x04) != 0);
+ self::trivial_ack(self.button_bytes(), raw_id)
+ }
+ OutputReportId::StatusInformationRequest => {
+ tracing::debug!("Wiimote status requested");
+ vec![self.make_status_report()]
+ }
+ OutputReportId::WriteMemoryAndRegisters if body.len() >= 5 => {
+ let address = self::decode_mem_address(body);
+
+ tracing::debug!(addr = format!("{address:#08x}"), "Wiimote write memory");
+
+ let address_space = body[0] & 0x06;
+ let size = body[4] as usize;
+
+ if address_space == 0 {
+ let payload = &body[5..5 + size.min(body.len().saturating_sub(5)).min(16)];
+ let end = (address as usize + payload.len()).min(self.eeprom.len());
+ let dst = &mut self.eeprom[address as usize..end];
+ dst.copy_from_slice(&payload[..dst.len()]);
+ }
+
+ self::trivial_ack(self.button_bytes(), raw_id)
+ }
+ OutputReportId::ReadMemoryAndRegisters if body.len() >= 6 => {
+ let address_space = body[0] & 0x06;
+ let address = self::decode_mem_address(body);
+ let size = u16::from_be_bytes([body[4], body[5]]) as usize;
+
+ tracing::debug!(
+ addr = format!("{address:#08x}"),
+ size,
+ space = address_space,
+ "Wiimote read memory"
+ );
+
+ self.read_memory_response(address_space, address, size)
+ }
+ OutputReportId::IrCameraEnable2 => {
+ self.ir_enabled_pin2 = body.first().is_some_and(|&b| (b & 0x04) != 0);
+ self::trivial_ack(self.button_bytes(), raw_id)
+ }
+ // Body too short for the variant's required fields.
+ _ => Vec::new(),
+ }
+ }
+
+ fn read_memory_response(&self, address_space: u8, address: u32, size: usize) -> Vec<Vec<u8>> {
+ if address_space != 0 {
+ return self.read_register_response(address, size);
+ }
+
+ let start = address as usize;
+ let end = start + size;
+ if end > self.eeprom.len() {
+ return vec![self.read_chunk_report(address as u16, &[], 0x08)];
+ }
+
+ let mut out = Vec::new();
+ let mut offset = 0usize;
+ while offset < size {
+ let chunk = (size - offset).min(16);
+ let chunk_addr = address as u16 + offset as u16;
+ out.push(self.read_chunk_report(chunk_addr, &self.eeprom[start + offset..start + offset + chunk], 0));
+
+ offset += chunk;
+ }
+
+ out
+ }
+
+ fn read_register_response(&self, address: u32, size: usize) -> Vec<Vec<u8>> {
+ let canonical = address & 0x00FFFFFF;
+
+ if !self.nunchuk_attached {
+ tracing::debug!(
+ addr = format!("{address:#08x}"),
+ "register read with no extension; returning no-peripheral error"
+ );
+
+ return vec![self.read_chunk_report(address as u16, &[], 0x07)];
+ }
+
+ let mut backing = [0u8; 0x100];
+ backing[0x20..0x30].copy_from_slice(&self.nunchuk_calibration);
+ backing[0xFA..0x100].copy_from_slice(&NUNCHUK_ID);
+
+ let base = (canonical & 0xFF) as usize;
+
+ let mut out = Vec::new();
+ let mut offset = 0usize;
+ while offset < size {
+ let chunk = (size - offset).min(16);
+ let start = base + offset;
+ let end = start + chunk;
+
+ if end > backing.len() {
+ out.push(self.read_chunk_report((address as u16) + offset as u16, &[], 0x08));
+ break;
+ }
+
+ out.push(self.read_chunk_report((address as u16) + offset as u16, &backing[start..end], 0));
+
+ offset += chunk;
+ }
+ out
+ }
+
+ fn read_chunk_report(&self, address: u16, data: &[u8], error: u8) -> Vec<u8> {
+ let [bb0, bb1] = self.button_bytes();
+ let chunk_len = data.len().min(16);
+ let size_and_error = if chunk_len == 0 {
+ error & 0x0F
+ } else {
+ (((chunk_len as u8 - 1) & 0x0F) << 4) | (error & 0x0F)
+ };
+
+ let mut report = Vec::with_capacity(22);
+ report.extend_from_slice(&[HID_PREFIX_INPUT, 0x21, bb0, bb1, size_and_error]);
+ report.extend_from_slice(&address.to_be_bytes());
+ report.extend_from_slice(&data[..chunk_len]);
+
+ for _ in chunk_len..16 {
+ report.push(0);
+ }
+
+ report
+ }
+
+ fn make_status_report(&self) -> Vec<u8> {
+ let [bb0, bb1] = self.button_bytes();
+ let ir_enabled = self.ir_enabled_pin1 && self.ir_enabled_pin2;
+ let mut flags = self.leds << 4;
+
+ if ir_enabled {
+ flags |= 0x08;
+ }
+
+ if self.nunchuk_attached {
+ flags |= 0x02; // extension connected
+ }
+
+ vec![HID_PREFIX_INPUT, 0x20, bb0, bb1, flags, 0x00, 0x00, 0x64]
+ }
+}
+
+fn compute_calibration_checksum(data: &[u8]) -> (u8, u8) {
+ // Per wiibrew: first byte = sum + 0x55, second byte = sum + 0xAA.
+ let mut sum: u8 = 0;
+ for &b in data {
+ sum = sum.wrapping_add(b);
+ }
+ (sum.wrapping_add(0x55), sum.wrapping_add(0xAA))
+}
+
+#[inline(always)]
+fn decode_mem_address(body: &[u8]) -> u32 {
+ ((body[1] as u32) << 16) | ((body[2] as u32) << 8) | (body[3] as u32)
+}
+
+#[inline(always)]
+fn trivial_ack(button_bytes: [u8; 2], report_id: u8) -> Vec<Vec<u8>> {
+ vec![vec![
+ HID_PREFIX_INPUT,
+ 0x22,
+ button_bytes[0],
+ button_bytes[1],
+ report_id,
+ 0x00,
+ ]]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn core_button_report_encodes_a_press_and_release() {
+ let mut wiimote = WiimoteState::default();
+
+ assert!(wiimote.set_buttons(BTN_A));
+ assert_eq!(wiimote.make_input_report(), [0xA1, 0x30, 0x00, 0x08]);
+
+ assert!(wiimote.set_buttons(0));
+ assert_eq!(wiimote.make_input_report(), [0xA1, 0x30, 0x00, 0x00]);
+ }
+
+ #[test]
+ fn data_reporting_mode_selects_extended_minimal_reports() {
+ let mut wiimote = WiimoteState::default();
+
+ assert!(wiimote.set_buttons(BTN_A));
+ let acks = wiimote.handle_output_report(&[0xA2, 0x12, 0x04, 0x31]);
+ assert_eq!(acks, vec![vec![0xA1, 0x22, 0x00, 0x08, 0x12, 0x00]]);
+ assert!(wiimote.continuous);
+ assert_eq!(wiimote.make_input_report(), [0xA1, 0x31, 0x00, 0x08, 0x80, 0x80, 0xB3]);
+
+ let acks = wiimote.handle_output_report(&[0xA2, 0x12, 0x00, 0x33]);
+ assert_eq!(acks, vec![vec![0xA1, 0x22, 0x00, 0x08, 0x12, 0x00]]);
+ let mut expected = vec![0xA1, 0x33, 0x00, 0x08, 0x80, 0x80, 0xB3];
+ expected.extend_from_slice(&[0xFF; 12]);
+ assert_eq!(wiimote.make_input_report(), expected);
+ }
+
+ #[test]
+ fn read_memory_returns_chunked_calibration_data() {
+ let mut wiimote = WiimoteState::default();
+ let reports = wiimote.handle_output_report(&[0xA2, 0x17, 0x00, 0x00, 0x00, 0x16, 0x00, 0x10]);
+ assert_eq!(reports.len(), 1);
+ let r = &reports[0];
+ assert_eq!(&r[0..2], &[0xA1, 0x21]);
+ assert_eq!(r[4], 0xF0); // 16 bytes - 1 = 0x0F, shifted into upper nibble
+ assert_eq!(&r[5..7], &[0x00, 0x16]);
+ assert_eq!(&r[7..23], &WIIMOTE_EEPROM_CALIBRATION[22..38]);
+ }
+
+ #[test]
+ fn unsupported_report_mode_is_rejected_and_kept_at_previous() {
+ let mut wiimote = WiimoteState::default();
+ // Pin a known mode first.
+ wiimote.handle_output_report(&[0xA2, 0x12, 0x00, 0x31]);
+ assert_eq!(wiimote.report_mode, ReportMode::CoreAccel);
+ // Reject unknown mode 0x3D and stay on 0x31.
+ wiimote.handle_output_report(&[0xA2, 0x12, 0x00, 0x3D]);
+ assert_eq!(wiimote.report_mode, ReportMode::CoreAccel);
+ }
+}
diff --git a/crates/gecko/src/input.rs b/crates/gecko/src/input.rs
new file mode 100644
index 0000000..4693fd3
--- /dev/null
+++ b/crates/gecko/src/input.rs
@@ -0,0 +1,38 @@
+use crate::{SystemId, flipper::si::pad, WII, GC};
+
+#[derive(Clone, Copy, Debug)]
+pub enum HostInput {
+ Gc(pad::PadStatus),
+ Wii {
+ wiimote_buttons: u16,
+ nunchuk_buttons: u8,
+ nunchuk_stick_x: u8,
+ nunchuk_stick_y: u8,
+ },
+}
+
+impl HostInput {
+ pub fn gc_connected() -> Self {
+ Self::Gc(pad::PadStatus {
+ connected: true,
+ ..pad::PadStatus::default()
+ })
+ }
+
+ pub fn wii_neutral() -> Self {
+ Self::Wii {
+ wiimote_buttons: 0,
+ nunchuk_buttons: 0,
+ nunchuk_stick_x: 0x80,
+ nunchuk_stick_y: 0x80,
+ }
+ }
+
+ pub fn neutral_for(system: SystemId) -> Self {
+ match system {
+ WII => Self::wii_neutral(),
+ GC => Self::gc_connected(),
+ _ => unreachable!(),
+ }
+ }
+}
\ No newline at end of file
diff --git a/crates/gecko/src/lib.rs b/crates/gecko/src/lib.rs
index b044112..70cf576 100644
--- a/crates/gecko/src/lib.rs
+++ b/crates/gecko/src/lib.rs
@@ -13,10 +13,12 @@ pub mod scheduler;
pub mod starlet;
pub mod system;
pub mod wii;
+pub mod input;
pub use gamecube::GameCube;
pub use system::{GC, System, SystemId, WII};
pub use wii::Wii;
+pub use input::HostInput;
#[cfg(feature = "hooks")]
pub mod hooks;
diff --git a/crates/gecko/src/starlet.rs b/crates/gecko/src/starlet.rs
index d2cd55c..271beed 100644
--- a/crates/gecko/src/starlet.rs
+++ b/crates/gecko/src/starlet.rs
@@ -90,6 +90,18 @@ impl Starlet {
}
}
+ pub fn set_wiimote_buttons(&mut self, buttons: u16) -> bool {
+ self.devices
+ .get_mut("/dev/usb/oh1/57e/305")
+ .is_some_and(|dev| dev.set_wiimote_buttons(buttons))
+ }
+
+ pub fn set_nunchuk(&mut self, buttons: u8, stick_x: u8, stick_y: u8) -> bool {
+ self.devices
+ .get_mut("/dev/usb/oh1/57e/305")
+ .is_some_and(|dev| dev.set_nunchuk(buttons, stick_x, stick_y))
+ }
+
/// Drop an fd. Calls `close` on the underlying device first; for owned
/// fds the device is dropped after close.
pub fn close_fd(&mut self, fd: i32, ctx: &mut DeviceContext<'_>) -> i32 {
@@ -121,6 +133,8 @@ impl System<{ crate::WII }> {
self.starlet.register("/dev/stm/immediate", Box::new(stm::Immediate));
self.starlet.register("/dev/stm/eventhook", Box::new(stm::EventHook));
self.starlet.register("/dev/fs", Box::new(ipc::fs::FileSystem));
+ self.starlet
+ .register("/shared2/sys/SYSCONF", Box::new(ipc::sysconf::SysConf::new()));
self.starlet
.register("/dev/di", Box::new(ipc::di::DiskInterface::new()));
self.starlet.register("/dev/es", Box::new(ipc::es::ETicketServices));
diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rs
index 7bb549f..aac6bf7 100644
--- a/crates/gecko/src/system.rs
+++ b/crates/gecko/src/system.rs
@@ -1,3 +1,4 @@
+use crate::HostInput;
use crate::audio::{AudioSink, EmptyAudioSink};
use crate::dvd::DvdInterface;
use crate::flipper::ai::AudioInterface;
@@ -8,7 +9,7 @@ use crate::flipper::gx::GraphicsProcessor;
use crate::flipper::mi::MemoryInterface;
use crate::flipper::pe::PixelEngine;
use crate::flipper::pi::ProcessorInterface;
-use crate::flipper::si::{SerialInterface, pad};
+use crate::flipper::si::SerialInterface;
use crate::flipper::vi::VideoInterface;
use crate::gekko::Gekko;
use crate::hollywood::Hollywood;
@@ -221,12 +222,23 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {
(fmt.columns(), fmt.lines())
}
- pub fn add_primary_controller(&mut self, input: pad::PadStatus) {
- self.si.pad_state[0] = input;
- }
-
- pub fn primary_controller_mut(&mut self) -> &mut pad::PadStatus {
- &mut self.si.pad_state[0]
+ pub fn apply_host_input(&mut self, input: &HostInput) {
+ match input {
+ HostInput::Gc(pad) if SYSTEM == GC => {
+ self.si.pad_state[0] = *pad;
+ }
+ HostInput::Wii {
+ wiimote_buttons,
+ nunchuk_buttons,
+ nunchuk_stick_x,
+ nunchuk_stick_y,
+ } if SYSTEM == WII => {
+ self.starlet.set_wiimote_buttons(*wiimote_buttons);
+ self.starlet
+ .set_nunchuk(*nunchuk_buttons, *nunchuk_stick_x, *nunchuk_stick_y);
+ }
+ _ => unreachable!("invalid host input for system"),
+ }
}
#[inline(always)]
diff --git a/crates/screenshotter/src/main.rs b/crates/screenshotter/src/main.rs
index c493cdd..13b1b92 100644
--- a/crates/screenshotter/src/main.rs
+++ b/crates/screenshotter/src/main.rs
@@ -1,6 +1,6 @@
use backend_wgpu::{GxRenderer, capture};
+use gecko::HostInput;
use gecko::flipper::si::pad;
-use gecko::flipper::si::pad::PadStatus;
use gecko::flipper::vi::regs::RefreshRate;
use gecko::gamecube::GameCube;
use gecko::host::{GxAction, RenderSink};
@@ -216,15 +216,16 @@ fn run_one(device: &wgpu::Device, queue: &wgpu::Queue, surface_format: wgpu::Tex
let mut gamecube = GameCube::with_ipl(IPL, true);
gamecube.dsp.load_irom(DSP);
- gamecube.add_primary_controller(PadStatus {
- connected: true,
- ..Default::default()
- });
+
+ let mut input = HostInput::gc_connected();
+ gamecube.apply_host_input(&input);
+
gamecube.render_sink = Box::new(SyncSink {
gx: gx.clone(),
device: device.clone(),
queue: queue.clone(),
});
+
gamecube.insert_dvd(image);
let framerate = match gamecube.vi.dcr.video_format().refresh_rate() {
@@ -244,8 +245,7 @@ fn run_one(device: &wgpu::Device, queue: &wgpu::Queue, surface_format: wgpu::Tex
}
for idx in 0..20 {
- {
- let pad = gamecube.primary_controller_mut();
+ if let HostInput::Gc(pad) = &mut input {
pad.stick_y = pad::STICK_CENTER;
pad.buttons = 0;
@@ -255,6 +255,7 @@ fn run_one(device: &wgpu::Device, queue: &wgpu::Queue, surface_format: wgpu::Tex
pad.buttons = pad::A | pad::START;
}
}
+ gamecube.apply_host_input(&input);
for _ in 0..(framerate * 2) {
gamecube.run_until_vsync();
diff --git a/crates/tinyapp/src/app.rs b/crates/tinyapp/src/app.rs
index 6fa22ee..b6ce927 100644
--- a/crates/tinyapp/src/app.rs
+++ b/crates/tinyapp/src/app.rs
@@ -2,13 +2,14 @@ use crate::thread::FrameMessage;
use backend_wgpu::capture::{self, CaptureRequest, ScreenshotControl};
use crossbeam_channel::Receiver;
use egui::ViewportId;
-use gecko::flipper::si::pad::PadStatus;
+use gecko::HostInput;
+use gecko::hollywood::ipc::usb;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use winit::application::ApplicationHandler;
-use winit::event::WindowEvent;
+use winit::event::{MouseButton, WindowEvent};
use winit::event_loop::ActiveEventLoop;
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::{Window, WindowId};
@@ -213,7 +214,7 @@ impl State {
pub struct App {
pub frame_rx: Receiver<FrameMessage>,
- pub input: Arc<Mutex<PadStatus>>,
+ pub input: Arc<Mutex<HostInput>>,
pub window: Option<Arc<Window>>,
pub state: Option<State>,
pub present_mode: wgpu::PresentMode,
@@ -314,8 +315,54 @@ impl ApplicationHandler for App {
}
}
}
- let mut pad = self.input.lock().unwrap();
- crate::update_pad(&mut pad, key, pressed);
+
+ let mut input = self.input.lock().unwrap();
+ match &mut *input {
+ HostInput::Gc(pad) => crate::update_pad(pad, key, pressed),
+ HostInput::Wii {
+ wiimote_buttons,
+ nunchuk_buttons,
+ nunchuk_stick_x,
+ nunchuk_stick_y,
+ } => {
+ crate::update_wiimote_keys(wiimote_buttons, key, pressed);
+ crate::update_nunchuk_keys(
+ nunchuk_buttons,
+ nunchuk_stick_x,
+ nunchuk_stick_y,
+ key,
+ pressed,
+ );
+ }
+ }
+ }
+ }
+ WindowEvent::MouseInput { state, button, .. } => {
+ let pressed = state.is_pressed();
+ let mask = match button {
+ MouseButton::Left => Some(usb::BTN_A),
+ MouseButton::Right => Some(usb::BTN_B),
+ _ => None,
+ };
+ if let Some(mask) = mask {
+ let mut input = self.input.lock().unwrap();
+
+ if let HostInput::Wii { wiimote_buttons, .. } = &mut *input {
+ let next = if pressed {
+ *wiimote_buttons | mask
+ } else {
+ *wiimote_buttons & !mask
+ };
+
+ if next != *wiimote_buttons {
+ *wiimote_buttons = next;
+ tracing::debug!(
+ mask = format!("{mask:#06x}"),
+ pressed,
+ "host mouse button mapped to Wiimote"
+ );
+ }
+ }
}
}
WindowEvent::RedrawRequested => {
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index a9a6583..601fa72 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -5,11 +5,13 @@ mod thread;
use backend_wgpu::sink::TargetAspect;
use clap::Parser;
use crossbeam_channel::bounded;
+use gecko::HostInput;
#[cfg(feature = "audio-wav-dump")]
use gecko::audio::WavAudioSink;
use gecko::audio::{AudioSink, EmptyAudioSink, MultiplexAudioSink};
use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER};
use gecko::gamecube::GameCube;
+use gecko::hollywood::ipc::usb as wiimote;
use gecko::system::{self, System, SystemId};
use gecko::wii::Wii;
use image::Dol;
@@ -181,10 +183,7 @@ fn configure<const SYSTEM: SystemId>(emulator: &mut System<SYSTEM>, args: &Args)
}
}
- emulator.add_primary_controller(PadStatus {
- connected: true,
- ..PadStatus::default()
- });
+ emulator.apply_host_input(&HostInput::neutral_for(SYSTEM));
}
fn run<const SYSTEM: SystemId>(mut emulator: System<SYSTEM>, present_mode: wgpu::PresentMode, args: &Args) {
@@ -217,7 +216,7 @@ fn run<const SYSTEM: SystemId>(mut emulator: System<SYSTEM>, present_mode: wgpu:
let audio_stream = install_audio_sink(args, &mut emulator);
- let input = Arc::new(Mutex::new(*emulator.primary_controller_mut()));
+ let input = Arc::new(Mutex::new(HostInput::neutral_for(SYSTEM)));
let (frame_tx, frame_rx) = bounded::<thread::FrameMessage>(2);
@@ -307,15 +306,20 @@ fn install_audio_sink<const SYSTEM: SystemId>(args: &Args, emulator: &mut System
stream
}
-fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {
- let set_button = |buttons: &mut u16, mask: u16, on: bool| {
- if on {
- *buttons |= mask;
- } else {
- *buttons &= !mask;
- }
- };
+#[inline(always)]
+fn set_bit<T: std::ops::BitOrAssign + std::ops::BitAndAssign + std::ops::Not<Output = T> + Copy>(
+ bits: &mut T,
+ mask: T,
+ on: bool,
+) {
+ if on {
+ *bits |= mask;
+ } else {
+ *bits &= !mask;
+ }
+}
+fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {
match key {
// Analog stick
KeyCode::ArrowUp => pad.stick_y = if pressed { 255 } else { STICK_CENTER },
@@ -324,29 +328,58 @@ fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {
KeyCode::ArrowRight => pad.stick_x = if pressed { 255 } else { STICK_CENTER },
// Face buttons
- KeyCode::KeyX => set_button(&mut pad.buttons, pad::A, pressed),
- KeyCode::KeyZ => set_button(&mut pad.buttons, pad::B, pressed),
- KeyCode::KeyC => set_button(&mut pad.buttons, pad::X, pressed),
- KeyCode::KeyV => set_button(&mut pad.buttons, pad::Y, pressed),
- KeyCode::Enter => set_button(&mut pad.buttons, pad::START, pressed),
+ KeyCode::KeyX => self::set_bit(&mut pad.buttons, pad::A, pressed),
+ KeyCode::KeyZ => self::set_bit(&mut pad.buttons, pad::B, pressed),
+ KeyCode::KeyC => self::set_bit(&mut pad.buttons, pad::X, pressed),
+ KeyCode::KeyV => self::set_bit(&mut pad.buttons, pad::Y, pressed),
+ KeyCode::Enter => self::set_bit(&mut pad.buttons, pad::START, pressed),
// Triggers
KeyCode::KeyA => {
- set_button(&mut pad.buttons, pad::L, pressed);
+ self::set_bit(&mut pad.buttons, pad::L, pressed);
pad.trigger_left = if pressed { 255 } else { 0 };
}
KeyCode::KeyS => {
- set_button(&mut pad.buttons, pad::R, pressed);
+ self::set_bit(&mut pad.buttons, pad::R, pressed);
pad.trigger_right = if pressed { 255 } else { 0 };
}
- KeyCode::KeyD => set_button(&mut pad.buttons, pad::Z, pressed),
+ KeyCode::KeyD => self::set_bit(&mut pad.buttons, pad::Z, pressed),
// D-pad
- KeyCode::KeyI => set_button(&mut pad.buttons, pad::DPAD_UP, pressed),
- KeyCode::KeyK => set_button(&mut pad.buttons, pad::DPAD_DOWN, pressed),
- KeyCode::KeyJ => set_button(&mut pad.buttons, pad::DPAD_LEFT, pressed),
- KeyCode::KeyL => set_button(&mut pad.buttons, pad::DPAD_RIGHT, pressed),
+ KeyCode::KeyI => self::set_bit(&mut pad.buttons, pad::DPAD_UP, pressed),
+ KeyCode::KeyK => self::set_bit(&mut pad.buttons, pad::DPAD_DOWN, pressed),
+ KeyCode::KeyJ => self::set_bit(&mut pad.buttons, pad::DPAD_LEFT, pressed),
+ KeyCode::KeyL => self::set_bit(&mut pad.buttons, pad::DPAD_RIGHT, pressed),
_ => {}
}
}
+
+pub fn update_wiimote_keys(buttons: &mut u16, key: KeyCode, pressed: bool) {
+ let mask = match key {
+ KeyCode::Digit1 => wiimote::BTN_ONE,
+ KeyCode::Digit2 => wiimote::BTN_TWO,
+ KeyCode::Home => wiimote::BTN_HOME,
+ KeyCode::Minus => wiimote::BTN_MINUS,
+ KeyCode::Equal => wiimote::BTN_PLUS,
+ KeyCode::ArrowUp => wiimote::BTN_UP,
+ KeyCode::ArrowDown => wiimote::BTN_DOWN,
+ KeyCode::ArrowLeft => wiimote::BTN_LEFT,
+ KeyCode::ArrowRight => wiimote::BTN_RIGHT,
+ _ => return,
+ };
+ self::set_bit(buttons, mask, pressed);
+}
+
+pub fn update_nunchuk_keys(buttons: &mut u8, stick_x: &mut u8, stick_y: &mut u8, key: KeyCode, pressed: bool) {
+ const NEUTRAL: u8 = 0x80;
+ match key {
+ KeyCode::KeyW => *stick_y = if pressed { 0xFF } else { NEUTRAL },
+ KeyCode::KeyS => *stick_y = if pressed { 0x00 } else { NEUTRAL },
+ KeyCode::KeyA => *stick_x = if pressed { 0x00 } else { NEUTRAL },
+ KeyCode::KeyD => *stick_x = if pressed { 0xFF } else { NEUTRAL },
+ KeyCode::KeyQ => self::set_bit(buttons, wiimote::NUNCHUK_BTN_Z, pressed),
+ KeyCode::KeyE => self::set_bit(buttons, wiimote::NUNCHUK_BTN_C, pressed),
+ _ => {}
+ }
+}
diff --git a/crates/tinyapp/src/thread.rs b/crates/tinyapp/src/thread.rs
index b3180f6..2f7c098 100644
--- a/crates/tinyapp/src/thread.rs
+++ b/crates/tinyapp/src/thread.rs
@@ -1,5 +1,5 @@
use crossbeam_channel::Sender;
-use gecko::flipper::si::pad::PadStatus;
+use gecko::HostInput;
use gecko::flipper::vi::regs::RefreshRate;
use gecko::system::{System, SystemId};
use std::sync::{Arc, Mutex};
@@ -12,11 +12,12 @@ pub struct FrameMessage {
pub fn emu_thread<const SYSTEM: SystemId>(
mut emulator: System<SYSTEM>,
frame_tx: Sender<FrameMessage>,
- input: Arc<Mutex<PadStatus>>,
+ input: Arc<Mutex<HostInput>>,
proxy: EventLoopProxy<()>,
) {
loop {
- *emulator.primary_controller_mut() = *input.lock().unwrap();
+ let input = *input.lock().unwrap();
+ emulator.apply_host_input(&input);
emulator.run_until_vsync();
let native_hz = match emulator.vi.dcr.video_format().refresh_rate() {
diff --git a/crates/tinybench/src/main.rs b/crates/tinybench/src/main.rs
index 33f1fac..9a12ce5 100644
--- a/crates/tinybench/src/main.rs
+++ b/crates/tinybench/src/main.rs
@@ -1,5 +1,5 @@
use clap::Parser;
-use gecko::flipper::si::pad::PadStatus;
+use gecko::HostInput;
use gecko::gamecube::GameCube;
use std::time::Instant;
@@ -56,10 +56,7 @@ fn main() {
emulator.dsp.load_irom(&dsp_data);
}
- emulator.add_primary_controller(PadStatus {
- connected: true,
- ..PadStatus::default()
- });
+ emulator.apply_host_input(&HostInput::gc_connected());
run_bench(&mut emulator, &args);
}
diff --git a/crates/web/Cargo.lock b/crates/web/Cargo.lock
index fe27f76..c045091 100644
--- a/crates/web/Cargo.lock
+++ b/crates/web/Cargo.lock
@@ -328,18 +328,18 @@ dependencies = [
[[package]]
name = "chipi-build"
-version = "0.9.0"
+version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc93ee723a2e1024de5fdcb59d2dfac6e06edf9a9ad7a3941920d5d9296b8fdc"
+checksum = "b3272bc243a8f30942ec5e6efd9b5fd904e5f051c38d9053f485d35bff204383"
dependencies = [
"chipi-core",
]
[[package]]
name = "chipi-core"
-version = "0.9.0"
+version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7c334634fcf9d942efa6f676b81d3dbf14c0bcf94fede78738d02a09eb3cc30a"
+checksum = "c8f3df7969c229e288b63158f9aabaaaff2aebbab70d642ba8ca7b10b6216581"
[[package]]
name = "codespan-reporting"
@@ -932,12 +932,14 @@ dependencies = [
"chapa",
"chipi-build",
"crc32fast",
+ "disasm",
"glam",
"image",
"multiversion",
"rustc-hash 2.1.2",
"tracing",
"twox-hash",
+ "zerocopy",
]
[[package]]
diff --git a/crates/web/src/lib.rs b/crates/web/src/lib.rs
index fdc7ab8..6a6fe07 100644
--- a/crates/web/src/lib.rs
+++ b/crates/web/src/lib.rs
@@ -4,6 +4,7 @@ use std::rc::Rc;
use std::sync::{Arc, Mutex};
use egui::ViewportId;
+use gecko::HostInput;
use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER};
use gecko::flipper::vi::regs::RefreshRate;
use gecko::gamecube::GameCube;
@@ -400,6 +401,7 @@ type SharedState = Rc<RefCell<Option<State>>>;
struct App {
emulator: GameCube,
+ input: HostInput,
action_queue: ActionQueue,
window: Option<Arc<Window>>,
state: SharedState,
@@ -449,7 +451,10 @@ impl ApplicationHandler for App {
WindowEvent::KeyboardInput { event, .. } => {
let pressed = event.state.is_pressed();
if let PhysicalKey::Code(key) = event.physical_key {
- update_pad(self.emulator.primary_controller_mut(), key, pressed);
+ if let HostInput::Gc(pad) = &mut self.input {
+ update_pad(pad, key, pressed);
+ }
+ self.emulator.apply_host_input(&self.input);
}
}
WindowEvent::RedrawRequested => {
@@ -487,10 +492,8 @@ pub fn start_emulator(rom_data: &[u8], filename: String, dsp_irom: Option<Vec<u8
emulator.dsp.load_irom(&irom);
}
- emulator.add_primary_controller(PadStatus {
- connected: true,
- ..PadStatus::default()
- });
+ let input = HostInput::gc_connected();
+ emulator.apply_host_input(&input);
// Install the WebSink as the emulator's render sink.
let action_queue: ActionQueue = Arc::new(Mutex::new(Vec::new()));
@@ -501,6 +504,7 @@ pub fn start_emulator(rom_data: &[u8], filename: String, dsp_irom: Option<Vec<u8
let event_loop = EventLoop::new().unwrap();
let app = App {
emulator,
+ input,
action_queue,
window: None,
state: Rc::new(RefCell::new(None)),