Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

nunchuck works now

Layle1e28700000b9
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rs
index 458d918..421517e 100644
--- a/crates/debugger/src/main.rs
+++ b/crates/debugger/src/main.rs
@@ -10,7 +10,7 @@ use winit::window::{Window, WindowId};
use gecko::HostInput;
use gecko::audio::WavAudioSink;
-use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER};
+use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER, STICK_MAX, STICK_MIN, TRIGGER_MAX, TRIGGER_MIN};
use gecko::gamecube::GameCube;
use gecko::wii::Wii;
use image::Dol;
@@ -475,10 +475,10 @@ fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {
match key {
// Analog stick (digital, full deflection)
- KeyCode::ArrowUp => pad.stick_y = if pressed { 255 } else { STICK_CENTER },
- KeyCode::ArrowDown => pad.stick_y = if pressed { 0 } else { STICK_CENTER },
- KeyCode::ArrowLeft => pad.stick_x = if pressed { 0 } else { STICK_CENTER },
- KeyCode::ArrowRight => pad.stick_x = if pressed { 255 } else { STICK_CENTER },
+ KeyCode::ArrowUp => pad.stick_y = if pressed { STICK_MAX } else { STICK_CENTER },
+ KeyCode::ArrowDown => pad.stick_y = if pressed { STICK_MIN } else { STICK_CENTER },
+ KeyCode::ArrowLeft => pad.stick_x = if pressed { STICK_MIN } else { STICK_CENTER },
+ KeyCode::ArrowRight => pad.stick_x = if pressed { STICK_MAX } else { STICK_CENTER },
// Face buttons
KeyCode::KeyX => set_button(&mut pad.buttons, pad::A, pressed),
@@ -490,11 +490,11 @@ fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {
// Triggers
KeyCode::KeyA => {
set_button(&mut pad.buttons, pad::L, pressed);
- pad.trigger_left = if pressed { 255 } else { 0 };
+ pad.trigger_left = if pressed { TRIGGER_MAX } else { TRIGGER_MIN };
}
KeyCode::KeyS => {
set_button(&mut pad.buttons, pad::R, pressed);
- pad.trigger_right = if pressed { 255 } else { 0 };
+ pad.trigger_right = if pressed { TRIGGER_MAX } else { TRIGGER_MIN };
}
KeyCode::KeyD => set_button(&mut pad.buttons, pad::Z, pressed),
diff --git a/crates/gecko/src/flipper/si/pad.rs b/crates/gecko/src/flipper/si/pad.rs
index 8d6b489..a3f7014 100644
--- a/crates/gecko/src/flipper/si/pad.rs
+++ b/crates/gecko/src/flipper/si/pad.rs
@@ -12,7 +12,11 @@ pub const Y: u16 = 0x0800;
pub const START: u16 = 0x1000;
pub const USE_ORIGIN: u16 = 0x0080;
+pub const STICK_MIN: u8 = 0;
pub const STICK_CENTER: u8 = 128;
+pub const STICK_MAX: u8 = 255;
+pub const TRIGGER_MIN: u8 = 0;
+pub const TRIGGER_MAX: u8 = 255;
pub const GC_CONTROLLER_ID: u32 = 0x0900_0000;
#[derive(Clone, Copy, Debug)]
diff --git a/crates/gecko/src/hollywood/ipc/usb.rs b/crates/gecko/src/hollywood/ipc/usb.rs
index 686ba7d..4c92428 100644
--- a/crates/gecko/src/hollywood/ipc/usb.rs
+++ b/crates/gecko/src/hollywood/ipc/usb.rs
@@ -1,4 +1,5 @@
mod bluetooth;
+mod crypto;
mod l2cap;
mod wiimote;
@@ -7,7 +8,7 @@ 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,
+ NUNCHUK_BTN_C, NUNCHUK_BTN_Z, NUNCHUK_STICK_CENTER, NUNCHUK_STICK_MAX, NUNCHUK_STICK_MIN,
};
const USB_CTRL: u32 = 0;
@@ -173,7 +174,25 @@ impl Bluetooth {
}
fn set_nunchuk(&mut self, buttons: u8, stick_x: u8, stick_y: u8) -> bool {
- self.wiimote.set_nunchuk(buttons, stick_x, stick_y)
+ let changed = self.wiimote.set_nunchuk(buttons, stick_x, stick_y);
+
+ if changed {
+ tracing::debug!(
+ buttons = format!("{buttons:#04x}"),
+ stick_x = format!("{stick_x:#04x}"),
+ stick_y = format!("{stick_y:#04x}"),
+ "Nunchuk 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);
+
+ changed
}
}
diff --git a/crates/gecko/src/hollywood/ipc/usb/crypto.rs b/crates/gecko/src/hollywood/ipc/usb/crypto.rs
new file mode 100644
index 0000000..3bc271d
--- /dev/null
+++ b/crates/gecko/src/hollywood/ipc/usb/crypto.rs
@@ -0,0 +1,282 @@
+//! ```c
+//! decrypted[i] = ft[(addr + i) & 7] + (raw[i] ^ sb[(addr + i) & 7])
+//! ```
+//!
+//! ```c
+//! encrypted[i] = (data[i] - ft[(addr + i) & 7]) ^ sb[(addr + i) & 7]
+//! ```
+//!
+//! Mirrors the algorithm in FFCC at `kpad_nunchuk_keygen` (0x803D9210) and the
+//! decrypt loop at `kpad_extension_crypt_buffer` (0x803DA000). The constant
+//! tables here are the same ones that live in FFCC `.data5` at
+//! `kpad_nunchuk_select_table` (0x80541068) and `kpad_nunchuk_perm_table`
+//! (0x80541098..0x80541998 = keygen sbox + 8 round sboxes).
+
+const ANS_TBL_1ST_PARTY: [[u8; 6]; 7] = [
+ [0xa8, 0x77, 0xa6, 0xe0, 0xf7, 0x43],
+ [0x5a, 0x35, 0x85, 0xe2, 0x72, 0x97],
+ [0x8f, 0xb7, 0x1a, 0x62, 0x87, 0x38],
+ [0x0d, 0x67, 0xc7, 0xbe, 0x4f, 0x3e],
+ [0x20, 0x76, 0x37, 0x8f, 0x68, 0xb7],
+ [0xa9, 0x26, 0x3f, 0x2b, 0x10, 0xe3],
+ [0x30, 0x7e, 0x90, 0x0e, 0x85, 0x0a],
+];
+
+#[rustfmt::skip]
+const KEYGEN_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0xb6, 0xfd, 0x37, 0x48, 0x4d, 0x39, 0xcb, 0xe0, 0x32,
+ ],
+];
+
+#[derive(Debug, Clone, Copy)]
+pub(super) struct Cipher {
+ ft: [u8; 8],
+ sb: [u8; 8],
+}
+
+impl Cipher {
+ /// Identity cipher: what the SDK uses before any encryption key is set.
+ /// Basically a nop.
+ pub(super) const IDENTITY: Self = Self { ft: [0; 8], sb: [0; 8] };
+
+ /// Reconstruct the cipher the SDK is about to use from the 16-byte
+ /// extension key the guest just wrote to nunchuk register 0x40.
+ ///
+ /// The SDK chose a random `idx` in 0..7 that isn't transmitted in the key
+ /// (see `kpad_nunchuk_keygen` 0x803D9210).
+ /// We brute-force it: try every idx and pick the one whose
+ /// `GenerateKeyData(rand, idx)` reproduces the trailing 6 bytes of the key.
+ pub(super) fn from_extension_key(ext_key: &[u8; 16]) -> Self {
+ let mut rand: [u8; 10] = ext_key[..10].try_into().unwrap();
+ rand.reverse();
+ let mut key: [u8; 6] = ext_key[10..].try_into().unwrap();
+ key.reverse();
+
+ for idx in 0..7 {
+ if self::generate_key_data(&rand, idx) == key {
+ let (ft, sb) = self::generate_tables(&rand, &key, idx);
+ return Self { ft, sb };
+ }
+ }
+
+ tracing::warn!(
+ key = format!("{ext_key:02X?}"),
+ "nunchuk encryption key did not match any idx; falling back to identity"
+ );
+ Self::IDENTITY
+ }
+
+ pub(super) fn encrypt(&self, data: &mut [u8], addr: u32) {
+ for (i, b) in data.iter_mut().enumerate() {
+ let k = ((addr + i as u32) & 7) as usize;
+ *b = b.wrapping_sub(self.ft[k]) ^ self.sb[k];
+ }
+ }
+}
+
+fn generate_key_data(rand: &[u8; 10], idx: usize) -> [u8; 6] {
+ let ans = &ANS_TBL_1ST_PARTY[idx];
+ let t0: [u8; 10] = std::array::from_fn(|i| KEYGEN_SBOX_1ST_PARTY[rand[i] as usize]);
+
+ [
+ ((ans[0] ^ t0[5]).rotate_right(t0[2] as u32).wrapping_sub(t0[9])) ^ t0[4],
+ ((ans[1] ^ t0[1]).rotate_right(t0[0] as u32).wrapping_sub(t0[5])) ^ t0[7],
+ ((ans[2] ^ t0[6]).rotate_right(t0[8] as u32).wrapping_sub(t0[2])) ^ t0[0],
+ ((ans[3] ^ t0[4]).rotate_right(t0[7] as u32).wrapping_sub(t0[3])) ^ t0[2],
+ ((ans[4] ^ t0[1]).rotate_right(t0[6] as u32).wrapping_sub(t0[3])) ^ t0[4],
+ ((ans[5] ^ t0[7]).rotate_right(t0[8] as u32).wrapping_sub(t0[5])) ^ t0[9],
+ ]
+}
+
+fn generate_tables(rand: &[u8; 10], key: &[u8; 6], idx: usize) -> ([u8; 8], [u8; 8]) {
+ let sbox_a = &SBOXES_1ST_PARTY[idx];
+ let sbox_b = &SBOXES_1ST_PARTY[idx + 1];
+ let a = |i: u8| sbox_a[i as usize];
+ let b = |i: u8| sbox_b[i as usize];
+
+ let ft = [
+ a(key[4]) ^ b(rand[3]),
+ a(key[2]) ^ b(rand[5]),
+ a(key[5]) ^ b(rand[7]),
+ a(key[0]) ^ b(rand[2]),
+ a(key[1]) ^ b(rand[4]),
+ a(key[3]) ^ b(rand[9]),
+ a(rand[0]) ^ b(rand[6]),
+ a(rand[1]) ^ b(rand[8]),
+ ];
+
+ let sb = [
+ a(key[0]) ^ b(rand[1]),
+ a(key[5]) ^ b(rand[4]),
+ a(key[3]) ^ b(rand[0]),
+ a(key[2]) ^ b(rand[9]),
+ a(key[4]) ^ b(rand[7]),
+ a(key[1]) ^ b(rand[8]),
+ a(rand[3]) ^ b(rand[5]),
+ a(rand[2]) ^ b(rand[6]),
+ ];
+
+ (ft, sb)
+}
diff --git a/crates/gecko/src/hollywood/ipc/usb/wiimote.rs b/crates/gecko/src/hollywood/ipc/usb/wiimote.rs
index 76f0941..16f1ded 100644
--- a/crates/gecko/src/hollywood/ipc/usb/wiimote.rs
+++ b/crates/gecko/src/hollywood/ipc/usb/wiimote.rs
@@ -1,3 +1,5 @@
+use super::crypto::Cipher;
+
pub const BTN_TWO: u16 = 0x0001;
pub const BTN_ONE: u16 = 0x0002;
pub const BTN_B: u16 = 0x0004;
@@ -13,6 +15,10 @@ pub const BTN_PLUS: u16 = 0x1000;
pub const NUNCHUK_BTN_C: u8 = 0x02;
pub const NUNCHUK_BTN_Z: u8 = 0x01;
+pub const NUNCHUK_STICK_MIN: u8 = 0x00;
+pub const NUNCHUK_STICK_CENTER: u8 = 0x80;
+pub const NUNCHUK_STICK_MAX: u8 = 0xFF;
+
const HID_PREFIX_INPUT: u8 = 0xA1;
const HID_PREFIX_OUTPUT: u8 = 0xA2;
@@ -70,10 +76,10 @@ enum ReportMode {
CoreExt19 = 0x34,
/// Core + accel + 16-byte extension.
CoreAccelExt16 = 0x35,
+ /// Core + 10-byte basic IR + 9-byte extension (no accel).
+ CoreIrBasicExt9 = 0x36,
/// Core + accel + 10-byte basic IR + 6-byte extension.
- CoreAccelIrBasicExt = 0x36,
- /// Core + accel + 10-byte basic IR + 6-byte extension (alternate framing).
- CoreAccelIrFullExt = 0x37,
+ CoreAccelIrBasicExt6 = 0x37,
}
impl ReportMode {
@@ -85,8 +91,8 @@ impl ReportMode {
0x33 => Self::CoreAccelIrExt,
0x34 => Self::CoreExt19,
0x35 => Self::CoreAccelExt16,
- 0x36 => Self::CoreAccelIrBasicExt,
- 0x37 => Self::CoreAccelIrFullExt,
+ 0x36 => Self::CoreIrBasicExt9,
+ 0x37 => Self::CoreAccelIrBasicExt6,
_ => return None,
})
}
@@ -109,11 +115,14 @@ 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
+ 0xE0, 0x20, 0x80, // stick X max, min, center
+ 0xE0, 0x20, 0x80, // stick Y max, min, center
0x00, 0x00, // checksum (filled below at runtime)
];
+const NUNCHUK_KEY_REG_BASE: u8 = 0x40;
+const NUNCHUK_KEY_LEN: usize = 16;
+
#[derive(Debug, Clone)]
pub(super) struct WiimoteState {
buttons: u16,
@@ -128,6 +137,9 @@ pub(super) struct WiimoteState {
nunchuk_stick_x: u8,
nunchuk_stick_y: u8,
nunchuk_calibration: [u8; 16],
+ nunchuk_key_buf: [u8; NUNCHUK_KEY_LEN],
+ nunchuk_key_valid: u16,
+ nunchuk_cipher: Cipher,
}
impl Default for WiimoteState {
@@ -150,9 +162,12 @@ impl Default for WiimoteState {
eeprom,
nunchuk_attached: true,
nunchuk_buttons: 0,
- nunchuk_stick_x: 0x80,
- nunchuk_stick_y: 0x80,
+ nunchuk_stick_x: NUNCHUK_STICK_CENTER,
+ nunchuk_stick_y: NUNCHUK_STICK_CENTER,
nunchuk_calibration,
+ nunchuk_key_buf: [0; NUNCHUK_KEY_LEN],
+ nunchuk_key_valid: 0,
+ nunchuk_cipher: Cipher::IDENTITY,
}
}
}
@@ -198,14 +213,13 @@ impl WiimoteState {
r.extend_from_slice(&accel);
self.append_nunchuk_ext_padded(&mut r, 16);
}
- ReportMode::CoreAccelIrBasicExt => {
- r.extend_from_slice(&accel);
+ ReportMode::CoreIrBasicExt9 => {
r.extend_from_slice(&ir_basic);
- r.extend_from_slice(&self.nunchuk_extension_bytes());
+ self.append_nunchuk_ext_padded(&mut r, 9);
}
- ReportMode::CoreAccelIrFullExt => {
+ ReportMode::CoreAccelIrBasicExt6 => {
r.extend_from_slice(&accel);
- r.extend_from_slice(&ir_extended);
+ r.extend_from_slice(&ir_basic);
r.extend_from_slice(&self.nunchuk_extension_bytes());
}
}
@@ -221,14 +235,16 @@ impl WiimoteState {
// Bits 0,1 of the trailing byte are inverted: 1 = button NOT pressed.
let inv_buttons = (!self.nunchuk_buttons) & 0x03;
- [
+ let mut bytes = [
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,
- ]
+ ];
+ self.nunchuk_cipher.encrypt(&mut bytes, 0);
+ bytes
}
/// Append the 6-byte nunchuk extension followed by 0xFF padding so the
@@ -301,16 +317,18 @@ impl WiimoteState {
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;
+ let payload = &body[5..5 + size.min(body.len().saturating_sub(5)).min(16)];
+
+ tracing::debug!(addr = format!("{address:#08x}"), "Wiimote write memory");
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()]);
+ } else {
+ self.observe_register_write(address, payload);
}
self::trivial_ack(self.button_bytes(), raw_id)
@@ -392,13 +410,53 @@ impl WiimoteState {
break;
}
- out.push(self.read_chunk_report((address as u16) + offset as u16, &backing[start..end], 0));
+ // The SDK runs `kpad_extension_crypt_buffer` (0x803DA000) over the
+ // returned bytes when the address sits in extension register space
+ // (see `kpad_dispatch_report` 0x803D66D0 read handler branch on
+ // `v13 == 1188`, i.e. high word == 0x4A4). It uses the low 16 bits
+ // of the request address as the cipher offset.
+ let chunk_addr = (address as u16) + offset as u16;
+ let mut chunk_data: [u8; 16] = [0; 16];
+ chunk_data[..chunk].copy_from_slice(&backing[start..end]);
+ self.nunchuk_cipher.encrypt(&mut chunk_data[..chunk], chunk_addr as u32);
+
+ out.push(self.read_chunk_report(chunk_addr, &chunk_data[..chunk], 0));
offset += chunk;
}
out
}
+ /// Track writes to nunchuk register 0x40-0x4F so we can mirror the cipher
+ /// the SDK builds in `kpad_nunchuk_keygen` (0x803D9210). Once all 16 bytes
+ /// have arrived we derive `ft`/`sb` and switch our outgoing extension
+ /// bytes and register read responses to encrypted output.
+ fn observe_register_write(&mut self, address: u32, payload: &[u8]) {
+ let reg = (address & 0xFF) as u8;
+ let Some(rel) = reg.checked_sub(NUNCHUK_KEY_REG_BASE) else {
+ return;
+ };
+
+ let rel = rel as usize;
+ if rel >= NUNCHUK_KEY_LEN {
+ return;
+ }
+
+ let count = payload.len().min(NUNCHUK_KEY_LEN - rel);
+ self.nunchuk_key_buf[rel..rel + count].copy_from_slice(&payload[..count]);
+ for i in 0..count {
+ self.nunchuk_key_valid |= 1 << (rel + i);
+ }
+
+ if self.nunchuk_key_valid == u16::MAX {
+ self.nunchuk_cipher = Cipher::from_extension_key(&self.nunchuk_key_buf);
+ tracing::debug!(
+ key = format!("{:02X?}", self.nunchuk_key_buf),
+ "Wiimote nunchuk encryption key complete"
+ );
+ }
+ }
+
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);
diff --git a/crates/gecko/src/input.rs b/crates/gecko/src/input.rs
index 53be6b4..7e581c6 100644
--- a/crates/gecko/src/input.rs
+++ b/crates/gecko/src/input.rs
@@ -1,4 +1,5 @@
use crate::flipper::si::pad;
+use crate::hollywood::ipc::usb;
use crate::{GC, SystemId, WII};
#[derive(Clone, Copy, Debug)]
@@ -24,8 +25,8 @@ impl HostInput {
Self::Wii {
wiimote_buttons: 0,
nunchuk_buttons: 0,
- nunchuk_stick_x: 0x80,
- nunchuk_stick_y: 0x80,
+ nunchuk_stick_x: usb::NUNCHUK_STICK_CENTER,
+ nunchuk_stick_y: usb::NUNCHUK_STICK_CENTER,
}
}
diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs
index b8b0282..f5ffe94 100644
--- a/crates/mcp/src/server.rs
+++ b/crates/mcp/src/server.rs
@@ -108,6 +108,20 @@ pub struct SetPadArgs {
pub buttons: Option<u16>,
}
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct SetWiimoteArgs {
+ #[schemars(
+ description = "Wiimote core button bitmask: A=0x0008, B=0x0004, ONE=0x0002, TWO=0x0001, MINUS=0x0010, HOME=0x0080, PLUS=0x1000, LEFT=0x0100, RIGHT=0x0200, DOWN=0x0400, UP=0x0800"
+ )]
+ pub buttons: Option<u16>,
+ #[schemars(description = "Nunchuk button bitmask: Z=0x01, C=0x02")]
+ pub nunchuk_buttons: Option<u8>,
+ #[schemars(description = "Nunchuk stick X (0..=255, center=0x80, full-left=0x00, full-right=0xFF)")]
+ pub nunchuk_stick_x: Option<u8>,
+ #[schemars(description = "Nunchuk stick Y (0..=255, center=0x80, full-down=0x00, full-up=0xFF)")]
+ pub nunchuk_stick_y: Option<u8>,
+}
+
#[derive(Debug, Serialize)]
struct StatusJson {
loaded: bool,
@@ -554,6 +568,26 @@ impl McpServer {
s.backend.as_mut().unwrap().apply_host_input(&input);
ok_json(&json!({"applied": true}))
}
+
+ #[tool(
+ description = "Update the Wii remote + nunchuk state. Defaults: buttons=0, stick centered (0x80). Unspecified fields go to those defaults."
+ )]
+ async fn set_wiimote(&self, Parameters(args): Parameters<SetWiimoteArgs>) -> Result<CallToolResult, McpError> {
+ require_loaded(&self.shared)?;
+ let input = gecko::HostInput::Wii {
+ wiimote_buttons: args.buttons.unwrap_or(0),
+ nunchuk_buttons: args.nunchuk_buttons.unwrap_or(0),
+ nunchuk_stick_x: args
+ .nunchuk_stick_x
+ .unwrap_or(gecko::hollywood::ipc::usb::NUNCHUK_STICK_CENTER),
+ nunchuk_stick_y: args
+ .nunchuk_stick_y
+ .unwrap_or(gecko::hollywood::ipc::usb::NUNCHUK_STICK_CENTER),
+ };
+ let mut s = self.shared.state.lock().unwrap();
+ s.backend.as_mut().unwrap().apply_host_input(&input);
+ ok_json(&json!({"applied": true}))
+ }
}
#[tool_handler]
@@ -563,7 +597,7 @@ impl ServerHandler for McpServer {
.with_server_info(Implementation::from_build_env())
.with_protocol_version(ProtocolVersion::V_2024_11_05)
.with_instructions(
- "Headless gecko (GameCube/Wii) emulator. Tools: load_game, status, pause/resume, step, run_frames, run_until_pc, run_until_vsync, read_memory, write_memory, search_bytes, get_registers, disassemble, get_view, list_textures, get_texture, list_bound_textures, set_pad."
+ "Headless gecko (GameCube/Wii) emulator. Tools: load_game, status, pause/resume, step, run_frames, run_until_pc, run_until_vsync, read_memory, write_memory, search_bytes, get_registers, disassemble, get_view, list_textures, get_texture, list_bound_textures, set_pad, set_wiimote."
.to_string(),
)
}
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index 2272985..b245ae5 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -11,7 +11,7 @@ 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::flipper::si::pad::{self, PadStatus, STICK_CENTER, STICK_MAX, STICK_MIN, TRIGGER_MAX, TRIGGER_MIN};
use gecko::gamecube::GameCube;
use gecko::hollywood::ipc::usb as wiimote;
use gecko::system::{self, System, SystemId};
@@ -476,10 +476,10 @@ fn set_bit<T: std::ops::BitOrAssign + std::ops::BitAndAssign + std::ops::Not<Out
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 },
- KeyCode::ArrowDown => pad.stick_y = if pressed { 0 } else { STICK_CENTER },
- KeyCode::ArrowLeft => pad.stick_x = if pressed { 0 } else { STICK_CENTER },
- KeyCode::ArrowRight => pad.stick_x = if pressed { 255 } else { STICK_CENTER },
+ KeyCode::ArrowUp => pad.stick_y = if pressed { STICK_MAX } else { STICK_CENTER },
+ KeyCode::ArrowDown => pad.stick_y = if pressed { STICK_MIN } else { STICK_CENTER },
+ KeyCode::ArrowLeft => pad.stick_x = if pressed { STICK_MIN } else { STICK_CENTER },
+ KeyCode::ArrowRight => pad.stick_x = if pressed { STICK_MAX } else { STICK_CENTER },
// Face buttons
KeyCode::KeyX => self::set_bit(&mut pad.buttons, pad::A, pressed),
@@ -491,11 +491,11 @@ fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {
// Triggers
KeyCode::KeyA => {
self::set_bit(&mut pad.buttons, pad::L, pressed);
- pad.trigger_left = if pressed { 255 } else { 0 };
+ pad.trigger_left = if pressed { TRIGGER_MAX } else { TRIGGER_MIN };
}
KeyCode::KeyS => {
self::set_bit(&mut pad.buttons, pad::R, pressed);
- pad.trigger_right = if pressed { 255 } else { 0 };
+ pad.trigger_right = if pressed { TRIGGER_MAX } else { TRIGGER_MIN };
}
KeyCode::KeyD => self::set_bit(&mut pad.buttons, pad::Z, pressed),
@@ -526,12 +526,12 @@ pub fn update_wiimote_keys(buttons: &mut u16, key: KeyCode, pressed: bool) {
}
pub fn update_nunchuk_keys(buttons: &mut u8, stick_x: &mut u8, stick_y: &mut u8, key: KeyCode, pressed: bool) {
- const NEUTRAL: u8 = 0x80;
+ use wiimote::{NUNCHUK_STICK_CENTER as C, NUNCHUK_STICK_MAX as MAX, NUNCHUK_STICK_MIN as MIN};
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::KeyW => *stick_y = if pressed { MAX } else { C },
+ KeyCode::KeyS => *stick_y = if pressed { MIN } else { C },
+ KeyCode::KeyA => *stick_x = if pressed { MIN } else { C },
+ KeyCode::KeyD => *stick_x = if pressed { MAX } else { C },
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/web/src/lib.rs b/crates/web/src/lib.rs
index 6a6fe07..5dd3170 100644
--- a/crates/web/src/lib.rs
+++ b/crates/web/src/lib.rs
@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};
use egui::ViewportId;
use gecko::HostInput;
-use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER};
+use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER, STICK_MAX, STICK_MIN, TRIGGER_MAX, TRIGGER_MIN};
use gecko::flipper::vi::regs::RefreshRate;
use gecko::gamecube::GameCube;
use gecko::host::{GxAction, RenderSink};
@@ -525,10 +525,10 @@ fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {
};
match key {
- KeyCode::ArrowUp => pad.stick_y = if pressed { 255 } else { STICK_CENTER },
- KeyCode::ArrowDown => pad.stick_y = if pressed { 0 } else { STICK_CENTER },
- KeyCode::ArrowLeft => pad.stick_x = if pressed { 0 } else { STICK_CENTER },
- KeyCode::ArrowRight => pad.stick_x = if pressed { 255 } else { STICK_CENTER },
+ KeyCode::ArrowUp => pad.stick_y = if pressed { STICK_MAX } else { STICK_CENTER },
+ KeyCode::ArrowDown => pad.stick_y = if pressed { STICK_MIN } else { STICK_CENTER },
+ KeyCode::ArrowLeft => pad.stick_x = if pressed { STICK_MIN } else { STICK_CENTER },
+ KeyCode::ArrowRight => pad.stick_x = if pressed { STICK_MAX } else { STICK_CENTER },
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),
@@ -536,11 +536,11 @@ fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {
KeyCode::Enter => set_button(&mut pad.buttons, pad::START, pressed),
KeyCode::KeyA => {
set_button(&mut pad.buttons, pad::L, pressed);
- pad.trigger_left = if pressed { 255 } else { 0 };
+ pad.trigger_left = if pressed { TRIGGER_MAX } else { TRIGGER_MIN };
}
KeyCode::KeyS => {
set_button(&mut pad.buttons, pad::R, pressed);
- pad.trigger_right = if pressed { 255 } else { 0 };
+ pad.trigger_right = if pressed { TRIGGER_MAX } else { TRIGGER_MIN };
}
KeyCode::KeyD => set_button(&mut pad.buttons, pad::Z, pressed),
KeyCode::KeyI => set_button(&mut pad.buttons, pad::DPAD_UP, pressed),