Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

controller support!

Laylebacfa01bf2e6
diff --git a/.dockerignore b/.dockerignore
index 130ba78..151e9c4 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -26,3 +26,6 @@ perf.*
!submodules/solstice/ipl/hle/
!submodules/solstice/ipl/hle/ipl/
!submodules/solstice/ipl/hle/ipl/gc_custom_ipl.bin
+
+docker/
+docker-build/
diff --git a/Cargo.lock b/Cargo.lock
index ef32ac2..be0d02a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2322,6 +2322,7 @@ dependencies = [
"cpal",
"futures",
"gecko",
+ "hostinput",
"iced",
"iced_aw",
"image 0.1.0",
@@ -2635,6 +2636,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"
+[[package]]
+name = "hostinput"
+version = "0.1.0"
+dependencies = [
+ "gecko",
+ "sdl3",
+ "serde",
+ "tracing",
+ "tracing-subscriber",
+]
+
[[package]]
name = "hotpath"
version = "0.16.1"
@@ -5579,6 +5591,12 @@ version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+[[package]]
+name = "rpkg-config"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a2d2f3481209a6b42eec2fbb49063fb4e8d35b57023401495d4fe0f85c817f0"
+
[[package]]
name = "rstest"
version = "0.25.0"
@@ -5839,6 +5857,100 @@ dependencies = [
"tiny-skia",
]
+[[package]]
+name = "sdl3"
+version = "0.18.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25bd22eb1bbc9137e914022b4994ed35591eea0884e9e3e98e6d9895cad6e1d2"
+dependencies = [
+ "bitflags 2.11.1",
+ "libc",
+ "sdl3-image-sys",
+ "sdl3-mixer-sys",
+ "sdl3-sys",
+ "sdl3-ttf-sys",
+]
+
+[[package]]
+name = "sdl3-image-src"
+version = "3.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe273101c7dab94551183212eee9adef1a7bf274d407f0b7bfe72482960ab25c"
+
+[[package]]
+name = "sdl3-image-sys"
+version = "0.6.4+SDL-image-3.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a445f781b39a1c1bc751f5f4612191e0402006e35ad5d02d9193281afad1cf4"
+dependencies = [
+ "cmake",
+ "pkg-config",
+ "rpkg-config",
+ "sdl3-image-src",
+ "sdl3-sys",
+ "vcpkg",
+]
+
+[[package]]
+name = "sdl3-mixer-src"
+version = "3.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9cd815ae87084588c7dbd027c1667b0a5e21a6b5ae7b22ecb230bc21c7063eca"
+
+[[package]]
+name = "sdl3-mixer-sys"
+version = "0.6.3+SDL-mixer-3.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b5a157588924cf886bdc3a7c9d0e478cdad35d315740f26af00609a61e7c327"
+dependencies = [
+ "cmake",
+ "pkg-config",
+ "rpkg-config",
+ "sdl3-mixer-src",
+ "sdl3-sys",
+ "vcpkg",
+]
+
+[[package]]
+name = "sdl3-src"
+version = "3.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed4dcad85f1657d3424642ca2ed8f9f185212975baefda8972ac606494755a62"
+
+[[package]]
+name = "sdl3-sys"
+version = "0.6.6+SDL-3.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04e7f134def04ed72e6f55187c6c29c72f7dab5d359c4be0dd49c9b97fef59c7"
+dependencies = [
+ "cc",
+ "cmake",
+ "pkg-config",
+ "rpkg-config",
+ "sdl3-src",
+ "vcpkg",
+]
+
+[[package]]
+name = "sdl3-ttf-src"
+version = "3.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8deaa09c46d6aa8e8a81a601eb4685b2a57f2ce8a4ea3c59e8b623b526d1125"
+
+[[package]]
+name = "sdl3-ttf-sys"
+version = "0.6.1+SDL-ttf-3.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8137096072109d6c834d4cb30b8a617ded4f150c7766757eddc834108bbcefd2"
+dependencies = [
+ "cmake",
+ "pkg-config",
+ "rpkg-config",
+ "sdl3-sys",
+ "sdl3-ttf-src",
+ "vcpkg",
+]
+
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -6546,6 +6658,7 @@ dependencies = [
"egui-wgpu",
"egui-winit",
"gecko",
+ "hostinput",
"hotpath",
"image 0.1.0",
"mimalloc",
@@ -7005,6 +7118,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
[[package]]
name = "vello_common"
version = "0.0.6"
diff --git a/Cargo.toml b/Cargo.toml
index 565eb21..3d202f8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -14,6 +14,7 @@ members = [
"crates/dff",
"crates/fifoplayer",
"crates/mcp",
+ "crates/hostinput",
# Stuff we rarely use
"crates/dsptestrunner",
@@ -32,6 +33,8 @@ default-members = [
"crates/backend-wgpu",
"crates/scripting",
"crates/mcp",
+ "crates/hostinput",
+ "crates/debugger",
]
exclude = [
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml
index bd7cbff..8cd119e 100644
--- a/crates/app/Cargo.toml
+++ b/crates/app/Cargo.toml
@@ -10,6 +10,7 @@ path = "src/main.rs"
[dependencies]
image = { path = "../image" }
gecko = { path = "../gecko", features = ["fps-counter"] }
+hostinput = { path = "../hostinput" }
backend-wgpu = { path = "../backend-wgpu" }
wgpu = "29.0.3"
cpal = "0.17.3"
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 2110b46..bd00605 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -5,7 +5,7 @@ use std::time::{Duration, Instant};
use backend_wgpu::capture;
use iced::theme::Mode;
-use iced::widget::{Stack, button, column, container, mouse_area, scrollable, stack, text};
+use iced::widget::{Stack, button, column, container, scrollable, stack, text};
use iced::{Background, Border, Color, Element, Length, Padding, Subscription, Task, Theme, window};
use crate::cache::{self, LibraryCache};
@@ -15,7 +15,8 @@ use crate::library::{self, ScanProgress};
use crate::player::{self, PlayerState, PlayerStatus};
use crate::theme::{self, Palette};
use crate::update::{self, Outcome};
-use crate::widgets::{game_row, menubar, search_bar, statusbar};
+use crate::widgets::input_settings::{self, BindTarget, InputTab, InvertTarget};
+use crate::widgets::{game_row, menubar, overlay, search_bar, statusbar};
const REPO_URL: &str = "https://github.com/ioncodes/gecko";
pub(crate) const ISSUE_URL: &str = "https://github.com/ioncodes/gecko/issues/new?template=bug_report.md";
@@ -44,6 +45,17 @@ pub enum Message {
MenuSetTheme(ThemePreference),
MenuAbout,
AboutClose,
+ MenuInputSettings,
+ InputClose,
+ InputTab(InputTab),
+ InputCapture(BindTarget),
+ InputTick,
+ InputPointer(String),
+ InputSensitivity(f32),
+ InputToggleSideways,
+ InputToggleStickDpad,
+ InputToggleInvert(InvertTarget),
+ InputReset,
OpenUrl(String),
CheckForUpdates,
UpdateChecked(Outcome),
@@ -101,6 +113,11 @@ pub struct App {
search_lc: String,
scanning: bool,
about_open: bool,
+ input_open: bool,
+ input_tab: InputTab,
+ input_capture: Option<BindTarget>,
+ input_capture_baseline: u32,
+ input_pad_name: Option<String>,
system_mode: Mode,
palette: Palette,
last_click: Option<(usize, Instant)>,
@@ -131,6 +148,11 @@ impl App {
search_lc: String::new(),
scanning: false,
about_open: false,
+ input_open: false,
+ input_tab: InputTab::Gc,
+ input_capture: None,
+ input_capture_baseline: 0,
+ input_pad_name: None,
system_mode: Mode::Light,
palette,
last_click: None,
@@ -178,6 +200,10 @@ impl App {
subs.push(window::frames().map(|_| Message::PlayerTick));
}
+ if self.input_open {
+ subs.push(iced::time::every(Duration::from_millis(100)).map(|_| Message::InputTick));
+ }
+
Subscription::batch(subs)
}
@@ -348,6 +374,86 @@ impl App {
self.about_open = true;
Task::none()
}
+ Message::MenuInputSettings => {
+ self.input_open = true;
+ self.input_capture = None;
+ self.input_pad_name = self::pad_state().1;
+ Task::none()
+ }
+ Message::InputClose => {
+ self.input_open = false;
+ self.input_capture = None;
+ Task::none()
+ }
+ Message::InputTab(tab) => {
+ self.input_tab = tab;
+ self.input_capture = None;
+ Task::none()
+ }
+ Message::InputCapture(target) => {
+ if self.input_capture == Some(target) {
+ self.input_capture = None;
+ } else {
+ self.input_capture = Some(target);
+ self.input_capture_baseline = self::pad_state().0.unwrap_or(0);
+ }
+ Task::none()
+ }
+ Message::InputTick => {
+ let (buttons, name) = self::pad_state();
+ self.input_pad_name = name;
+
+ if let Some(target) = self.input_capture
+ && let Some(buttons) = buttons
+ {
+ self.input_capture_baseline &= buttons;
+
+ let fresh = buttons & !self.input_capture_baseline;
+ if let Some(button) = input_settings::pressed_button(fresh) {
+ *input_settings::field(&mut self.config.input, target) =
+ Some(hostinput::config::button_name(button).to_owned());
+ self.input_capture = None;
+ self.persist_config();
+ }
+ }
+
+ Task::none()
+ }
+ Message::InputPointer(source) => {
+ self.config.input.wii.pointer = Some(source);
+ self.persist_config();
+ Task::none()
+ }
+ Message::InputSensitivity(delta) => {
+ let current = self.config.input.wii.pointer_sensitivity.unwrap_or(1.0);
+ self.config.input.wii.pointer_sensitivity = Some((current + delta).clamp(0.25, 4.0));
+ self.persist_config();
+ Task::none()
+ }
+ Message::InputToggleSideways => {
+ let current = self.config.input.wii.sideways.unwrap_or(false);
+ self.config.input.wii.sideways = Some(!current);
+ self.persist_config();
+ Task::none()
+ }
+ Message::InputToggleStickDpad => {
+ let current = self.config.input.wii.stick_dpad.unwrap_or(true);
+ self.config.input.wii.stick_dpad = Some(!current);
+ self.persist_config();
+ Task::none()
+ }
+ Message::InputToggleInvert(target) => {
+ let field = input_settings::invert_field(&mut self.config.input, target);
+ *field = Some(!field.unwrap_or(false));
+ self.persist_config();
+ Task::none()
+ }
+ Message::InputReset => {
+ self.config.input = hostinput::InputConfig::default();
+ self.input_capture = None;
+ self.persist_config();
+ Task::none()
+ }
Message::AboutClose => {
self.about_open = false;
Task::none()
@@ -524,12 +630,25 @@ impl App {
..container::Style::default()
});
- let root_element: Element<'_, Message> = root.into();
+ let mut root_element: Element<'_, Message> = root.into();
if self.about_open {
- stack![root_element, self::about_overlay(palette)].into()
- } else {
- root_element
+ root_element = stack![root_element, self::about_overlay(palette)].into();
}
+ if self.input_open {
+ root_element = stack![
+ root_element,
+ input_settings::overlay(
+ palette,
+ &self.config.input,
+ self.input_tab,
+ self.input_capture,
+ self.input_pad_name.as_deref(),
+ )
+ ]
+ .into();
+ }
+
+ root_element
}
fn player_view<'a>(&'a self, window_id: window::Id, player: &'a PlayerWindow) -> Element<'a, Message> {
@@ -767,8 +886,16 @@ fn overlay_card(palette: &Palette, title: &str, detail: Option<&str>, error: boo
stack![backdrop, centered].into()
}
+fn pad_state() -> (Option<u32>, Option<String>) {
+ let service = hostinput::sdl::service();
+
+ let buttons = service.shared.lock().unwrap().map(|port| port.state.buttons);
+ let name = service.device.lock().unwrap().clone();
+
+ (buttons, name)
+}
+
fn about_overlay(palette: &Palette) -> Element<'static, Message> {
- let bg = palette.bg;
let surface = palette.surface;
let surface_2 = palette.surface_2;
let border = palette.border;
@@ -777,10 +904,6 @@ fn about_overlay(palette: &Palette) -> Element<'static, Message> {
let dim = palette.text_dim;
let mute = palette.text_mute;
let link_color = palette.accent;
- let backdrop_color = Color {
- a: 0.45,
- ..(if palette.is_dark { Color::BLACK } else { palette.text })
- };
let link_button = button(text(REPO_URL).size(12).color(link_color))
.on_press(Message::OpenUrl(REPO_URL.to_owned()))
@@ -801,88 +924,56 @@ fn about_overlay(palette: &Palette) -> Element<'static, Message> {
}
});
- let card: Element<'static, Message> = container(
- column![
- text("Gecko").size(28).color(text_color),
- text("GameCube / Wii emulator").size(13).color(dim),
- link_button,
- container(text(""))
- .width(Length::Fill)
- .height(1)
- .style(move |_: &Theme| container::Style {
- background: Some(Background::Color(border)),
- ..container::Style::default()
- }),
- column![
- text("Author").size(13).color(text_color),
- text("Layle").size(12).color(dim),
- ]
- .spacing(2)
- .align_x(iced::Alignment::Center),
- column![
- text("Acknowledgements").size(13).color(text_color),
- text("zayd").size(12).color(dim),
- text("vxpm").size(12).color(dim),
- text("hazelwiss").size(12).color(dim),
- text("Dolphin team").size(12).color(dim),
- ]
- .spacing(2)
- .align_x(iced::Alignment::Center),
- text(self::version_label()).size(11).color(mute),
- button(text("Close").size(13))
- .on_press(Message::AboutClose)
- .padding(Padding::from([6, 14]))
- .style(move |_: &Theme, status| {
- let button_bg = match status {
- button::Status::Hovered | button::Status::Pressed => surface_2,
- _ => surface,
- };
- button::Style {
- background: Some(Background::Color(button_bg)),
- text_color,
- border: Border {
- color: border_2,
- width: 1.0,
- radius: 6.0.into(),
- },
- ..button::Style::default()
- }
- }),
- ]
- .spacing(8)
- .align_x(iced::Alignment::Center),
- )
- .width(Length::Fixed(320.0))
- .padding(24)
- .style(move |_: &Theme| container::Style {
- background: Some(Background::Color(bg)),
- border: Border {
- color: border_2,
- width: 1.0,
- radius: 12.0.into(),
- },
- ..container::Style::default()
- })
- .into();
-
- let backdrop: Element<'static, Message> = mouse_area(
+ let content: Element<'static, Message> = column![
+ text("Gecko").size(28).color(text_color),
+ text("GameCube / Wii emulator").size(13).color(dim),
+ link_button,
container(text(""))
.width(Length::Fill)
- .height(Length::Fill)
+ .height(1)
.style(move |_: &Theme| container::Style {
- background: Some(Background::Color(backdrop_color)),
+ background: Some(Background::Color(border)),
..container::Style::default()
}),
- )
- .on_press(Message::AboutClose)
+ column![
+ text("Author").size(13).color(text_color),
+ text("Layle").size(12).color(dim),
+ ]
+ .spacing(2)
+ .align_x(iced::Alignment::Center),
+ column![
+ text("Acknowledgements").size(13).color(text_color),
+ text("zayd").size(12).color(dim),
+ text("vxpm").size(12).color(dim),
+ text("hazelwiss").size(12).color(dim),
+ text("Dolphin team").size(12).color(dim),
+ ]
+ .spacing(2)
+ .align_x(iced::Alignment::Center),
+ text(self::version_label()).size(11).color(mute),
+ button(text("Close").size(13))
+ .on_press(Message::AboutClose)
+ .padding(Padding::from([6, 14]))
+ .style(move |_: &Theme, status| {
+ let button_bg = match status {
+ button::Status::Hovered | button::Status::Pressed => surface_2,
+ _ => surface,
+ };
+ button::Style {
+ background: Some(Background::Color(button_bg)),
+ text_color,
+ border: Border {
+ color: border_2,
+ width: 1.0,
+ radius: 6.0.into(),
+ },
+ ..button::Style::default()
+ }
+ }),
+ ]
+ .spacing(8)
+ .align_x(iced::Alignment::Center)
.into();
- let centered: Element<'static, Message> = container(card)
- .width(Length::Fill)
- .height(Length::Fill)
- .center_x(Length::Fill)
- .center_y(Length::Fill)
- .into();
-
- stack![backdrop, centered].into()
+ overlay::modal(palette, 320.0, 24.0, Message::AboutClose, content)
}
diff --git a/crates/app/src/config.rs b/crates/app/src/config.rs
index f45d992..e992692 100644
--- a/crates/app/src/config.rs
+++ b/crates/app/src/config.rs
@@ -17,6 +17,7 @@ pub struct Config {
pub ipl: Option<PathBuf>,
#[serde(default = "self::default_skip_ipl")]
pub skip_ipl: bool,
+ pub input: hostinput::InputConfig,
}
fn default_skip_ipl() -> bool {
@@ -35,6 +36,7 @@ impl Default for Config {
dsp_coef: None,
ipl: None,
skip_ipl: self::default_skip_ipl(),
+ input: hostinput::InputConfig::default(),
}
}
}
diff --git a/crates/app/src/player/emu_thread.rs b/crates/app/src/player/emu_thread.rs
index 63b6ffe..393bfc8 100644
--- a/crates/app/src/player/emu_thread.rs
+++ b/crates/app/src/player/emu_thread.rs
@@ -8,6 +8,7 @@ use std::time::Duration;
pub fn run<const SYSTEM: SystemId>(
mut emulator: System<SYSTEM>,
input: Arc<Mutex<HostInput>>,
+ input_config: hostinput::InputConfig,
game_id: Option<String>,
throttle: Arc<AtomicBool>,
shutdown: Arc<AtomicBool>,
@@ -15,7 +16,11 @@ pub fn run<const SYSTEM: SystemId>(
let sleeper = SpinSleeper::default();
let throttle_step = Duration::from_micros(5);
- emulator.set_input_sink(Box::new(input.clone()));
+ emulator.set_input_sink(Box::new(hostinput::InputManager::new(
+ SYSTEM,
+ &input_config,
+ input.clone(),
+ )));
while !shutdown.load(Ordering::Relaxed) {
while throttle.load(Ordering::Relaxed) && emulator.audio_sink.should_throttle() {
@@ -25,8 +30,6 @@ pub fn run<const SYSTEM: SystemId>(
sleeper.sleep(throttle_step);
}
- let input = *input.lock().unwrap();
- emulator.apply_host_input(&input);
emulator.run_until_vsync();
}
diff --git a/crates/app/src/player/state.rs b/crates/app/src/player/state.rs
index dd7ad1e..ee70ae2 100644
--- a/crates/app/src/player/state.rs
+++ b/crates/app/src/player/state.rs
@@ -24,6 +24,7 @@ struct BootParams {
ipl_path: Option<PathBuf>,
skip_ipl: bool,
execution_mode: gecko::ExecutionMode,
+ input_config: hostinput::InputConfig,
}
struct Initialized {
@@ -82,6 +83,7 @@ impl PlayerState {
ipl_path: ipl,
skip_ipl: config.skip_ipl,
execution_mode: config.cpu_mode.into(),
+ input_config: config.input.clone(),
})),
initialized: OnceLock::new(),
shutdown: Arc::new(AtomicBool::new(false)),
@@ -144,7 +146,7 @@ impl PlayerState {
nunchuk_buttons,
nunchuk_stick_x,
nunchuk_stick_y,
- ir_pointer: _,
+ ..
} => {
input::update_wiimote_keys(wiimote_buttons, key, pressed);
input::update_wiimote_motion_keys(wiimote_shake, key, pressed);
@@ -174,7 +176,7 @@ impl PlayerState {
if self.platform != Platform::Wii {
return;
}
- let (ir_x, ir_y) = self::aim_to_ir(aim_x, aim_y);
+ let (ir_x, ir_y) = gecko::input::aim_to_ir(aim_x, aim_y);
let mut input_guard = self.input.lock().unwrap();
if let HostInput::Wii { ir_pointer, .. } = &mut *input_guard {
*ir_pointer = Some((ir_x, ir_y));
@@ -221,22 +223,6 @@ pub fn physical_to_code(physical: &Physical) -> Option<Code> {
}
}
-fn aim_to_ir(aim_x: f32, aim_y: f32) -> (u16, u16) {
- const POINTER_SCALE_X: f64 = 0.44;
- const POINTER_SCALE_Y: f64 = 0.66;
- const POINTER_Y_OFFSET: f64 = 120.0;
-
- let aim_x = (aim_x as f64).clamp(0.0, 1.0);
- let aim_y = (aim_y as f64).clamp(0.0, 1.0);
- let span_x = usb::IR_CAMERA_WIDTH as f64 * POINTER_SCALE_X;
- let span_y = usb::IR_CAMERA_HEIGHT as f64 * POINTER_SCALE_Y;
- let base_x = (usb::IR_CAMERA_WIDTH as f64 - span_x) / 2.0;
- let base_y = (usb::IR_CAMERA_HEIGHT as f64 - span_y) / 2.0 + POINTER_Y_OFFSET;
- let ir_x = (base_x + (1.0 - aim_x) * span_x) as u16;
- let ir_y = (base_y + aim_y * span_y) as u16;
- (ir_x, ir_y)
-}
-
fn player_thread(
state: Arc<PlayerState>,
params: BootParams,
@@ -281,6 +267,7 @@ fn player_thread(
emu_thread::run::<{ system::WII }>(
emu,
state.input.clone(),
+ params.input_config.clone(),
Some(game_id),
state.throttle.clone(),
shutdown,
@@ -296,6 +283,7 @@ fn player_thread(
emu_thread::run::<{ system::GC }>(
emu,
state.input.clone(),
+ params.input_config.clone(),
Some(game_id),
state.throttle.clone(),
shutdown,
diff --git a/crates/app/src/widgets.rs b/crates/app/src/widgets.rs
index e7c083d..8fa7f70 100644
--- a/crates/app/src/widgets.rs
+++ b/crates/app/src/widgets.rs
@@ -1,6 +1,8 @@
pub mod badge;
pub mod cover;
pub mod game_row;
+pub mod input_settings;
pub mod menubar;
+pub mod overlay;
pub mod search_bar;
pub mod statusbar;
diff --git a/crates/app/src/widgets/input_settings.rs b/crates/app/src/widgets/input_settings.rs
new file mode 100644
index 0000000..ee536a0
--- /dev/null
+++ b/crates/app/src/widgets/input_settings.rs
@@ -0,0 +1,503 @@
+use gecko::flipper::si::pad;
+use gecko::hollywood::ipc::usb;
+use hostinput::mapping::{GcProfile, WiiProfile};
+use hostinput::{Button, InputConfig};
+use iced::widget::{button, column, container, pick_list, row, text};
+use iced::{Alignment, Background, Border, Color, Element, Length, Padding};
+
+use crate::app::Message;
+use crate::theme::Palette;
+use crate::widgets::overlay;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum InputTab {
+ Gc,
+ Wii,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BindTarget {
+ GcA,
+ GcB,
+ GcX,
+ GcY,
+ GcStart,
+ GcZ,
+ WiiA,
+ WiiB,
+ WiiOne,
+ WiiTwo,
+ WiiPlus,
+ WiiMinus,
+ WiiHome,
+ NunchukC,
+ NunchukZ,
+ Shake,
+ Recenter,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum InvertTarget {
+ GcStickX,
+ GcStickY,
+ GcCstickX,
+ GcCstickY,
+ NunchukX,
+ NunchukY,
+ StickDpadX,
+ StickDpadY,
+ PointerX,
+ PointerY,
+}
+
+const GC_TARGETS: [(BindTarget, &str); 6] = [
+ (BindTarget::GcA, "A"),
+ (BindTarget::GcB, "B"),
+ (BindTarget::GcX, "X"),
+ (BindTarget::GcY, "Y"),
+ (BindTarget::GcStart, "Start"),
+ (BindTarget::GcZ, "Z"),
+];
+
+const WII_TARGETS: [(BindTarget, &str); 11] = [
+ (BindTarget::WiiA, "A"),
+ (BindTarget::WiiB, "B"),
+ (BindTarget::WiiOne, "1"),
+ (BindTarget::WiiTwo, "2"),
+ (BindTarget::WiiPlus, "Plus"),
+ (BindTarget::WiiMinus, "Minus"),
+ (BindTarget::WiiHome, "Home"),
+ (BindTarget::NunchukC, "Nunchuk C"),
+ (BindTarget::NunchukZ, "Nunchuk Z"),
+ (BindTarget::Shake, "Shake"),
+ (BindTarget::Recenter, "Recenter"),
+];
+
+const POINTER_SOURCES: [&str; 5] = ["auto", "gyro", "stick", "touchpad", "mouse"];
+
+pub fn field(config: &mut InputConfig, target: BindTarget) -> &mut Option<String> {
+ match target {
+ BindTarget::GcA => &mut config.gc.a,
+ BindTarget::GcB => &mut config.gc.b,
+ BindTarget::GcX => &mut config.gc.x,
+ BindTarget::GcY => &mut config.gc.y,
+ BindTarget::GcStart => &mut config.gc.start,
+ BindTarget::GcZ => &mut config.gc.z,
+ BindTarget::WiiA => &mut config.wii.a,
+ BindTarget::WiiB => &mut config.wii.b,
+ BindTarget::WiiOne => &mut config.wii.one,
+ BindTarget::WiiTwo => &mut config.wii.two,
+ BindTarget::WiiPlus => &mut config.wii.plus,
+ BindTarget::WiiMinus => &mut config.wii.minus,
+ BindTarget::WiiHome => &mut config.wii.home,
+ BindTarget::NunchukC => &mut config.wii.nunchuk_c,
+ BindTarget::NunchukZ => &mut config.wii.nunchuk_z,
+ BindTarget::Shake => &mut config.wii.shake,
+ BindTarget::Recenter => &mut config.wii.recenter,
+ }
+}
+
+pub fn invert_field(config: &mut InputConfig, target: InvertTarget) -> &mut Option<bool> {
+ match target {
+ InvertTarget::GcStickX => &mut config.gc.invert_stick_x,
+ InvertTarget::GcStickY => &mut config.gc.invert_stick_y,
+ InvertTarget::GcCstickX => &mut config.gc.invert_cstick_x,
+ InvertTarget::GcCstickY => &mut config.gc.invert_cstick_y,
+ InvertTarget::NunchukX => &mut config.wii.invert_nunchuk_x,
+ InvertTarget::NunchukY => &mut config.wii.invert_nunchuk_y,
+ InvertTarget::StickDpadX => &mut config.wii.invert_stick_dpad_x,
+ InvertTarget::StickDpadY => &mut config.wii.invert_stick_dpad_y,
+ InvertTarget::PointerX => &mut config.wii.invert_pointer_x,
+ InvertTarget::PointerY => &mut config.wii.invert_pointer_y,
+ }
+}
+
+fn invert_value(config: &InputConfig, target: InvertTarget) -> bool {
+ let field = match target {
+ InvertTarget::GcStickX => &config.gc.invert_stick_x,
+ InvertTarget::GcStickY => &config.gc.invert_stick_y,
+ InvertTarget::GcCstickX => &config.gc.invert_cstick_x,
+ InvertTarget::GcCstickY => &config.gc.invert_cstick_y,
+ InvertTarget::NunchukX => &config.wii.invert_nunchuk_x,
+ InvertTarget::NunchukY => &config.wii.invert_nunchuk_y,
+ InvertTarget::StickDpadX => &config.wii.invert_stick_dpad_x,
+ InvertTarget::StickDpadY => &config.wii.invert_stick_dpad_y,
+ InvertTarget::PointerX => &config.wii.invert_pointer_x,
+ InvertTarget::PointerY => &config.wii.invert_pointer_y,
+ };
+
+ field.unwrap_or(false)
+}
+
+fn display_name(button: Button) -> &'static str {
+ match button {
+ Button::South => "South",
+ Button::East => "East",
+ Button::West => "West",
+ Button::North => "North",
+ Button::L1 => "L1",
+ Button::R1 => "R1",
+ Button::L2 => "L2",
+ Button::R2 => "R2",
+ Button::L3 => "L3",
+ Button::R3 => "R3",
+ Button::Start => "Start",
+ Button::Select => "Select",
+ Button::Guide => "Guide",
+ Button::DpadUp => "D-Pad Up",
+ Button::DpadDown => "D-Pad Down",
+ Button::DpadLeft => "D-Pad Left",
+ Button::DpadRight => "D-Pad Right",
+ Button::TouchpadClick => "Touchpad",
+ }
+}
+
+fn capitalize(s: &str) -> String {
+ let mut chars = s.chars();
+
+ match chars.next() {
+ Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
+ None => String::new(),
+ }
+}
+
+fn bound(buttons: &[(Button, u16)], mask: u16) -> String {
+ buttons
+ .iter()
+ .find(|(_, m)| *m == mask)
+ .map(|(b, _)| self::display_name(*b).to_owned())
+ .unwrap_or_else(|| "Unbound".to_owned())
+}
+
+fn effective(gc: &GcProfile, wii: &WiiProfile, target: BindTarget) -> String {
+ match target {
+ BindTarget::GcA => self::bound(&gc.buttons, pad::A),
+ BindTarget::GcB => self::bound(&gc.buttons, pad::B),
+ BindTarget::GcX => self::bound(&gc.buttons, pad::X),
+ BindTarget::GcY => self::bound(&gc.buttons, pad::Y),
+ BindTarget::GcStart => self::bound(&gc.buttons, pad::START),
+ BindTarget::GcZ => self::bound(&gc.buttons, pad::Z),
+ BindTarget::WiiA => self::bound(&wii.buttons, usb::BTN_A),
+ BindTarget::WiiB => self::bound(&wii.buttons, usb::BTN_B),
+ BindTarget::WiiOne => self::bound(&wii.buttons, usb::BTN_ONE),
+ BindTarget::WiiTwo => self::bound(&wii.buttons, usb::BTN_TWO),
+ BindTarget::WiiPlus => self::bound(&wii.buttons, usb::BTN_PLUS),
+ BindTarget::WiiMinus => self::bound(&wii.buttons, usb::BTN_MINUS),
+ BindTarget::WiiHome => self::bound(&wii.buttons, usb::BTN_HOME),
+ BindTarget::NunchukC => self::display_name(wii.nunchuk_c).to_owned(),
+ BindTarget::NunchukZ => self::display_name(wii.nunchuk_z).to_owned(),
+ BindTarget::Shake => wii
+ .shake
+ .map(|b| self::display_name(b).to_owned())
+ .unwrap_or_else(|| "None".to_owned()),
+ BindTarget::Recenter => self::display_name(wii.recenter).to_owned(),
+ }
+}
+
+pub fn pressed_button(fresh: u32) -> Option<Button> {
+ Button::ALL.iter().copied().find(|b| fresh & b.mask() != 0)
+}
+
+pub fn overlay(
+ palette: &Palette,
+ config: &InputConfig,
+ tab: InputTab,
+ capture: Option<BindTarget>,
+ pad: Option<&str>,
+) -> Element<'static, Message> {
+ let gc_profile = config.gc_profile();
+ let wii_profile = config.wii_profile();
+
+ let status = match pad {
+ Some(name) => text(name.to_owned()).size(11).color(palette.accent),
+ None => text("No gamepad detected").size(11).color(palette.text_mute),
+ };
+
+ let header = column![text("Controller Bindings").size(16).color(palette.text), status,].spacing(2);
+
+ let tabs = row![
+ self::chip(
+ palette,
+ "GameCube",
+ Message::InputTab(InputTab::Gc),
+ tab == InputTab::Gc
+ ),
+ self::chip(palette, "Wii", Message::InputTab(InputTab::Wii), tab == InputTab::Wii),
+ ]
+ .spacing(6);
+
+ let mut body = column![].spacing(4);
+
+ let targets: &[(BindTarget, &str)] = match tab {
+ InputTab::Gc => &GC_TARGETS,
+ InputTab::Wii => &WII_TARGETS,
+ };
+
+ for (target, label) in targets {
+ let value = if capture == Some(*target) {
+ "press a button".to_owned()
+ } else {
+ self::effective(&gc_profile, &wii_profile, *target)
+ };
+
+ body = body.push(self::binding_row(
+ palette,
+ label,
+ value,
+ *target,
+ capture == Some(*target),
+ ));
+ }
+
+ if tab == InputTab::Gc {
+ body = body
+ .push(self::separator(palette))
+ .push(self::invert_row(
+ palette,
+ config,
+ "Invert Stick",
+ InvertTarget::GcStickX,
+ InvertTarget::GcStickY,
+ ))
+ .push(self::invert_row(
+ palette,
+ config,
+ "Invert C-Stick",
+ InvertTarget::GcCstickX,
+ InvertTarget::GcCstickY,
+ ));
+ }
+
+ if tab == InputTab::Wii {
+ let options: Vec<String> = POINTER_SOURCES.iter().map(|s| s.to_string()).collect();
+ let selected = config.wii.pointer.as_deref().unwrap_or("auto").to_string();
+
+ let surface = palette.surface;
+ let surface_2 = palette.surface_2;
+ let border_2 = palette.border_2;
+ let text_dim = palette.text_dim;
+ let accent = palette.accent;
+ let pointer_row = row![
+ container(text("Pointer").size(13).color(palette.text_dim)).width(Length::Fixed(130.0)),
+ pick_list(Some(selected), options, |source: &String| self::capitalize(source))
+ .on_select(Message::InputPointer)
+ .text_size(12)
+ .padding(Padding::from([4, 10]))
+ .width(Length::Fixed(140.0))
+ .style(move |_, status| {
+ let bg = match status {
+ iced::widget::pick_list::Status::Hovered | iced::widget::pick_list::Status::Opened { .. } => {
+ surface_2
+ }
+ _ => surface,
+ };
+ iced::widget::pick_list::Style {
+ text_color: text_dim,
+ placeholder_color: text_dim,
+ handle_color: text_dim,
+ background: Background::Color(bg),
+ border: Border {
+ color: border_2,
+ width: 1.0,
+ radius: 6.0.into(),
+ },
+ }
+ })
+ .menu_style(move |_| iced::widget::overlay::menu::Style {
+ background: Background::Color(surface),
+ border: Border {
+ color: border_2,
+ width: 1.0,
+ radius: 6.0.into(),
+ },
+ text_color: text_dim,
+ selected_text_color: accent,
+ selected_background: Background::Color(surface_2),
+ shadow: iced::Shadow::default(),
+ }),
+ ]
+ .spacing(6)
+ .align_y(Alignment::Center);
+
+ let sensitivity = wii_profile.sensitivity;
+ let sensitivity_row = row![
+ container(text("Sensitivity").size(13).color(palette.text_dim)).width(Length::Fixed(130.0)),
+ self::chip(palette, "-", Message::InputSensitivity(-0.25), false),
+ container(text(format!("{sensitivity:.2}")).size(13).color(palette.text))
+ .width(Length::Fixed(48.0))
+ .align_x(Alignment::Center),
+ self::chip(palette, "+", Message::InputSensitivity(0.25), false),
+ ]
+ .spacing(6)
+ .align_y(Alignment::Center);
+
+ let toggles = row![
+ container(text("Options").size(13).color(palette.text_dim)).width(Length::Fixed(130.0)),
+ self::chip(palette, "Sideways", Message::InputToggleSideways, wii_profile.sideways),
+ self::chip(
+ palette,
+ "Stick D-Pad",
+ Message::InputToggleStickDpad,
+ wii_profile.stick_dpad
+ ),
+ ]
+ .spacing(6)
+ .align_y(Alignment::Center);
+
+ body = body
+ .push(self::separator(palette))
+ .push(pointer_row)
+ .push(sensitivity_row)
+ .push(toggles)
+ .push(self::invert_row(
+ palette,
+ config,
+ "Invert Nunchuk",
+ InvertTarget::NunchukX,
+ InvertTarget::NunchukY,
+ ))
+ .push(self::invert_row(
+ palette,
+ config,
+ "Invert Stick D-Pad",
+ InvertTarget::StickDpadX,
+ InvertTarget::StickDpadY,
+ ))
+ .push(self::invert_row(
+ palette,
+ config,
+ "Invert Pointer",
+ InvertTarget::PointerX,
+ InvertTarget::PointerY,
+ ));
+ }
+
+ let footer = row![
+ self::chip(palette, "Reset to Defaults", Message::InputReset, false),
+ container(text("")).width(Length::Fill),
+ self::chip(palette, "Close", Message::InputClose, false),
+ ]
+ .align_y(Alignment::Center);
+
+ let card_col = column![header, tabs, body, footer].spacing(14);
+
+ overlay::modal(palette, 360.0, 20.0, Message::InputClose, card_col.into())
+}
+
+fn control_style(
+ surface: Color,
+ surface_2: Color,
+ border: Color,
+ text_color: Color,
+) -> impl Fn(&iced::Theme, button::Status) -> button::Style {
+ move |_, status| {
+ let bg = match status {
+ button::Status::Hovered | button::Status::Pressed => surface_2,
+ _ => surface,
+ };
+
+ button::Style {
+ background: Some(Background::Color(bg)),
+ text_color,
+ border: Border {
+ color: border,
+ width: 1.0,
+ radius: 6.0.into(),
+ },
+ ..button::Style::default()
+ }
+ }
+}
+
+fn binding_row(
+ palette: &Palette,
+ label: &'static str,
+ value: String,
+ target: BindTarget,
+ capturing: bool,
+) -> Element<'static, Message> {
+ let value_color = if capturing { palette.accent } else { palette.text_dim };
+ let border = if capturing { palette.accent } else { palette.border_2 };
+
+ let bind = button(
+ container(text(value).size(12).color(value_color))
+ .width(Length::Fill)
+ .align_x(Alignment::Center),
+ )
+ .width(Length::Fixed(180.0))
+ .padding(Padding::from([4, 10]))
+ .on_press(Message::InputCapture(target))
+ .style(self::control_style(
+ palette.surface,
+ palette.surface_2,
+ border,
+ value_color,
+ ));
+
+ row![
+ container(text(label).size(13).color(palette.text)).width(Length::Fixed(130.0)),
+ bind,
+ ]
+ .spacing(6)
+ .align_y(Alignment::Center)
+ .into()
+}
+
+fn separator(palette: &Palette) -> Element<'static, Message> {
+ let color = palette.border;
+
+ container(
+ container(text(""))
+ .width(Length::Fill)
+ .height(1)
+ .style(move |_| container::Style {
+ background: Some(Background::Color(color)),
+ ..container::Style::default()
+ }),
+ )
+ .padding(Padding::from([6, 0]))
+ .into()
+}
+
+fn invert_row(
+ palette: &Palette,
+ config: &InputConfig,
+ label: &'static str,
+ x: InvertTarget,
+ y: InvertTarget,
+) -> Element<'static, Message> {
+ row![
+ container(text(label).size(13).color(palette.text_dim)).width(Length::Fixed(130.0)),
+ self::chip(
+ palette,
+ "X",
+ Message::InputToggleInvert(x),
+ self::invert_value(config, x)
+ ),
+ self::chip(
+ palette,
+ "Y",
+ Message::InputToggleInvert(y),
+ self::invert_value(config, y)
+ ),
+ ]
+ .spacing(6)
+ .align_y(Alignment::Center)
+ .into()
+}
+
+fn chip(palette: &Palette, label: &'static str, msg: Message, selected: bool) -> Element<'static, Message> {
+ let text_color = if selected { palette.accent } else { palette.text_dim };
+ let border = if selected { palette.accent } else { palette.border_2 };
+
+ button(text(label).size(12).color(text_color))
+ .padding(Padding::from([4, 10]))
+ .on_press(msg)
+ .style(self::control_style(
+ palette.surface,
+ palette.surface_2,
+ border,
+ text_color,
+ ))
+ .into()
+}
diff --git a/crates/app/src/widgets/menubar.rs b/crates/app/src/widgets/menubar.rs
index afd02c5..116223f 100644
--- a/crates/app/src/widgets/menubar.rs
+++ b/crates/app/src/widgets/menubar.rs
@@ -253,6 +253,14 @@ fn settings_menu(
Message::MenuSetTheme(ThemePreference::Dark),
Some(theme_pref == ThemePreference::Dark),
)),
+ Item::new(self::separator(palette)),
+ Item::new(self::section_header(palette, "Input")),
+ Item::new(self::menu_item(
+ palette,
+ "Controller Bindings",
+ Message::MenuInputSettings,
+ None,
+ )),
])
.max_width(240.0)
.offset(4.0)
diff --git a/crates/app/src/widgets/overlay.rs b/crates/app/src/widgets/overlay.rs
new file mode 100644
index 0000000..1563dd0
--- /dev/null
+++ b/crates/app/src/widgets/overlay.rs
@@ -0,0 +1,53 @@
+use iced::widget::{container, mouse_area, stack, text};
+use iced::{Background, Border, Color, Element, Length};
+
+use crate::app::Message;
+use crate::theme::Palette;
+
+pub fn modal(
+ palette: &Palette,
+ width: f32,
+ padding: f32,
+ on_close: Message,
+ content: Element<'static, Message>,
+) -> Element<'static, Message> {
+ let bg = palette.bg;
+ let border_2 = palette.border_2;
+ let backdrop_color = Color {
+ a: 0.45,
+ ..(if palette.is_dark { Color::BLACK } else { palette.text })
+ };
+
+ let backdrop: Element<'static, Message> = mouse_area(
+ container(text(""))
+ .width(Length::Fill)
+ .height(Length::Fill)
+ .style(move |_| container::Style {
+ background: Some(Background::Color(backdrop_color)),
+ ..container::Style::default()
+ }),
+ )
+ .on_press(on_close)
+ .into();
+
+ let card = container(content)
+ .width(Length::Fixed(width))
+ .padding(padding)
+ .style(move |_| container::Style {
+ background: Some(Background::Color(bg)),
+ border: Border {
+ color: border_2,
+ width: 1.0,
+ radius: 12.0.into(),
+ },
+ ..container::Style::default()
+ });
+
+ let centered = container(card)
+ .width(Length::Fill)
+ .height(Length::Fill)
+ .center_x(Length::Fill)
+ .center_y(Length::Fill);
+
+ stack![backdrop, centered].into()
+}
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rs
index b9b321d..3b0a17d 100644
--- a/crates/debugger/src/main.rs
+++ b/crates/debugger/src/main.rs
@@ -264,7 +264,7 @@ impl ApplicationHandler<UserEvent> for App {
nunchuk_buttons,
nunchuk_stick_x,
nunchuk_stick_y,
- ir_pointer: _,
+ ..
} => {
update_wiimote_keys(wiimote_buttons, key, pressed);
update_wiimote_motion_keys(wiimote_shake, key, pressed);
diff --git a/crates/gecko/src/flipper/si.rs b/crates/gecko/src/flipper/si.rs
index f7eb3c6..876c6ff 100644
--- a/crates/gecko/src/flipper/si.rs
+++ b/crates/gecko/src/flipper/si.rs
@@ -32,6 +32,7 @@ pub struct SerialInterface {
pub exi_clock_count: u32,
pub io_buffer: [u8; 128],
pub pad_state: [PadStatus; NUM_CHANNELS],
+ pub rumble_motor: [u8; NUM_CHANNELS],
}
impl SerialInterface {
@@ -44,9 +45,15 @@ impl SerialInterface {
exi_clock_count: 0,
io_buffer: [0u8; 128],
pad_state: [PadStatus::default(); NUM_CHANNELS],
+ rumble_motor: [0; NUM_CHANNELS],
}
}
+ #[inline(always)]
+ pub fn rumble(&self, channel: usize) -> bool {
+ self.rumble_motor[channel] == 1
+ }
+
#[inline(always)]
pub fn interrupt_active(&self) -> bool {
(self.comcsr.tc_interrupt() && self.comcsr.tc_interrupt_mask())
@@ -120,6 +127,11 @@ impl SerialInterface {
// EN0 is bit 7 of the 4-bit enable field, EN3 is bit 4
let ch_enabled = (enable >> (3 - ch)) & 1 != 0;
if ch_enabled && self.pad_state[ch].connected {
+ let out = self.channels[ch].out;
+ if (out >> 16) & 0xFF == 0x40 {
+ self.rumble_motor[ch] = (out & 0x03) as u8;
+ }
+
self.channels[ch].in_hi = self.pad_state[ch].encode_hi();
self.channels[ch].in_lo = self.pad_state[ch].encode_lo();
self.set_rdst(ch);
@@ -147,6 +159,8 @@ impl SerialInterface {
}
// Return current pad data (8 bytes).
0x40 => {
+ self.rumble_motor[channel] = self.io_buffer[2] & 0x03;
+
let hi = self.pad_state[channel].encode_hi();
let lo = self.pad_state[channel].encode_lo();
self.io_buffer[0..4].copy_from_slice(&hi.to_be_bytes());
diff --git a/crates/gecko/src/hollywood/ipc.rs b/crates/gecko/src/hollywood/ipc.rs
index 74a57ae..9649556 100644
--- a/crates/gecko/src/hollywood/ipc.rs
+++ b/crates/gecko/src/hollywood/ipc.rs
@@ -99,6 +99,12 @@ pub trait IosDevice: Send {
fn set_wiimote_shake(&mut self, _active: bool) {}
+ fn set_wiimote_accel(&mut self, _accel: Option<[f32; 3]>) {}
+
+ fn wiimote_rumble(&self) -> bool {
+ false
+ }
+
fn set_nunchuk(&mut self, _buttons: u8, _stick_x: u8, _stick_y: u8) -> bool {
false
}
diff --git a/crates/gecko/src/hollywood/ipc/usb.rs b/crates/gecko/src/hollywood/ipc/usb.rs
index 6639959..40b1aa7 100644
--- a/crates/gecko/src/hollywood/ipc/usb.rs
+++ b/crates/gecko/src/hollywood/ipc/usb.rs
@@ -67,6 +67,14 @@ impl IosDevice for Bluetooth {
Bluetooth::set_wiimote_shake(self, active)
}
+ fn set_wiimote_accel(&mut self, accel: Option<[f32; 3]>) {
+ self.wiimote.set_accel(accel);
+ }
+
+ fn wiimote_rumble(&self) -> bool {
+ self.wiimote.rumble()
+ }
+
fn set_nunchuk(&mut self, buttons: u8, stick_x: u8, stick_y: u8) -> bool {
Bluetooth::set_nunchuk(self, buttons, stick_x, stick_y)
}
diff --git a/crates/gecko/src/hollywood/ipc/usb/wiimote.rs b/crates/gecko/src/hollywood/ipc/usb/wiimote.rs
index 52ff7b1..79bb202 100644
--- a/crates/gecko/src/hollywood/ipc/usb/wiimote.rs
+++ b/crates/gecko/src/hollywood/ipc/usb/wiimote.rs
@@ -160,8 +160,10 @@ pub(super) struct WiimoteState {
nunchuk_cipher: Cipher,
ir_pointer: Option<(u16, u16)>,
accel: [u8; 3],
+ accel_override: Option<[u8; 3]>,
shake_active: bool,
shake_phase: f32,
+ rumble: bool,
dirty: bool,
}
@@ -193,8 +195,10 @@ impl Default for WiimoteState {
nunchuk_cipher: Cipher::IDENTITY,
ir_pointer: None,
accel: ACCEL_REST,
+ accel_override: None,
shake_active: false,
shake_phase: 0.0,
+ rumble: false,
dirty: false,
}
}
@@ -222,7 +226,26 @@ impl WiimoteState {
self.shake_active = active;
}
+ pub(super) fn rumble(&self) -> bool {
+ self.rumble
+ }
+
+ pub(super) fn set_accel(&mut self, accel: Option<[f32; 3]>) {
+ self.accel_override = accel.map(|g| [encode_wiimote_g(g[0]), encode_wiimote_g(g[1]), encode_wiimote_g(g[2])]);
+ }
+
pub(super) fn tick_motion(&mut self) {
+ if let Some(accel) = self.accel_override {
+ self.shake_phase = 0.0;
+
+ if self.accel != accel {
+ self.accel = accel;
+ self.dirty = true;
+ }
+
+ return;
+ }
+
if self.shake_active {
self.shake_phase = (self.shake_phase + SHAKE_PHASE_STEP) % (2.0 * std::f32::consts::PI);
let g = SHAKE_AMPLITUDE_G * self.shake_phase.sin();
@@ -352,6 +375,8 @@ impl WiimoteState {
tracing::debug!(report_id = ?report_id, "received Wiimote output report");
+ self.rumble = body.first().is_some_and(|b| b & 0x01 != 0);
+
match report_id {
OutputReportId::Rumble
| OutputReportId::SpeakerEnable
diff --git a/crates/gecko/src/input.rs b/crates/gecko/src/input.rs
index 772c777..1c5f050 100644
--- a/crates/gecko/src/input.rs
+++ b/crates/gecko/src/input.rs
@@ -8,6 +8,8 @@ use std::sync::{Arc, Mutex};
/// state available.
pub trait InputSink: Send {
fn sample(&mut self) -> HostInput;
+
+ fn set_rumble(&mut self, _port: usize, _on: bool) {}
}
impl InputSink for Arc<Mutex<HostInput>> {
@@ -26,9 +28,29 @@ pub enum HostInput {
nunchuk_stick_x: u8,
nunchuk_stick_y: u8,
ir_pointer: Option<(u16, u16)>,
+ accel: Option<[f32; 3]>,
},
}
+pub fn aim_to_ir(aim_x: f32, aim_y: f32) -> (u16, u16) {
+ const POINTER_SCALE_X: f64 = 0.44;
+ const POINTER_SCALE_Y: f64 = 0.66;
+ const POINTER_Y_OFFSET: f64 = 120.0;
+
+ let aim_x = (aim_x as f64).clamp(0.0, 1.0);
+ let aim_y = (aim_y as f64).clamp(0.0, 1.0);
+
+ let span_x = usb::IR_CAMERA_WIDTH as f64 * POINTER_SCALE_X;
+ let span_y = usb::IR_CAMERA_HEIGHT as f64 * POINTER_SCALE_Y;
+ let base_x = (usb::IR_CAMERA_WIDTH as f64 - span_x) / 2.0;
+ let base_y = (usb::IR_CAMERA_HEIGHT as f64 - span_y) / 2.0 + POINTER_Y_OFFSET;
+
+ let ir_x = (base_x + (1.0 - aim_x) * span_x) as u16;
+ let ir_y = (base_y + aim_y * span_y) as u16;
+
+ (ir_x, ir_y)
+}
+
impl HostInput {
pub fn gc_connected() -> Self {
Self::Gc(pad::PadStatus {
@@ -45,6 +67,7 @@ impl HostInput {
nunchuk_stick_x: usb::NUNCHUK_STICK_CENTER,
nunchuk_stick_y: usb::NUNCHUK_STICK_CENTER,
ir_pointer: None,
+ accel: None,
}
}
diff --git a/crates/gecko/src/scheduler.rs b/crates/gecko/src/scheduler.rs
index d6038b0..869d2b3 100644
--- a/crates/gecko/src/scheduler.rs
+++ b/crates/gecko/src/scheduler.rs
@@ -156,12 +156,7 @@ impl<const SYSTEM: SystemId> Scheduler<SYSTEM> {
crate::flipper::cp::PUMP_INTERVAL_CYCLES,
crate::flipper::cp::pump_handler::<SYSTEM>,
);
- if SYSTEM == system::WII {
- s.schedule_at(
- self::wiimote_report_interval(SYSTEM),
- self::wiimote_report_handler::<SYSTEM>,
- );
- }
+ s.schedule_at(self::input_poll_interval(SYSTEM), self::input_poll_handler::<SYSTEM>);
#[cfg(feature = "fps-counter")]
s.schedule_at(self::cpu_clock(SYSTEM), crate::fps::fps_handler::<SYSTEM>);
s
@@ -193,21 +188,22 @@ pub fn reseed_vsync<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {
}
#[inline(always)]
-pub const fn wiimote_report_interval(system: SystemId) -> u64 {
+pub const fn input_poll_interval(system: SystemId) -> u64 {
self::cpu_clock(system) / crate::hollywood::ipc::usb::REPORT_HZ
}
/// Reschedules itself at the Wiimote's 200Hz (TODO VERIFY) report rate. Samples
-/// fresh host input and emits one HID input report per tick (continuous
-/// mode) or only on change (non continuous).
-pub fn wiimote_report_handler<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {
+/// fresh host input on both systems and, on Wii, emits one HID input report
+/// per tick (continuous mode) or only on change (non continuous).
+pub fn input_poll_handler<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {
sys.sample_host_input();
- sys.starlet.tick_wiimote();
- sys.scheduler.schedule_in(
- self::wiimote_report_interval(SYSTEM),
- self::wiimote_report_handler::<SYSTEM>,
- );
+ if SYSTEM == system::WII {
+ sys.starlet.tick_wiimote();
+ }
+
+ sys.scheduler
+ .schedule_in(self::input_poll_interval(SYSTEM), self::input_poll_handler::<SYSTEM>);
}
#[inline(always)]
diff --git a/crates/gecko/src/starlet.rs b/crates/gecko/src/starlet.rs
index b7fc24d..47d29c0 100644
--- a/crates/gecko/src/starlet.rs
+++ b/crates/gecko/src/starlet.rs
@@ -119,6 +119,18 @@ impl Starlet {
}
}
+ pub fn set_wiimote_accel(&mut self, accel: Option<[f32; 3]>) {
+ if let Some(dev) = self.devices.get_mut(WIIMOTE_DEVICE_PATH) {
+ dev.set_wiimote_accel(accel);
+ }
+ }
+
+ pub fn wiimote_rumble(&self) -> bool {
+ self.devices
+ .get(WIIMOTE_DEVICE_PATH)
+ .is_some_and(|dev| dev.wiimote_rumble())
+ }
+
pub fn set_nunchuk(&mut self, buttons: u8, stick_x: u8, stick_y: u8) -> bool {
self.devices
.get_mut(WIIMOTE_DEVICE_PATH)
diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rs
index 295c766..4e91389 100644
--- a/crates/gecko/src/system.rs
+++ b/crates/gecko/src/system.rs
@@ -1,4 +1,3 @@
-use crate::input::InputSink;
use crate::HostInput;
use crate::audio::{AudioSink, EmptyAudioSink};
use crate::dvd::DvdInterface;
@@ -19,6 +18,7 @@ use crate::hollywood::Hollywood;
#[cfg(feature = "hooks")]
use crate::hooks::{HookFilters, HookFlags, HookState, Host};
use crate::host::{EmptyRenderSink, RenderSink};
+use crate::input::InputSink;
use crate::mmio::Mmio;
use crate::scheduler::Scheduler;
use crate::starlet::Starlet;
@@ -664,6 +664,16 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {
let input = sink.sample();
self.apply_host_input(&input);
+
+ let rumble = if SYSTEM == WII {
+ self.starlet.wiimote_rumble()
+ } else {
+ self.si.rumble(0)
+ };
+
+ if let Some(sink) = self.input_sink.as_mut() {
+ sink.set_rumble(0, rumble);
+ }
}
pub fn apply_host_input(&mut self, input: &HostInput) {
@@ -678,12 +688,14 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {
nunchuk_stick_x,
nunchuk_stick_y,
ir_pointer,
+ accel,
} if SYSTEM == WII => {
self.starlet.set_wiimote_buttons(*wiimote_buttons);
self.starlet.set_wiimote_shake(*wiimote_shake);
self.starlet
.set_nunchuk(*nunchuk_buttons, *nunchuk_stick_x, *nunchuk_stick_y);
self.starlet.set_ir_pointer(*ir_pointer);
+ self.starlet.set_wiimote_accel(*accel);
}
_ => unreachable!("invalid host input for system"),
}
diff --git a/crates/hostinput/Cargo.toml b/crates/hostinput/Cargo.toml
new file mode 100644
index 0000000..990cad8
--- /dev/null
+++ b/crates/hostinput/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "hostinput"
+version = "0.1.0"
+edition = "2024"
+
+[[bin]]
+name = "input-probe"
+path = "src/probe.rs"
+
+[dependencies]
+gecko = { path = "../gecko", default-features = false }
+sdl3 = { version = "0.18.4", features = ["build-from-source-static", "hidapi"] }
+serde = { version = "1.0.228", features = ["derive"] }
+tracing = "0.1.44"
+tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
diff --git a/crates/hostinput/src/config.rs b/crates/hostinput/src/config.rs
new file mode 100644
index 0000000..6d5ac9b
--- /dev/null
+++ b/crates/hostinput/src/config.rs
@@ -0,0 +1,216 @@
+use crate::device::Button;
+use crate::mapping::{GcProfile, PointerSource, WiiProfile};
+use gecko::flipper::si::pad;
+use gecko::hollywood::ipc::usb;
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(default)]
+pub struct InputConfig {
+ pub gamepads: bool,
+ pub gc: GcConfig,
+ pub wii: WiiConfig,
+}
+
+impl Default for InputConfig {
+ fn default() -> Self {
+ Self {
+ gamepads: true,
+ gc: GcConfig::default(),
+ wii: WiiConfig::default(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct GcConfig {
+ pub a: Option<String>,
+ pub b: Option<String>,
+ pub x: Option<String>,
+ pub y: Option<String>,
+ pub start: Option<String>,
+ pub z: Option<String>,
+ pub invert_stick_x: Option<bool>,
+ pub invert_stick_y: Option<bool>,
+ pub invert_cstick_x: Option<bool>,
+ pub invert_cstick_y: Option<bool>,
+ pub deadzone: Option<f32>,
+}
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct WiiConfig {
+ pub a: Option<String>,
+ pub b: Option<String>,
+ pub one: Option<String>,
+ pub two: Option<String>,
+ pub plus: Option<String>,
+ pub minus: Option<String>,
+ pub home: Option<String>,
+ pub nunchuk_c: Option<String>,
+ pub nunchuk_z: Option<String>,
+ pub shake: Option<String>,
+ pub recenter: Option<String>,
+ pub pointer: Option<String>,
+ pub pointer_sensitivity: Option<f32>,
+ pub sideways: Option<bool>,
+ pub stick_dpad: Option<bool>,
+ pub invert_nunchuk_x: Option<bool>,
+ pub invert_nunchuk_y: Option<bool>,
+ pub invert_stick_dpad_x: Option<bool>,
+ pub invert_stick_dpad_y: Option<bool>,
+ pub invert_pointer_x: Option<bool>,
+ pub invert_pointer_y: Option<bool>,
+ pub deadzone: Option<f32>,
+}
+
+pub fn button_name(button: Button) -> &'static str {
+ match button {
+ Button::South => "south",
+ Button::East => "east",
+ Button::West => "west",
+ Button::North => "north",
+ Button::L1 => "l1",
+ Button::R1 => "r1",
+ Button::L2 => "l2",
+ Button::R2 => "r2",
+ Button::L3 => "l3",
+ Button::R3 => "r3",
+ Button::Start => "start",
+ Button::Select => "select",
+ Button::Guide => "guide",
+ Button::DpadUp => "dpad_up",
+ Button::DpadDown => "dpad_down",
+ Button::DpadLeft => "dpad_left",
+ Button::DpadRight => "dpad_right",
+ Button::TouchpadClick => "touchpad",
+ }
+}
+
+pub fn parse_button(name: &str) -> Option<Button> {
+ Some(match name {
+ "south" => Button::South,
+ "east" => Button::East,
+ "west" => Button::West,
+ "north" => Button::North,
+ "l1" => Button::L1,
+ "r1" => Button::R1,
+ "l2" => Button::L2,
+ "r2" => Button::R2,
+ "l3" => Button::L3,
+ "r3" => Button::R3,
+ "start" => Button::Start,
+ "select" => Button::Select,
+ "guide" => Button::Guide,
+ "dpad_up" => Button::DpadUp,
+ "dpad_down" => Button::DpadDown,
+ "dpad_left" => Button::DpadLeft,
+ "dpad_right" => Button::DpadRight,
+ "touchpad" => Button::TouchpadClick,
+ _ => return None,
+ })
+}
+
+fn warn_parse(name: &str) -> Option<Button> {
+ let button = self::parse_button(name);
+
+ if button.is_none() {
+ tracing::warn!(name, "unknown input button name, keeping default");
+ }
+
+ button
+}
+
+fn rebind(buttons: &mut Vec<(Button, u16)>, mask: u16, name: &Option<String>) {
+ let Some(button) = name.as_deref().and_then(self::warn_parse) else {
+ return;
+ };
+
+ buttons.retain(|(_, m)| *m != mask);
+ buttons.push((button, mask));
+}
+
+fn button_or(name: &Option<String>, default: Button) -> Button {
+ name.as_deref().and_then(self::warn_parse).unwrap_or(default)
+}
+
+impl InputConfig {
+ pub fn gc_profile(&self) -> GcProfile {
+ let mut profile = GcProfile::default();
+
+ self::rebind(&mut profile.buttons, pad::A, &self.gc.a);
+ self::rebind(&mut profile.buttons, pad::B, &self.gc.b);
+ self::rebind(&mut profile.buttons, pad::X, &self.gc.x);
+ self::rebind(&mut profile.buttons, pad::Y, &self.gc.y);
+ self::rebind(&mut profile.buttons, pad::START, &self.gc.start);
+ self::rebind(&mut profile.buttons, pad::Z, &self.gc.z);
+
+ profile.stick_invert.x = self.gc.invert_stick_x.unwrap_or(profile.stick_invert.x);
+ profile.stick_invert.y = self.gc.invert_stick_y.unwrap_or(profile.stick_invert.y);
+ profile.substick_invert.x = self.gc.invert_cstick_x.unwrap_or(profile.substick_invert.x);
+ profile.substick_invert.y = self.gc.invert_cstick_y.unwrap_or(profile.substick_invert.y);
+
+ if let Some(deadzone) = self.gc.deadzone {
+ profile.deadzone = deadzone.clamp(0.0, 0.9);
+ }
+
+ profile
+ }
+
+ pub fn wii_profile(&self) -> WiiProfile {
+ let mut profile = WiiProfile::default();
+
+ self::rebind(&mut profile.buttons, usb::BTN_A, &self.wii.a);
+ self::rebind(&mut profile.buttons, usb::BTN_B, &self.wii.b);
+ self::rebind(&mut profile.buttons, usb::BTN_ONE, &self.wii.one);
+ self::rebind(&mut profile.buttons, usb::BTN_TWO, &self.wii.two);
+ self::rebind(&mut profile.buttons, usb::BTN_PLUS, &self.wii.plus);
+ self::rebind(&mut profile.buttons, usb::BTN_MINUS, &self.wii.minus);
+ self::rebind(&mut profile.buttons, usb::BTN_HOME, &self.wii.home);
+
+ profile.nunchuk_c = self::button_or(&self.wii.nunchuk_c, profile.nunchuk_c);
+ profile.nunchuk_z = self::button_or(&self.wii.nunchuk_z, profile.nunchuk_z);
+ profile.recenter = self::button_or(&self.wii.recenter, profile.recenter);
+
+ profile.shake = match self.wii.shake.as_deref() {
+ Some("none") => None,
+ Some(name) => self::warn_parse(name).or(profile.shake),
+ None => profile.shake,
+ };
+
+ profile.pointer = match self.wii.pointer.as_deref() {
+ Some("auto") | None => PointerSource::Auto,
+ Some("gyro") => PointerSource::Gyro,
+ Some("stick") => PointerSource::RightStick,
+ Some("touchpad") => PointerSource::Touchpad,
+ Some("mouse") => PointerSource::Mouse,
+ Some(other) => {
+ tracing::warn!(other, "unknown pointer source, using auto");
+ PointerSource::Auto
+ }
+ };
+
+ if let Some(sensitivity) = self.wii.pointer_sensitivity {
+ profile.sensitivity = sensitivity.clamp(0.1, 10.0);
+ }
+ if let Some(sideways) = self.wii.sideways {
+ profile.sideways = sideways;
+ }
+ if let Some(stick_dpad) = self.wii.stick_dpad {
+ profile.stick_dpad = stick_dpad;
+ }
+
+ profile.nunchuk_invert.x = self.wii.invert_nunchuk_x.unwrap_or(profile.nunchuk_invert.x);
+ profile.nunchuk_invert.y = self.wii.invert_nunchuk_y.unwrap_or(profile.nunchuk_invert.y);
+ profile.stick_dpad_invert.x = self.wii.invert_stick_dpad_x.unwrap_or(profile.stick_dpad_invert.x);
+ profile.stick_dpad_invert.y = self.wii.invert_stick_dpad_y.unwrap_or(profile.stick_dpad_invert.y);
+ profile.pointer_invert.x = self.wii.invert_pointer_x.unwrap_or(profile.pointer_invert.x);
+ profile.pointer_invert.y = self.wii.invert_pointer_y.unwrap_or(profile.pointer_invert.y);
+ if let Some(deadzone) = self.wii.deadzone {
+ profile.deadzone = deadzone.clamp(0.0, 0.9);
+ }
+
+ profile
+ }
+}
diff --git a/crates/hostinput/src/device.rs b/crates/hostinput/src/device.rs
new file mode 100644
index 0000000..adcd5c0
--- /dev/null
+++ b/crates/hostinput/src/device.rs
@@ -0,0 +1,80 @@
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Button {
+ South,
+ East,
+ West,
+ North,
+ L1,
+ R1,
+ L2,
+ R2,
+ L3,
+ R3,
+ Start,
+ Select,
+ Guide,
+ DpadUp,
+ DpadDown,
+ DpadLeft,
+ DpadRight,
+ TouchpadClick,
+}
+
+impl Button {
+ pub const ALL: [Button; 18] = [
+ Button::South,
+ Button::East,
+ Button::West,
+ Button::North,
+ Button::L1,
+ Button::R1,
+ Button::L2,
+ Button::R2,
+ Button::L3,
+ Button::R3,
+ Button::Start,
+ Button::Select,
+ Button::Guide,
+ Button::DpadUp,
+ Button::DpadDown,
+ Button::DpadLeft,
+ Button::DpadRight,
+ Button::TouchpadClick,
+ ];
+
+ pub const fn mask(self) -> u32 {
+ 1 << self as u32
+ }
+}
+
+#[derive(Clone, Copy, Default, Debug)]
+pub struct DeviceState {
+ pub buttons: u32,
+ pub left: (f32, f32),
+ pub right: (f32, f32),
+ pub l2: f32,
+ pub r2: f32,
+ pub accel: [f32; 3],
+}
+
+impl DeviceState {
+ pub fn pressed(&self, button: Button) -> bool {
+ self.buttons & button.mask() != 0
+ }
+}
+
+#[derive(Clone, Copy, Default, Debug)]
+pub struct Capabilities {
+ pub analog_sticks: bool,
+ pub gyro: bool,
+ pub accel: bool,
+ pub rumble: bool,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct PortInput {
+ pub state: DeviceState,
+ pub caps: Capabilities,
+ pub pointer: Option<(u16, u16)>,
+ pub touch: Option<(f32, f32)>,
+}
diff --git a/crates/hostinput/src/lib.rs b/crates/hostinput/src/lib.rs
new file mode 100644
index 0000000..c5e9568
--- /dev/null
+++ b/crates/hostinput/src/lib.rs
@@ -0,0 +1,11 @@
+pub mod config;
+pub mod device;
+pub mod manager;
+pub mod mapping;
+pub mod merge;
+pub mod motion;
+pub mod sdl;
+
+pub use config::InputConfig;
+pub use device::Button;
+pub use manager::InputManager;
diff --git a/crates/hostinput/src/manager.rs b/crates/hostinput/src/manager.rs
new file mode 100644
index 0000000..f3f5b60
--- /dev/null
+++ b/crates/hostinput/src/manager.rs
@@ -0,0 +1,85 @@
+use crate::config::InputConfig;
+use crate::device::{Capabilities, PortInput};
+use crate::mapping::{GcProfile, PointerSource, WiiProfile};
+use crate::{mapping, merge, sdl};
+use gecko::{GC, HostInput, InputSink, SystemId, WII};
+use std::sync::atomic::Ordering;
+use std::sync::{Arc, Mutex};
+
+pub struct InputManager {
+ system: SystemId,
+ keyboard: Arc<Mutex<HostInput>>,
+ gc_profile: GcProfile,
+ wii_profile: WiiProfile,
+ service: Option<&'static sdl::Service>,
+}
+
+impl InputManager {
+ pub fn new(system: SystemId, config: &InputConfig, keyboard: Arc<Mutex<HostInput>>) -> Self {
+ let gc_profile = config.gc_profile();
+ let wii_profile = config.wii_profile();
+
+ let service = config.gamepads.then(|| {
+ let service = sdl::service();
+
+ *service.motion.lock().unwrap() = sdl::MotionSettings {
+ sensitivity: wii_profile.sensitivity,
+ recenter: wii_profile.recenter,
+ invert: (wii_profile.pointer_invert.x, wii_profile.pointer_invert.y),
+ };
+
+ service
+ });
+
+ Self {
+ system,
+ keyboard,
+ gc_profile,
+ wii_profile,
+ service,
+ }
+ }
+}
+
+fn resolve_pointer(profile: PointerSource, caps: &Capabilities) -> PointerSource {
+ match profile {
+ PointerSource::Auto if caps.gyro => PointerSource::Gyro,
+ PointerSource::Auto if caps.analog_sticks => PointerSource::RightStick,
+ PointerSource::Auto => PointerSource::Mouse,
+ forced => forced,
+ }
+}
+
+impl InputSink for InputManager {
+ fn sample(&mut self) -> HostInput {
+ let kb = *self.keyboard.lock().unwrap();
+
+ let Some(service) = self.service else {
+ return kb;
+ };
+
+ let port: Option<PortInput> = *service.shared.lock().unwrap();
+
+ let Some(port) = port else {
+ return kb;
+ };
+
+ match (self.system, kb) {
+ (GC, HostInput::Gc(kb_pad)) => {
+ HostInput::Gc(merge::gc(mapping::gc::map(&port.state, &self.gc_profile), kb_pad))
+ }
+ (WII, kb @ HostInput::Wii { .. }) => {
+ let source = self::resolve_pointer(self.wii_profile.pointer, &port.caps);
+
+ merge::wii(mapping::wii::map(&port, &self.wii_profile, source), kb)
+ }
+ _ => kb,
+ }
+ }
+
+ fn set_rumble(&mut self, _port: usize, on: bool) {
+ if let Some(service) = self.service {
+ service.rumble.store(on, Ordering::Relaxed);
+ }
+ }
+}
diff --git a/crates/hostinput/src/mapping.rs b/crates/hostinput/src/mapping.rs
new file mode 100644
index 0000000..586e13e
--- /dev/null
+++ b/crates/hostinput/src/mapping.rs
@@ -0,0 +1,124 @@
+pub mod gc;
+pub mod wii;
+
+use crate::device::Button;
+use gecko::flipper::si::pad;
+use gecko::hollywood::ipc::usb;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum PointerSource {
+ Auto,
+ Gyro,
+ RightStick,
+ Touchpad,
+ Mouse,
+}
+
+#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
+pub struct Invert {
+ pub x: bool,
+ pub y: bool,
+}
+
+impl Invert {
+ pub fn apply(self, v: (f32, f32)) -> (f32, f32) {
+ (if self.x { -v.0 } else { v.0 }, if self.y { -v.1 } else { v.1 })
+ }
+}
+
+pub struct GcProfile {
+ pub buttons: Vec<(Button, u16)>,
+ pub stick_invert: Invert,
+ pub substick_invert: Invert,
+ pub deadzone: f32,
+}
+
+impl Default for GcProfile {
+ fn default() -> Self {
+ Self {
+ buttons: vec![
+ (Button::South, pad::A),
+ (Button::East, pad::X),
+ (Button::West, pad::B),
+ (Button::North, pad::Y),
+ (Button::Start, pad::START),
+ (Button::R1, pad::Z),
+ (Button::DpadUp, pad::DPAD_UP),
+ (Button::DpadDown, pad::DPAD_DOWN),
+ (Button::DpadLeft, pad::DPAD_LEFT),
+ (Button::DpadRight, pad::DPAD_RIGHT),
+ ],
+ stick_invert: Invert::default(),
+ substick_invert: Invert::default(),
+ deadzone: 0.12,
+ }
+ }
+}
+
+pub struct WiiProfile {
+ pub buttons: Vec<(Button, u16)>,
+ pub nunchuk_c: Button,
+ pub nunchuk_z: Button,
+ pub shake: Option<Button>,
+ pub recenter: Button,
+ pub pointer: PointerSource,
+ pub sensitivity: f32,
+ pub sideways: bool,
+ pub stick_dpad: bool,
+ pub nunchuk_invert: Invert,
+ pub stick_dpad_invert: Invert,
+ pub pointer_invert: Invert,
+ pub deadzone: f32,
+}
+
+impl Default for WiiProfile {
+ fn default() -> Self {
+ Self {
+ buttons: vec![
+ (Button::South, usb::BTN_A),
+ (Button::R2, usb::BTN_B),
+ (Button::West, usb::BTN_ONE),
+ (Button::North, usb::BTN_TWO),
+ (Button::Start, usb::BTN_PLUS),
+ (Button::Select, usb::BTN_MINUS),
+ (Button::Guide, usb::BTN_HOME),
+ (Button::DpadUp, usb::BTN_UP),
+ (Button::DpadDown, usb::BTN_DOWN),
+ (Button::DpadLeft, usb::BTN_LEFT),
+ (Button::DpadRight, usb::BTN_RIGHT),
+ ],
+ nunchuk_c: Button::L1,
+ nunchuk_z: Button::L2,
+ shake: Some(Button::R1),
+ recenter: Button::R3,
+ pointer: PointerSource::Auto,
+ sensitivity: 1.0,
+ sideways: false,
+ stick_dpad: true,
+ nunchuk_invert: Invert::default(),
+ stick_dpad_invert: Invert::default(),
+ pointer_invert: Invert::default(),
+ deadzone: 0.12,
+ }
+ }
+}
+
+pub fn radial(v: (f32, f32), deadzone: f32) -> (f32, f32) {
+ let mag = (v.0 * v.0 + v.1 * v.1).sqrt();
+
+ if mag <= deadzone {
+ return (0.0, 0.0);
+ }
+
+ let scale = ((mag - deadzone) / (1.0 - deadzone)).min(1.0) / mag;
+
+ (v.0 * scale, v.1 * scale)
+}
+
+pub fn stick_byte(v: f32) -> u8 {
+ (v * 127.0 + 128.0).clamp(0.0, 255.0) as u8
+}
+
+pub fn trigger_byte(v: f32) -> u8 {
+ (v * 255.0).clamp(0.0, 255.0) as u8
+}
diff --git a/crates/hostinput/src/mapping/gc.rs b/crates/hostinput/src/mapping/gc.rs
new file mode 100644
index 0000000..9d9d707
--- /dev/null
+++ b/crates/hostinput/src/mapping/gc.rs
@@ -0,0 +1,35 @@
+use crate::device::DeviceState;
+use crate::mapping::{self, GcProfile};
+use gecko::flipper::si::pad::{self, PadStatus};
+
+pub const TRIGGER_THRESHOLD: f32 = 0.85;
+
+pub fn map(state: &DeviceState, profile: &GcProfile) -> PadStatus {
+ let mut buttons = 0u16;
+ for (button, mask) in &profile.buttons {
+ if state.pressed(*button) {
+ buttons |= mask;
+ }
+ }
+
+ if state.l2 >= TRIGGER_THRESHOLD {
+ buttons |= pad::L;
+ }
+ if state.r2 >= TRIGGER_THRESHOLD {
+ buttons |= pad::R;
+ }
+
+ let (lx, ly) = mapping::radial(profile.stick_invert.apply(state.left), profile.deadzone);
+ let (rx, ry) = mapping::radial(profile.substick_invert.apply(state.right), profile.deadzone);
+
+ PadStatus {
+ buttons,
+ stick_x: mapping::stick_byte(lx),
+ stick_y: mapping::stick_byte(ly),
+ substick_x: mapping::stick_byte(rx),
+ substick_y: mapping::stick_byte(ry),
+ trigger_left: mapping::trigger_byte(state.l2),
+ trigger_right: mapping::trigger_byte(state.r2),
+ connected: true,
+ }
+}
diff --git a/crates/hostinput/src/mapping/wii.rs b/crates/hostinput/src/mapping/wii.rs
new file mode 100644
index 0000000..ece86cb
--- /dev/null
+++ b/crates/hostinput/src/mapping/wii.rs
@@ -0,0 +1,96 @@
+use crate::device::PortInput;
+use crate::mapping::{self, PointerSource, WiiProfile};
+use crate::motion;
+use gecko::HostInput;
+use gecko::hollywood::ipc::usb;
+
+const STICK_DPAD_THRESHOLD: f32 = 0.5;
+
+pub fn map(port: &PortInput, profile: &WiiProfile, source: PointerSource) -> HostInput {
+ let state = &port.state;
+
+ let mut buttons = 0u16;
+ for (button, mask) in &profile.buttons {
+ if state.pressed(*button) {
+ buttons |= mask;
+ }
+ }
+
+ if profile.stick_dpad && source != PointerSource::RightStick {
+ let (rx, ry) = profile.stick_dpad_invert.apply(state.right);
+
+ if ry >= STICK_DPAD_THRESHOLD {
+ buttons |= usb::BTN_UP;
+ }
+ if ry <= -STICK_DPAD_THRESHOLD {
+ buttons |= usb::BTN_DOWN;
+ }
+ if rx <= -STICK_DPAD_THRESHOLD {
+ buttons |= usb::BTN_LEFT;
+ }
+ if rx >= STICK_DPAD_THRESHOLD {
+ buttons |= usb::BTN_RIGHT;
+ }
+ }
+
+ if profile.sideways {
+ buttons = self::rotate_dpad(buttons);
+ }
+
+ let mut nunchuk_buttons = 0u8;
+ if state.pressed(profile.nunchuk_c) {
+ nunchuk_buttons |= usb::NUNCHUK_BTN_C;
+ }
+ if state.pressed(profile.nunchuk_z) {
+ nunchuk_buttons |= usb::NUNCHUK_BTN_Z;
+ }
+
+ let (nx, ny) = mapping::radial(profile.nunchuk_invert.apply(state.left), profile.deadzone);
+
+ let ir_pointer = match source {
+ PointerSource::Gyro => port.pointer,
+ PointerSource::RightStick => motion::stick_pointer(mapping::radial(
+ profile.pointer_invert.apply(state.right),
+ profile.deadzone,
+ )),
+ PointerSource::Touchpad => port.touch.map(|(x, y)| gecko::input::aim_to_ir(x, y)),
+ _ => None,
+ };
+
+ let mut accel = port.caps.accel.then(|| motion::map_accel(state.accel));
+
+ if profile.sideways {
+ accel = accel.map(|a| [-a[2], a[1], a[0]]);
+ }
+
+ HostInput::Wii {
+ wiimote_buttons: buttons,
+ wiimote_shake: profile.shake.is_some_and(|button| state.pressed(button)) && accel.is_none(),
+ nunchuk_buttons,
+ nunchuk_stick_x: mapping::stick_byte(nx),
+ nunchuk_stick_y: mapping::stick_byte(ny),
+ ir_pointer,
+ accel,
+ }
+}
+
+fn rotate_dpad(buttons: u16) -> u16 {
+ const DPAD: u16 = usb::BTN_UP | usb::BTN_DOWN | usb::BTN_LEFT | usb::BTN_RIGHT;
+
+ let mut out = buttons & !DPAD;
+
+ if buttons & usb::BTN_UP != 0 {
+ out |= usb::BTN_RIGHT;
+ }
+ if buttons & usb::BTN_DOWN != 0 {
+ out |= usb::BTN_LEFT;
+ }
+ if buttons & usb::BTN_LEFT != 0 {
+ out |= usb::BTN_UP;
+ }
+ if buttons & usb::BTN_RIGHT != 0 {
+ out |= usb::BTN_DOWN;
+ }
+
+ out
+}
diff --git a/crates/hostinput/src/merge.rs b/crates/hostinput/src/merge.rs
new file mode 100644
index 0000000..5d464b4
--- /dev/null
+++ b/crates/hostinput/src/merge.rs
@@ -0,0 +1,57 @@
+use gecko::HostInput;
+use gecko::flipper::si::pad::{PadStatus, STICK_CENTER};
+
+pub fn gc(pad: PadStatus, kb: PadStatus) -> PadStatus {
+ PadStatus {
+ buttons: pad.buttons | kb.buttons,
+ stick_x: self::stick(pad.stick_x, kb.stick_x),
+ stick_y: self::stick(pad.stick_y, kb.stick_y),
+ substick_x: self::stick(pad.substick_x, kb.substick_x),
+ substick_y: self::stick(pad.substick_y, kb.substick_y),
+ trigger_left: pad.trigger_left.max(kb.trigger_left),
+ trigger_right: pad.trigger_right.max(kb.trigger_right),
+ connected: true,
+ }
+}
+
+fn stick(pad: u8, kb: u8) -> u8 {
+ if pad != STICK_CENTER { pad } else { kb }
+}
+
+pub fn wii(pad: HostInput, kb: HostInput) -> HostInput {
+ let HostInput::Wii {
+ wiimote_buttons,
+ wiimote_shake,
+ nunchuk_buttons,
+ nunchuk_stick_x,
+ nunchuk_stick_y,
+ ir_pointer,
+ accel,
+ } = pad
+ else {
+ return kb;
+ };
+
+ let HostInput::Wii {
+ wiimote_buttons: kb_buttons,
+ wiimote_shake: kb_shake,
+ nunchuk_buttons: kb_nunchuk,
+ nunchuk_stick_x: kb_stick_x,
+ nunchuk_stick_y: kb_stick_y,
+ ir_pointer: kb_pointer,
+ accel: kb_accel,
+ } = kb
+ else {
+ return kb;
+ };
+
+ HostInput::Wii {
+ wiimote_buttons: wiimote_buttons | kb_buttons,
+ wiimote_shake: wiimote_shake || kb_shake,
+ nunchuk_buttons: nunchuk_buttons | kb_nunchuk,
+ nunchuk_stick_x: self::stick(nunchuk_stick_x, kb_stick_x),
+ nunchuk_stick_y: self::stick(nunchuk_stick_y, kb_stick_y),
+ ir_pointer: ir_pointer.or(kb_pointer),
+ accel: accel.or(kb_accel),
+ }
+}
diff --git a/crates/hostinput/src/motion.rs b/crates/hostinput/src/motion.rs
new file mode 100644
index 0000000..ea8ec0a
--- /dev/null
+++ b/crates/hostinput/src/motion.rs
@@ -0,0 +1,49 @@
+use gecko::input::aim_to_ir;
+
+const FOV_X: f32 = 0.60;
+const FOV_Y: f32 = 0.45;
+const OVERSHOOT: f32 = 1.2;
+
+#[derive(Default)]
+pub struct GyroPointer {
+ yaw: f32,
+ pitch: f32,
+}
+
+impl GyroPointer {
+ pub fn integrate(&mut self, gyro: [f32; 3], dt: f32, sensitivity: f32, invert: (bool, bool)) {
+ let limit_x = FOV_X * OVERSHOOT / 2.0;
+ let limit_y = FOV_Y * OVERSHOOT / 2.0;
+
+ let dx = gyro[1] * dt * sensitivity * if invert.0 { -1.0 } else { 1.0 };
+ let dy = gyro[0] * dt * sensitivity * if invert.1 { -1.0 } else { 1.0 };
+
+ self.yaw = (self.yaw - dx).clamp(-limit_x, limit_x);
+ self.pitch = (self.pitch - dy).clamp(-limit_y, limit_y);
+ }
+
+ pub fn recenter(&mut self) {
+ self.yaw = 0.0;
+ self.pitch = 0.0;
+ }
+
+ pub fn ir(&self) -> Option<(u16, u16)> {
+ if self.yaw.abs() > FOV_X / 2.0 || self.pitch.abs() > FOV_Y / 2.0 {
+ return None;
+ }
+
+ Some(aim_to_ir(self.yaw / FOV_X + 0.5, self.pitch / FOV_Y + 0.5))
+ }
+}
+
+pub fn map_accel(host: [f32; 3]) -> [f32; 3] {
+ [-host[0], -host[2], host[1]]
+}
+
+pub fn stick_pointer(v: (f32, f32)) -> Option<(u16, u16)> {
+ if v == (0.0, 0.0) {
+ return None;
+ }
+
+ Some(aim_to_ir((v.0 + 1.0) / 2.0, (1.0 - v.1) / 2.0))
+}
diff --git a/crates/hostinput/src/probe.rs b/crates/hostinput/src/probe.rs
new file mode 100644
index 0000000..022a93a
--- /dev/null
+++ b/crates/hostinput/src/probe.rs
@@ -0,0 +1,35 @@
+use std::time::Duration;
+
+fn main() {
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "hostinput=debug".into()),
+ )
+ .init();
+
+ let service = hostinput::sdl::service();
+
+ loop {
+ std::thread::sleep(Duration::from_millis(500));
+
+ let Some(p) = *service.shared.lock().unwrap() else {
+ continue;
+ };
+
+ println!(
+ "{:?} buttons={:019b} left=({:+.2},{:+.2}) right=({:+.2},{:+.2}) l2={:.2} r2={:.2} accel=({:+.2},{:+.2},{:+.2}) pointer={:?}",
+ p.caps,
+ p.state.buttons,
+ p.state.left.0,
+ p.state.left.1,
+ p.state.right.0,
+ p.state.right.1,
+ p.state.l2,
+ p.state.r2,
+ p.state.accel[0],
+ p.state.accel[1],
+ p.state.accel[2],
+ p.pointer,
+ );
+ }
+}
diff --git a/crates/hostinput/src/sdl.rs b/crates/hostinput/src/sdl.rs
new file mode 100644
index 0000000..c71445c
--- /dev/null
+++ b/crates/hostinput/src/sdl.rs
@@ -0,0 +1,365 @@
+use crate::device::{Button, Capabilities, DeviceState, PortInput};
+use crate::motion::GyroPointer;
+use sdl3::GamepadSubsystem;
+use sdl3::event::Event;
+use sdl3::gamepad::{Axis, Button as SdlButton, Gamepad};
+use sdl3::joystick::JoystickId;
+use sdl3::sensor::SensorType;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+const STANDARD_GRAVITY: f32 = 9.80665;
+
+#[derive(Clone, Copy)]
+pub struct MotionSettings {
+ pub sensitivity: f32,
+ pub recenter: Button,
+ pub invert: (bool, bool),
+}
+
+impl Default for MotionSettings {
+ fn default() -> Self {
+ Self {
+ sensitivity: 1.0,
+ recenter: Button::R3,
+ invert: (false, false),
+ }
+ }
+}
+
+pub struct Service {
+ pub shared: Arc<Mutex<Option<PortInput>>>,
+ pub rumble: Arc<AtomicBool>,
+ pub motion: Arc<Mutex<MotionSettings>>,
+ pub device: Arc<Mutex<Option<String>>>,
+}
+
+static SERVICE: OnceLock<Service> = OnceLock::new();
+
+pub fn service() -> &'static Service {
+ SERVICE.get_or_init(|| {
+ let shared = Arc::new(Mutex::new(None));
+ let rumble = Arc::new(AtomicBool::new(false));
+ let motion = Arc::new(Mutex::new(MotionSettings::default()));
+ let device = Arc::new(Mutex::new(None));
+
+ let thread_shared = shared.clone();
+ let thread_rumble = rumble.clone();
+ let thread_motion = motion.clone();
+ let thread_device = device.clone();
+ std::thread::Builder::new()
+ .name("hostinput-sdl".into())
+ .spawn(move || self::run(thread_shared, thread_rumble, thread_motion, thread_device))
+ .expect("failed to spawn SDL input thread");
+
+ Service {
+ shared,
+ rumble,
+ motion,
+ device,
+ }
+ })
+}
+
+struct Slot {
+ pad: Gamepad,
+ id: u32,
+ caps: Capabilities,
+ pointer: GyroPointer,
+ accel: [f32; 3],
+ touch: Option<(f32, f32)>,
+ last_gyro_ts: Option<u64>,
+ rumble_on: bool,
+ rumble_refresh: Instant,
+}
+
+fn run(
+ shared: Arc<Mutex<Option<PortInput>>>,
+ rumble: Arc<AtomicBool>,
+ motion: Arc<Mutex<MotionSettings>>,
+ device: Arc<Mutex<Option<String>>>,
+) {
+ let sdl = match sdl3::init() {
+ Ok(sdl) => sdl,
+ Err(err) => {
+ tracing::error!(%err, "SDL init failed, gamepads unavailable");
+ return;
+ }
+ };
+
+ let subsystem = match sdl.gamepad() {
+ Ok(subsystem) => subsystem,
+ Err(err) => {
+ tracing::error!(%err, "SDL gamepad subsystem unavailable");
+ return;
+ }
+ };
+
+ let mut pump = match sdl.event_pump() {
+ Ok(pump) => pump,
+ Err(err) => {
+ tracing::error!(%err, "SDL event pump unavailable");
+ return;
+ }
+ };
+
+ let mut slot: Option<Slot> = None;
+
+ if let Ok(ids) = subsystem.gamepads() {
+ for id in ids {
+ self::add_device(&subsystem, &mut slot, &device, id);
+ }
+ }
+
+ loop {
+ let settings = *motion.lock().unwrap();
+
+ let first = pump.wait_event_timeout(Duration::from_millis(4));
+
+ for event in first.into_iter().chain(std::iter::from_fn(|| pump.poll_event())) {
+ self::handle_event(&subsystem, &mut slot, &settings, &device, event);
+ }
+
+ let snapshot = slot.as_mut().map(|slot| {
+ let mut state = self::read_state(&slot.pad);
+ state.accel = slot.accel;
+
+ if state.pressed(settings.recenter) {
+ slot.pointer.recenter();
+ }
+
+ PortInput {
+ state,
+ caps: slot.caps,
+ pointer: slot.caps.gyro.then(|| slot.pointer.ir()).flatten(),
+ touch: slot.touch,
+ }
+ });
+
+ *shared.lock().unwrap() = snapshot;
+
+ if let Some(slot) = slot.as_mut()
+ && slot.caps.rumble
+ {
+ let desired = rumble.load(Ordering::Relaxed);
+ let refresh = desired && slot.rumble_refresh.elapsed() >= Duration::from_millis(200);
+
+ if desired != slot.rumble_on || refresh {
+ let (low, high) = if desired { (0xC000, 0xC000) } else { (0, 0) };
+ if let Err(err) = slot.pad.set_rumble(low, high, 500) {
+ tracing::debug!(id = slot.id, %err, "rumble update failed");
+ }
+
+ slot.rumble_on = desired;
+ slot.rumble_refresh = Instant::now();
+ }
+ }
+ }
+}
+
+fn handle_event(
+ subsystem: &GamepadSubsystem,
+ slot: &mut Option<Slot>,
+ settings: &MotionSettings,
+ device: &Mutex<Option<String>>,
+ event: Event,
+) {
+ match event {
+ Event::ControllerDeviceAdded { which, .. } => {
+ self::add_device(subsystem, slot, device, sdl3::sys::joystick::SDL_JoystickID(which))
+ }
+ Event::ControllerDeviceRemoved { which, .. } => self::remove_device(subsystem, slot, device, which),
+ Event::ControllerSensorUpdated {
+ timestamp,
+ which,
+ sensor,
+ data,
+ } => self::sensor_update(slot, settings, which, sensor, data, timestamp),
+ Event::ControllerTouchpadDown {
+ which, finger, x, y, ..
+ }
+ | Event::ControllerTouchpadMotion {
+ which, finger, x, y, ..
+ } => self::touch_update(slot, which, finger, Some((x, y))),
+ Event::ControllerTouchpadUp { which, finger, .. } => self::touch_update(slot, which, finger, None),
+ _ => {}
+ }
+}
+
+fn touch_update(slot: &mut Option<Slot>, id: u32, finger: i32, touch: Option<(f32, f32)>) {
+ if finger != 0 {
+ return;
+ }
+
+ if let Some(slot) = slot.as_mut().filter(|slot| slot.id == id) {
+ slot.touch = touch;
+ }
+}
+
+fn sensor_update(
+ slot: &mut Option<Slot>,
+ settings: &MotionSettings,
+ id: u32,
+ sensor: SensorType,
+ data: [f32; 3],
+ timestamp: u64,
+) {
+ let Some(slot) = slot.as_mut().filter(|slot| slot.id == id) else {
+ return;
+ };
+
+ match sensor {
+ SensorType::Gyroscope => {
+ let dt = match slot.last_gyro_ts {
+ Some(prev) if timestamp > prev => ((timestamp - prev) as f32 / 1_000_000_000.0).min(0.05),
+ _ => 0.0,
+ };
+ slot.last_gyro_ts = Some(timestamp);
+
+ slot.pointer.integrate(data, dt, settings.sensitivity, settings.invert);
+ }
+ SensorType::Accelerometer => {
+ slot.accel = [
+ data[0] / STANDARD_GRAVITY,
+ data[1] / STANDARD_GRAVITY,
+ data[2] / STANDARD_GRAVITY,
+ ];
+ }
+ _ => {}
+ }
+}
+
+fn add_device(subsystem: &GamepadSubsystem, slot: &mut Option<Slot>, device: &Mutex<Option<String>>, id: JoystickId) {
+ if slot.as_ref().is_some_and(|slot| slot.id == u32::from(id)) {
+ return;
+ }
+
+ let pad = match subsystem.open(id) {
+ Ok(pad) => pad,
+ Err(err) => {
+ tracing::warn!(id = u32::from(id), %err, "failed to open gamepad");
+ return;
+ }
+ };
+
+ let id = u32::from(id);
+ let caps = self::query_caps(&pad);
+
+ let replace = match slot.as_ref() {
+ None => true,
+ Some(current) => caps.gyro && !current.caps.gyro,
+ };
+
+ if !replace {
+ tracing::info!(id, name = ?pad.name(), "gamepad ignored, slot occupied");
+ return;
+ }
+
+ tracing::info!(id, name = ?pad.name(), ?caps, "gamepad connected");
+
+ *device.lock().unwrap() = pad.name();
+
+ if caps.gyro
+ && let Err(err) = pad.sensor_set_enabled(SensorType::Gyroscope, true)
+ {
+ tracing::warn!(id, %err, "failed to enable gyroscope");
+ }
+ if caps.accel
+ && let Err(err) = pad.sensor_set_enabled(SensorType::Accelerometer, true)
+ {
+ tracing::warn!(id, %err, "failed to enable accelerometer");
+ }
+
+ *slot = Some(Slot {
+ pad,
+ id,
+ caps,
+ pointer: GyroPointer::default(),
+ accel: [0.0; 3],
+ touch: None,
+ last_gyro_ts: None,
+ rumble_on: false,
+ rumble_refresh: Instant::now(),
+ });
+}
+
+fn remove_device(subsystem: &GamepadSubsystem, slot: &mut Option<Slot>, device: &Mutex<Option<String>>, id: u32) {
+ if !slot.as_ref().is_some_and(|slot| slot.id == id) {
+ return;
+ }
+
+ tracing::info!(id, "gamepad disconnected");
+ *slot = None;
+ *device.lock().unwrap() = None;
+
+ if let Ok(ids) = subsystem.gamepads() {
+ for id in ids {
+ self::add_device(subsystem, slot, device, id);
+ }
+ }
+}
+
+fn query_caps(pad: &Gamepad) -> Capabilities {
+ Capabilities {
+ analog_sticks: pad.has_axis(Axis::LeftX),
+ gyro: unsafe { pad.has_sensor(SensorType::Gyroscope) },
+ accel: unsafe { pad.has_sensor(SensorType::Accelerometer) },
+ rumble: unsafe { pad.has_rumble() },
+ }
+}
+
+const BUTTON_MAP: [(SdlButton, Button); 16] = [
+ (SdlButton::South, Button::South),
+ (SdlButton::East, Button::East),
+ (SdlButton::West, Button::West),
+ (SdlButton::North, Button::North),
+ (SdlButton::LeftShoulder, Button::L1),
+ (SdlButton::RightShoulder, Button::R1),
+ (SdlButton::LeftStick, Button::L3),
+ (SdlButton::RightStick, Button::R3),
+ (SdlButton::Start, Button::Start),
+ (SdlButton::Back, Button::Select),
+ (SdlButton::Guide, Button::Guide),
+ (SdlButton::DPadUp, Button::DpadUp),
+ (SdlButton::DPadDown, Button::DpadDown),
+ (SdlButton::DPadLeft, Button::DpadLeft),
+ (SdlButton::DPadRight, Button::DpadRight),
+ (SdlButton::Touchpad, Button::TouchpadClick),
+];
+
+fn read_state(pad: &Gamepad) -> DeviceState {
+ let mut buttons = 0u32;
+ for (sdl, button) in BUTTON_MAP {
+ if pad.button(sdl) {
+ buttons |= button.mask();
+ }
+ }
+
+ let l2 = self::trigger(pad, Axis::TriggerLeft);
+ let r2 = self::trigger(pad, Axis::TriggerRight);
+
+ if l2 >= 0.5 {
+ buttons |= Button::L2.mask();
+ }
+ if r2 >= 0.5 {
+ buttons |= Button::R2.mask();
+ }
+
+ DeviceState {
+ buttons,
+ left: (self::axis(pad, Axis::LeftX), -self::axis(pad, Axis::LeftY)),
+ right: (self::axis(pad, Axis::RightX), -self::axis(pad, Axis::RightY)),
+ l2,
+ r2,
+ accel: [0.0; 3],
+ }
+}
+
+fn axis(pad: &Gamepad, axis: Axis) -> f32 {
+ (pad.axis(axis) as f32 / 32767.0).clamp(-1.0, 1.0)
+}
+
+fn trigger(pad: &Gamepad, axis: Axis) -> f32 {
+ (pad.axis(axis) as f32 / 32767.0).clamp(0.0, 1.0)
+}
diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs
index 032ae94..2c7008c 100644
--- a/crates/mcp/src/server.rs
+++ b/crates/mcp/src/server.rs
@@ -595,6 +595,7 @@ impl McpServer {
.nunchuk_stick_y
.unwrap_or(gecko::hollywood::ipc::usb::NUNCHUK_STICK_CENTER),
ir_pointer: args.ir_x.zip(args.ir_y),
+ accel: None,
};
let mut s = self.shared.state.lock().unwrap();
s.backend.as_mut().unwrap().apply_host_input(&input);
diff --git a/crates/tinyapp/Cargo.toml b/crates/tinyapp/Cargo.toml
index f896449..d1f88a0 100644
--- a/crates/tinyapp/Cargo.toml
+++ b/crates/tinyapp/Cargo.toml
@@ -20,6 +20,7 @@ hotpath-tui = ["hotpath", "hotpath/tui"]
[dependencies]
gecko = { path = "../gecko" }
+hostinput = { path = "../hostinput" }
scripting = { path = "../scripting", optional = true }
image = { path = "../image" }
backend-wgpu = { path = "../backend-wgpu" }
diff --git a/crates/tinyapp/src/app.rs b/crates/tinyapp/src/app.rs
index 4cd4c7b..794a461 100644
--- a/crates/tinyapp/src/app.rs
+++ b/crates/tinyapp/src/app.rs
@@ -464,7 +464,7 @@ impl ApplicationHandler<crate::UserEvent> for App {
nunchuk_buttons,
nunchuk_stick_x,
nunchuk_stick_y,
- ir_pointer: _,
+ ..
} => {
crate::update_wiimote_keys(wiimote_buttons, key, pressed);
crate::update_wiimote_motion_keys(wiimote_shake, key, pressed);
@@ -511,18 +511,9 @@ impl ApplicationHandler<crate::UserEvent> for App {
return;
}
- const POINTER_SCALE_X: f64 = 0.44;
- const POINTER_SCALE_Y: f64 = 0.66;
- const POINTER_Y_OFFSET: f64 = 120.0;
-
- let aim_x = (position.x / size.width as f64).clamp(0.0, 1.0);
- let aim_y = (position.y / size.height as f64).clamp(0.0, 1.0);
- let span_x = usb::IR_CAMERA_WIDTH as f64 * POINTER_SCALE_X;
- let span_y = usb::IR_CAMERA_HEIGHT as f64 * POINTER_SCALE_Y;
- let base_x = (usb::IR_CAMERA_WIDTH as f64 - span_x) / 2.0;
- let base_y = (usb::IR_CAMERA_HEIGHT as f64 - span_y) / 2.0 + POINTER_Y_OFFSET;
- let ir_x = (base_x + (1.0 - aim_x) * span_x) as u16;
- let ir_y = (base_y + aim_y * span_y) as u16;
+ let aim_x = (position.x / size.width as f64) as f32;
+ let aim_y = (position.y / size.height as f64) as f32;
+ let (ir_x, ir_y) = gecko::input::aim_to_ir(aim_x, aim_y);
let mut input = self.input.lock().unwrap();
if let HostInput::Wii { ir_pointer, .. } = &mut *input
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index ee11c9e..d0ad101 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -167,6 +167,10 @@ struct Args {
#[arg(long)]
wait: bool,
+ /// Wiimote pointer source: auto, gyro, stick, touchpad, or mouse
+ #[arg(long, default_value = "mouse")]
+ pointer: String,
+
/// Force interpreter dispatch for CPU/DSP/Vertex (default: JIT)
#[arg(long)]
interpreter: bool,
@@ -404,6 +408,10 @@ fn run<const SYSTEM: SystemId>(
let emu_start_gate = start_gate.clone();
let emu_shutdown = shutdown_requested.clone();
let fifo_record = args.fifo_record.clone();
+
+ let mut input_config = hostinput::InputConfig::default();
+ input_config.wii.pointer = Some(args.pointer.clone());
+
drop(proxy);
let emu_handle = std::thread::Builder::new()
.name("emu".into())
@@ -411,6 +419,7 @@ fn run<const SYSTEM: SystemId>(
thread::emu_thread::<SYSTEM>(
emulator,
emu_input,
+ input_config,
game_id,
throttle,
emu_start_gate,
diff --git a/crates/tinyapp/src/thread.rs b/crates/tinyapp/src/thread.rs
index d1af7b8..0fdbaf6 100644
--- a/crates/tinyapp/src/thread.rs
+++ b/crates/tinyapp/src/thread.rs
@@ -9,6 +9,7 @@ use std::time::Duration;
pub fn emu_thread<const SYSTEM: SystemId>(
mut emulator: System<SYSTEM>,
input: Arc<Mutex<HostInput>>,
+ input_config: hostinput::InputConfig,
game_id: Option<String>,
throttle: bool,
start_gate: Arc<AtomicBool>,
@@ -30,7 +31,11 @@ pub fn emu_thread<const SYSTEM: SystemId>(
emulator.gx.recorder = Some(Box::new(FifoRecorder::new()));
}
- emulator.set_input_sink(Box::new(input.clone()));
+ emulator.set_input_sink(Box::new(hostinput::InputManager::new(
+ SYSTEM,
+ &input_config,
+ input.clone(),
+ )));
while !shutdown.load(Ordering::Relaxed) {
while throttle && emulator.audio_sink.should_throttle() {
@@ -40,8 +45,6 @@ pub fn emu_thread<const SYSTEM: SystemId>(
sleeper.sleep(throttle_step);
}
- let input = *input.lock().unwrap();
- emulator.apply_host_input(&input);
emulator.run_until_vsync();
}
diff --git a/crates/web/Cargo.toml b/crates/web/Cargo.toml
index 4d7d692..ee61bb4 100644
--- a/crates/web/Cargo.toml
+++ b/crates/web/Cargo.toml
@@ -36,4 +36,4 @@ web-sys = { version = "0.3.94", features = [
"console",
] }
console_error_panic_hook = "0.1.7"
-getrandom = { version = "0.3", features = ["wasm_js"] }
+getrandom = { version = "0.3.4", features = ["wasm_js"] }
diff --git a/docker/Dockerfile.native b/docker/Dockerfile.native
index 96509e9..8522614 100644
--- a/docker/Dockerfile.native
+++ b/docker/Dockerfile.native
@@ -1,21 +1,24 @@
-# Cross-compiles tinyapp, debugger and multitool for x86_64 Linux and Windows.
-# Produces a debug build and a release build separately. For the release build
-# only, all chipi bindings are switched from fn_ptr_lut to jump_table.
+# Cross-compiles tinyapp, debugger, multitool, gecko-app, fifoplayer and
+# input-probe for x86_64 Linux and Windows. Produces a debug build and a
+# release build separately. For the release build only, all chipi bindings are
+# switched from fn_ptr_lut to jump_table.
#
# Build:
# docker build -f Dockerfile.native --output type=local,dest=docker-build .
#
# Output:
-# docker-build/debug/ {tinyapp, debugger, multitool}
-# docker-build/release/ {tinyapp, debugger, multitool}
+# docker-build/debug/ {tinyapp, debugger, multitool, gecko, fifoplayer, input-probe}
+# docker-build/release/ {tinyapp, debugger, multitool, gecko, fifoplayer, input-probe}
FROM rust:latest AS base
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
mingw-w64 \
+ cmake ninja-build \
libwayland-dev libxkbcommon-dev libx11-dev libxi-dev libxrandr-dev libxcursor-dev \
- libasound2-dev \
+ libxss-dev libxtst-dev libxext-dev libxfixes-dev \
+ libasound2-dev libudev-dev \
&& rm -rf /var/lib/apt/lists/*
RUN update-alternatives --set x86_64-w64-mingw32-gcc /usr/bin/x86_64-w64-mingw32-gcc-posix \
@@ -26,6 +29,8 @@ ENV CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc \
CXX_x86_64_pc_windows_gnu=x86_64-w64-mingw32-g++ \
AR_x86_64_pc_windows_gnu=x86_64-w64-mingw32-ar
+RUN rustup target add x86_64-pc-windows-gnu
+
WORKDIR /app
COPY . .
@@ -33,18 +38,24 @@ COPY . .
FROM base AS debug-build
RUN cargo build --profile dev \
--target x86_64-unknown-linux-gnu \
- --package tinyapp --package debugger --package multitool \
+ --package tinyapp --package debugger --package multitool --package gecko-app --package fifoplayer --package hostinput \
&& cargo build --profile dev \
--target x86_64-pc-windows-gnu \
- --package tinyapp --package debugger --package multitool
+ --package tinyapp --package debugger --package multitool --package gecko-app --package fifoplayer --package hostinput
RUN mkdir -p /out/debug \
&& cp target/x86_64-unknown-linux-gnu/debug/tinyapp /out/debug/ \
&& cp target/x86_64-unknown-linux-gnu/debug/debugger /out/debug/ \
&& cp target/x86_64-unknown-linux-gnu/debug/multitool /out/debug/ \
+ && cp target/x86_64-unknown-linux-gnu/debug/gecko /out/debug/ \
+ && cp target/x86_64-unknown-linux-gnu/debug/fifoplayer /out/debug/ \
+ && cp target/x86_64-unknown-linux-gnu/debug/input-probe /out/debug/ \
&& cp target/x86_64-pc-windows-gnu/debug/tinyapp.exe /out/debug/ \
&& cp target/x86_64-pc-windows-gnu/debug/debugger.exe /out/debug/ \
- && cp target/x86_64-pc-windows-gnu/debug/multitool.exe /out/debug/
+ && cp target/x86_64-pc-windows-gnu/debug/multitool.exe /out/debug/ \
+ && cp target/x86_64-pc-windows-gnu/debug/gecko.exe /out/debug/ \
+ && cp target/x86_64-pc-windows-gnu/debug/fifoplayer.exe /out/debug/ \
+ && cp target/x86_64-pc-windows-gnu/debug/input-probe.exe /out/debug/
FROM base AS release-build
@@ -52,18 +63,24 @@ FROM base AS release-build
RUN cargo build --release \
--target x86_64-unknown-linux-gnu \
- --package tinyapp --package debugger --package multitool \
+ --package tinyapp --package debugger --package multitool --package gecko-app --package fifoplayer --package hostinput \
&& cargo build --release \
--target x86_64-pc-windows-gnu \
- --package tinyapp --package debugger --package multitool
+ --package tinyapp --package debugger --package multitool --package gecko-app --package fifoplayer --package hostinput
RUN mkdir -p /out/release \
&& cp target/x86_64-unknown-linux-gnu/release/tinyapp /out/release/ \
&& cp target/x86_64-unknown-linux-gnu/release/debugger /out/release/ \
&& cp target/x86_64-unknown-linux-gnu/release/multitool /out/release/ \
+ && cp target/x86_64-unknown-linux-gnu/release/gecko /out/release/ \
+ && cp target/x86_64-unknown-linux-gnu/release/fifoplayer /out/release/ \
+ && cp target/x86_64-unknown-linux-gnu/release/input-probe /out/release/ \
&& cp target/x86_64-pc-windows-gnu/release/tinyapp.exe /out/release/ \
&& cp target/x86_64-pc-windows-gnu/release/debugger.exe /out/release/ \
- && cp target/x86_64-pc-windows-gnu/release/multitool.exe /out/release/
+ && cp target/x86_64-pc-windows-gnu/release/multitool.exe /out/release/ \
+ && cp target/x86_64-pc-windows-gnu/release/gecko.exe /out/release/ \
+ && cp target/x86_64-pc-windows-gnu/release/fifoplayer.exe /out/release/ \
+ && cp target/x86_64-pc-windows-gnu/release/input-probe.exe /out/release/
FROM scratch AS artifacts
diff --git a/other/example.conf b/other/example.conf
new file mode 100644
index 0000000..e9da808
--- /dev/null
+++ b/other/example.conf
@@ -0,0 +1,53 @@
+gcn_library = "/path/to/gamecube/games"
+wii_library = "/path/to/wii/games"
+system_dir = "/path/to/system"
+dsp_rom = "/path/to/dsp_rom.bin"
+dsp_coef = "/path/to/dsp_coef.bin"
+ipl = "/path/to/IPL.bin"
+
+cpu_mode = "jit" # jit | interpreter
+theme = "system" # system | light | dark
+skip_ipl = true
+
+[input]
+gamepads = true
+
+# Button names: south, east, west, north, l1, r1, l2, r2, l3, r3,
+# start, select, guide, dpad_up, dpad_down, dpad_left, dpad_right, touchpad
+
+[input.gc]
+a = "south"
+b = "west"
+x = "east"
+y = "north"
+start = "start"
+z = "r1"
+invert_stick_x = false
+invert_stick_y = false
+invert_cstick_x = false
+invert_cstick_y = false
+deadzone = 0.12
+
+[input.wii]
+a = "south"
+b = "r2"
+one = "west"
+two = "north"
+plus = "start"
+minus = "select"
+home = "guide"
+nunchuk_c = "l1"
+nunchuk_z = "l2"
+shake = "r1" # or "none"
+recenter = "r3"
+pointer = "auto" # auto | gyro | stick | touchpad | mouse
+pointer_sensitivity = 1.0
+sideways = false
+stick_dpad = true
+invert_nunchuk_x = false
+invert_nunchuk_y = false
+invert_stick_dpad_x = false
+invert_stick_dpad_y = false
+invert_pointer_x = false
+invert_pointer_y = false
+deadzone = 0.12