diff --git a/client/configuration.cpp b/client/configuration.cpp index 8cc717ca..bb68531c 100644 --- a/client/configuration.cpp +++ b/client/configuration.cpp @@ -180,6 +180,15 @@ configuration::configuration(xr::system & system, xr::session & session) if (auto val = root["mic_unprocessed_audio"]; val.is_bool()) mic_unprocessed_audio = val.get_bool(); + if (auto val = root["forward_keyboard"]; val.is_bool()) + forward_keyboard = val.get_bool(); + + if (auto val = root["forward_mouse"]; val.is_bool()) + forward_mouse = val.get_bool(); + + if (auto val = root["forward_gamepad"]; val.is_bool()) + forward_gamepad = val.get_bool(); + if (auto val = root["fb_lower_body"]; val.is_bool()) fb_lower_body = val.get_bool(); if (auto val = root["fb_hip"]; val.is_bool()) @@ -296,6 +305,9 @@ void configuration::save() write_openxr_post_processing(json, openxr_post_processing); json << ",\"passthrough_enabled\":" << std::boolalpha << passthrough_enabled; json << ",\"mic_unprocessed_audio\":" << std::boolalpha << mic_unprocessed_audio; + json << ",\"forward_keyboard\":" << std::boolalpha << forward_keyboard; + json << ",\"forward_mouse\":" << std::boolalpha << forward_mouse; + json << ",\"forward_gamepad\":" << std::boolalpha << forward_gamepad; json << ",\"fb_lower_body\":" << std::boolalpha << fb_lower_body; json << ",\"fb_hip\":" << std::boolalpha << fb_hip; json << ",\"enable_stream_gui\":" << std::boolalpha << enable_stream_gui; diff --git a/client/configuration.h b/client/configuration.h index 825fce5a..7ce170ef 100644 --- a/client/configuration.h +++ b/client/configuration.h @@ -68,6 +68,11 @@ public: bool passthrough_enabled = false; bool mic_unprocessed_audio = false; + // Input forwarding, per device. Off by default; only effective if the server permits it. + bool forward_keyboard = false; + bool forward_mouse = false; + bool forward_gamepad = false; + bool fb_lower_body = false; bool fb_hip = true; diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index 38dbe10b..72625731 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -867,6 +867,8 @@ void scenes::lobby::render(const XrFrameState & frame_state) if (next_scene) { + server_hid_forwarding = next_scene->hid_forwarding_enabled(); + switch (next_scene->current_state()) { case scenes::stream::state::streaming: diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index 3b8aa535..bfdd3ca9 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -63,6 +63,10 @@ class lobby : public scene_impl std::string server_name; bool autoconnect_enabled = true; + // Last known uinput forwarding state of the connected server, kept after disconnection so the + // settings can warn that forwarded keyboard and mouse will not reach the server. + std::optional server_hid_forwarding; + std::optional input; entt::entity lobby_entity; diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index 4118fcb0..bd843b6b 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -784,6 +784,32 @@ void scenes::lobby::gui_settings() ImGui::Unindent(); ImGui::EndDisabled(); } + { + // Virtual devices: a keyboard, mouse or gamepad connected to the headset is + // replicated on the server through uinput. The gamepad is also exposed through + // OpenXR, whether or not it is mirrored to a virtual device. + ImGui::Text("%s", _S("Virtual devices")); + if (ImGui::IsItemHovered()) + imgui_ctx->tooltip(_("Input devices connected to the headset are replicated as virtual devices on the PC.\nThe server must allow forwarded input devices; this is not available when the server runs as Flatpak.\nA gamepad is also usable without a virtual device by applications that read it through OpenXR.")); + ImGui::Indent(); + if (ImGui::Checkbox(_S("Keyboard"), &config.forward_keyboard)) + config.save(); + imgui_ctx->vibrate_on_hover(); + if (ImGui::Checkbox(_S("Mouse"), &config.forward_mouse)) + config.save(); + imgui_ctx->vibrate_on_hover(); + if (ImGui::Checkbox(_S("Gamepad"), &config.forward_gamepad)) + config.save(); + imgui_ctx->vibrate_on_hover(); + ImGui::Unindent(); + + if (server_hid_forwarding == false and (config.forward_keyboard or config.forward_mouse or config.forward_gamepad)) + { + ImGui::TextColored(constants::style::warn, ICON_FA_TRIANGLE_EXCLAMATION); + ImGui::SameLine(); + ImGui::Text("%s", _S("The server does not allow forwarded input devices")); + } + } if (system.hand_tracking_supported()) { bool enabled = config.check_feature(feature::hand_tracking); diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 21e248ec..f775bbc3 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -265,6 +265,7 @@ std::shared_ptr scenes::stream::create(std::unique_ptrsend_control(from_headset::hid::input{packet}); return true; @@ -1372,25 +1374,25 @@ bool scenes::stream::forward_hid_input(from_headset::hid::input_t packet) bool scenes::stream::on_input_key_down(uint8_t key_code) { - return forward_hid_input(from_headset::hid::key_down{key_code}); + return forward_hid_input(from_headset::hid::key_down{key_code}, application::get_config().forward_keyboard); } bool scenes::stream::on_input_key_up(uint8_t key_code) { - return forward_hid_input(from_headset::hid::key_up{key_code}); + return forward_hid_input(from_headset::hid::key_up{key_code}, application::get_config().forward_keyboard); } bool scenes::stream::on_input_mouse_move(float x, float y) { - return forward_hid_input(from_headset::hid::mouse_move{x, y}); + return forward_hid_input(from_headset::hid::mouse_move{x, y}, application::get_config().forward_mouse); } bool scenes::stream::on_input_button_down(uint8_t button) { - return forward_hid_input(from_headset::hid::button_down{button}); + return forward_hid_input(from_headset::hid::button_down{button}, application::get_config().forward_mouse); } bool scenes::stream::on_input_button_up(uint8_t button) { - return forward_hid_input(from_headset::hid::button_up{button}); + return forward_hid_input(from_headset::hid::button_up{button}, application::get_config().forward_mouse); } bool scenes::stream::on_input_scroll(float h, float v) { - return forward_hid_input(from_headset::hid::mouse_scroll{h, v}); + return forward_hid_input(from_headset::hid::mouse_scroll{h, v}, application::get_config().forward_mouse); } diff --git a/client/scenes/stream.h b/client/scenes/stream.h index b3e11217..c7bc4c2e 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -32,6 +32,7 @@ #include "wivrn_packets.h" #include "xr/space.h" #include +#include #include #include #include @@ -188,7 +189,7 @@ private: stream(std::string server_name, scene & parent_scene); - bool forward_hid_input(from_headset::hid::input_t); + bool forward_hid_input(from_headset::hid::input_t, bool device_enabled); public: ~stream(); @@ -239,6 +240,13 @@ public: return state_; } + // Whether the server mirrors forwarded input devices to uinput. The gamepad is also exposed + // through OpenXR regardless, so this only affects forwarded keyboard and mouse. + bool hid_forwarding_enabled() const + { + return hid_forwarding; + } + void exit(); void start_application(std::string appid); diff --git a/client/scenes/stream_gui.cpp b/client/scenes/stream_gui.cpp index 6a2af4ed..29e50574 100644 --- a/client/scenes/stream_gui.cpp +++ b/client/scenes/stream_gui.cpp @@ -387,6 +387,7 @@ static void send_settings_changed_packet(xr::session & session, wivrn_session * .minimum_refresh_rate = config.minimum_refresh_rate.value_or(0), .fps_divider = config.fps_divider, .bitrate_bps = config.bitrate_bps, + .mirror_gamepad = config.forward_gamepad, }); } diff --git a/client/scenes/stream_network.cpp b/client/scenes/stream_network.cpp index edd1c98b..99a85aca 100644 --- a/client/scenes/stream_network.cpp +++ b/client/scenes/stream_network.cpp @@ -19,10 +19,8 @@ #include "stream.h" -#ifdef __ANDROID__ #include "application.h" -#endif - +#include "utils/i18n.h" #include "utils/named_thread.h" #include @@ -87,6 +85,12 @@ void scenes::stream::operator()(to_headset::feature_control && control) { case wivrn::to_headset::feature_control::hid_input: hid_forwarding = control.state; + if (not control.state and (application::get_config().forward_keyboard or application::get_config().forward_mouse or application::get_config().forward_gamepad)) + { + auto toast = gui_toast.lock(); + toast->emplace(_("The server does not allow forwarded input devices"), true); + gui_status_last_change = instance.now(); + } return; case wivrn::to_headset::feature_control::microphone: if (audio_handle) @@ -94,6 +98,7 @@ void scenes::stream::operator()(to_headset::feature_control && control) return; } } + void scenes::stream::operator()(to_headset::audio_stream_description && desc) { audio_handle.emplace(desc, *network_session, instance); diff --git a/common/wivrn_packets.h b/common/wivrn_packets.h index 5b6b0ba4..db5495c1 100644 --- a/common/wivrn_packets.h +++ b/common/wivrn_packets.h @@ -269,6 +269,10 @@ struct settings_changed uint32_t fps_divider = 1; uint32_t bitrate_bps; + + // Whether the server should mirror the gamepad to a virtual uinput device; + // gamepad inputs are always forwarded for the OpenXR path + bool mirror_gamepad = false; }; struct headset_info_packet diff --git a/dashboard/qml/SettingsPage.qml b/dashboard/qml/SettingsPage.qml index f32848f1..cfd1706a 100644 --- a/dashboard/qml/SettingsPage.qml +++ b/dashboard/qml/SettingsPage.qml @@ -111,10 +111,10 @@ Kirigami.ScrollablePage { visible: Settings.hid_forwarding_supported Controls.CheckBox { id: hid_forwarding - text: i18n("Forward keyboard & mouse from headset") + text: i18n("Expose forwarded input devices via uinput") } Kirigami.ContextualHelpButton { - toolTipText: i18n("Keyboard and mouse connected to the client will act as if connected to the server. Client OS may reserve specific keys and combinations, which cannot be forwarded.") + toolTipText: i18n("Replicate mouse, keyboard and gamepad connected to the headset as virtual devices on PC.\nReplicated devices will appear as if they were plugged to the PC, some keys may be reserved by the headset OS and not be available. Gamepad is also available without virtual devices for applications that access it through OpenXR.") } } Controls.CheckBox { diff --git a/docs/configuration.md b/docs/configuration.md index cf713147..fe442ff3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -136,7 +136,14 @@ Default value: `false` Only available when the `uinput` kernel module is loaded and the user has write access. -Enables the forwarding of keyboard and mouse input from the client to the server. +Mirrors input devices forwarded from the headset (keyboard, mouse, gamepad) to `uinput` +devices, for applications that do not read them through OpenXR. Which devices are forwarded is +chosen on the headset. + +A forwarded gamepad is also exposed as a native OpenXR gamepad at `/user/gamepad`, which needs +no permission and is always available. Only the digested controller state is forwarded +(buttons, two sticks, analog triggers and a d-pad), so device specific features such as gyro, +adaptive triggers or the touchpad are not available. ## `debug-gui` Default value: `false` diff --git a/server/driver/configuration.cpp b/server/driver/configuration.cpp index da4a9f9e..8c974780 100644 --- a/server/driver/configuration.cpp +++ b/server/driver/configuration.cpp @@ -189,6 +189,8 @@ configuration::configuration() } } + // Gates the uinput mirror of forwarded input devices. The OpenXR gamepad needs no + // permission, so it is always exposed. if (auto it = json.find("hid-forwarding"); it != json.end()) hid_forwarding = *it; diff --git a/server/driver/wivrn_gamepad_map.h b/server/driver/wivrn_gamepad_map.h index 3e5b8bbb..b8cfd006 100644 --- a/server/driver/wivrn_gamepad_map.h +++ b/server/driver/wivrn_gamepad_map.h @@ -20,6 +20,9 @@ #include "wivrn_packets.h" +#include +#include + namespace wivrn { enum gp_input @@ -58,6 +61,7 @@ struct gamepad_input { gp_input slot; gp_value kind; + uint16_t ev_code; // BTN_* or ABS_*, unused for dpad }; inline gamepad_input map_gamepad(device_id id) @@ -65,47 +69,49 @@ inline gamepad_input map_gamepad(device_id id) switch (id) { case device_id::GAMEPAD_MENU_CLICK: - return {gp_menu, gp_value::button}; + return {gp_menu, gp_value::button, BTN_START}; case device_id::GAMEPAD_VIEW_CLICK: - return {gp_view, gp_value::button}; + return {gp_view, gp_value::button, BTN_SELECT}; case device_id::GAMEPAD_A_CLICK: - return {gp_a, gp_value::button}; + return {gp_a, gp_value::button, BTN_SOUTH}; case device_id::GAMEPAD_B_CLICK: - return {gp_b, gp_value::button}; + return {gp_b, gp_value::button, BTN_EAST}; + // BTN_X/BTN_Y aliases don't match compass positions (BTN_X == BTN_NORTH, + // BTN_Y == BTN_WEST); xpad and SDL expect the aliases, not the positions case device_id::GAMEPAD_X_CLICK: - return {gp_x, gp_value::button}; + return {gp_x, gp_value::button, BTN_X}; case device_id::GAMEPAD_Y_CLICK: - return {gp_y, gp_value::button}; + return {gp_y, gp_value::button, BTN_Y}; case device_id::GAMEPAD_SHOULDER_LEFT_CLICK: - return {gp_shoulder_left, gp_value::button}; + return {gp_shoulder_left, gp_value::button, BTN_TL}; case device_id::GAMEPAD_SHOULDER_RIGHT_CLICK: - return {gp_shoulder_right, gp_value::button}; + return {gp_shoulder_right, gp_value::button, BTN_TR}; case device_id::GAMEPAD_THUMBSTICK_LEFT_CLICK: - return {gp_thumbstick_left_click, gp_value::button}; + return {gp_thumbstick_left_click, gp_value::button, BTN_THUMBL}; case device_id::GAMEPAD_THUMBSTICK_RIGHT_CLICK: - return {gp_thumbstick_right_click, gp_value::button}; + return {gp_thumbstick_right_click, gp_value::button, BTN_THUMBR}; case device_id::GAMEPAD_DPAD_DOWN_CLICK: - return {gp_dpad_down, gp_value::dpad}; + return {gp_dpad_down, gp_value::dpad, 0}; case device_id::GAMEPAD_DPAD_RIGHT_CLICK: - return {gp_dpad_right, gp_value::dpad}; + return {gp_dpad_right, gp_value::dpad, 0}; case device_id::GAMEPAD_DPAD_UP_CLICK: - return {gp_dpad_up, gp_value::dpad}; + return {gp_dpad_up, gp_value::dpad, 0}; case device_id::GAMEPAD_DPAD_LEFT_CLICK: - return {gp_dpad_left, gp_value::dpad}; + return {gp_dpad_left, gp_value::dpad, 0}; case device_id::GAMEPAD_TRIGGER_LEFT_VALUE: - return {gp_trigger_left, gp_value::trigger}; + return {gp_trigger_left, gp_value::trigger, ABS_Z}; case device_id::GAMEPAD_TRIGGER_RIGHT_VALUE: - return {gp_trigger_right, gp_value::trigger}; + return {gp_trigger_right, gp_value::trigger, ABS_RZ}; case device_id::GAMEPAD_THUMBSTICK_LEFT_X: - return {gp_thumbstick_left, gp_value::stick_x}; + return {gp_thumbstick_left, gp_value::stick_x, ABS_X}; case device_id::GAMEPAD_THUMBSTICK_LEFT_Y: - return {gp_thumbstick_left, gp_value::stick_y}; + return {gp_thumbstick_left, gp_value::stick_y, ABS_Y}; case device_id::GAMEPAD_THUMBSTICK_RIGHT_X: - return {gp_thumbstick_right, gp_value::stick_x}; + return {gp_thumbstick_right, gp_value::stick_x, ABS_RX}; case device_id::GAMEPAD_THUMBSTICK_RIGHT_Y: - return {gp_thumbstick_right, gp_value::stick_y}; + return {gp_thumbstick_right, gp_value::stick_y, ABS_RY}; default: - return {gp_count, gp_value::button}; + return {gp_count, gp_value::button, 0}; } } diff --git a/server/driver/wivrn_session.cpp b/server/driver/wivrn_session.cpp index d8b39f1b..969855ee 100644 --- a/server/driver/wivrn_session.cpp +++ b/server/driver/wivrn_session.cpp @@ -248,10 +248,10 @@ wivrn::wivrn_session::wivrn_session(std::unique_ptr connection } catch (...) { - U_LOG_W("Could not initialize keyboard & mouse forwarding"); + U_LOG_W("Could not initialize input forwarding"); U_LOG_W("Ensure that the uinput kernel module is loaded and your user is in the input group."); wivrn_ipc_socket_monado->send(from_monado::server_error{ - .where = "Could not initialize keyboard & mouse forwarding", + .where = "Could not initialize input forwarding", .message = "Ensure that the uinput kernel module is loaded and your user is in the input group.", }); } @@ -403,8 +403,9 @@ void wivrn_session::resume_session() if (audio_handle) audio_handle->resume(); - if (uinput_handler) - send_control(to_headset::feature_control{to_headset::feature_control::hid_input, true}); + // Tell the headset whether forwarded input devices are mirrored to uinput. The headset picks + // what to forward. The OpenXR gamepad at /user/gamepad is always available regardless. + send_control(to_headset::feature_control{to_headset::feature_control::hid_input, bool(uinput_handler)}); { float target_fps = default_fps(); @@ -480,8 +481,7 @@ void wivrn_session::operator()(from_headset::headset_info_packet &&) void wivrn_session::operator()(const from_headset::settings_changed & settings) { - auto locked = this->settings.lock(); - *locked = settings; + *this->settings.lock() = settings; if (settings.bitrate_bps != 0) compositor.set_bitrate(settings.bitrate_bps); @@ -489,6 +489,9 @@ void wivrn_session::operator()(const from_headset::settings_changed & settings) if (settings.preferred_refresh_rate != 0) compositor.set_framerate(settings.preferred_refresh_rate / settings.fps_divider); + if (not settings.mirror_gamepad and uinput_handler) + uinput_handler->destroy_gamepad(); + wivrn_ipc_socket_monado->send(std::move(settings)); } @@ -549,7 +552,12 @@ static xrt_device_name get_name(interaction_profile profile) void wivrn_session::operator()(const from_headset::tracking & tracking) { if (gamepad_device) - gamepad_device->set_connected(tracking.interaction_profiles[2] != interaction_profile::none); + { + gamepad_connected = tracking.interaction_profiles[2] != interaction_profile::none; + gamepad_device->set_connected(gamepad_connected); + if (not gamepad_connected and uinput_handler) + uinput_handler->destroy_gamepad(); + } auto left = (roles.left == -1 || roles.left == left_controller_index || roles.left == left_hand_interaction_index) ? get_name(tracking.interaction_profiles[0]) : XRT_DEVICE_INVALID; auto right = (roles.right == -1 || roles.right == right_controller_index || roles.right == right_hand_interaction_index) ? get_name(tracking.interaction_profiles[1]) : XRT_DEVICE_INVALID; @@ -683,7 +691,25 @@ void wivrn_session::operator()(from_headset::inputs && inputs) right_controller.set_inputs(inputs, offset); if (gamepad_device) + { gamepad_device->set_inputs(inputs); + try + { + // Mirror to a uinput gamepad for non-OpenXR consumers, when the + // headset opts in and the server permits. + if (uinput_handler and gamepad_connected and settings.lock()->mirror_gamepad) + uinput_handler->handle_gamepad(inputs); + } + catch (const std::exception & e) + { + wivrn_ipc_socket_monado->send(from_monado::server_error{ + .where = "Gamepad forwarding error", + .message = e.what(), + }); + U_LOG_E("Gamepad forwarding error: %s", e.what()); + uinput_handler.reset(); + } + } } void wivrn_session::operator()(from_headset::hid::input && e) @@ -1005,6 +1031,12 @@ void wivrn_session::run_net(std::stop_token stop) try { connection->poll(*this, 20); + + if (uinput_handler) + { + for (auto & haptics: uinput_handler->read_rumble()) + send_stream(std::move(haptics)); + } } catch (const std::exception & e) { diff --git a/server/driver/wivrn_session.h b/server/driver/wivrn_session.h index 29bfab18..d06edb84 100644 --- a/server/driver/wivrn_session.h +++ b/server/driver/wivrn_session.h @@ -102,6 +102,7 @@ class wivrn_session : public xrt_system_devices std::optional htc_face_tracker; beman::inplace_vector::inplace_vector generic_trackers; std::optional uinput_handler; + bool gamepad_connected = false; // network thread only clock_offset_estimator offset_est; std::atomic tracking_latency; // production to reception time diff --git a/server/driver/wivrn_uinput.cpp b/server/driver/wivrn_uinput.cpp index eca268dd..91cc7a74 100644 --- a/server/driver/wivrn_uinput.cpp +++ b/server/driver/wivrn_uinput.cpp @@ -1,8 +1,11 @@ #include "wivrn_uinput.h" #include "utils/overloaded.h" +#include "wivrn_gamepad_map.h" +#include #include #include +#include #include #include @@ -17,12 +20,12 @@ namespace { -wivrn::fd_base open_uinput_or_throw() +wivrn::fd_base open_uinput_or_throw(int flags = O_WRONLY) { constexpr std::array paths = {"/dev/uinput", "/dev/input/uinput"}; for (const char * p: paths) { - int fd = ::open(p, O_WRONLY | O_NONBLOCK); + int fd = ::open(p, flags | O_NONBLOCK); if (fd >= 0) return fd; if (errno != ENOENT) // exists but inaccessbile @@ -40,15 +43,20 @@ void write_or_throw(int fd, const void * buf, size_t n) throw std::runtime_error("byte count mismatch while writing to uinput"); } -void fill_ids(uinput_user_dev & uidev, uint16_t product) noexcept +void fill_ids(uinput_user_dev & uidev, uint16_t vendor, uint16_t product) noexcept { std::memset(&uidev, 0, sizeof(uidev)); uidev.id.bustype = 0x03; - uidev.id.vendor = 0x4711; + uidev.id.vendor = vendor; uidev.id.product = product; uidev.id.version = 5; } +void fill_ids(uinput_user_dev & uidev, uint16_t product) noexcept +{ + fill_ids(uidev, 0x4711, product); +} + void emit_ev(int fd, uint16_t type, uint16_t code, int32_t value) { struct input_event ev; @@ -80,14 +88,14 @@ void ioctl_or_throw(int fd, unsigned long op, unsigned long int arg) } // namespace -wivrn_uinput::wivrn_uinput() -{ - init_keyboard(); - init_mouse(); -}; - void wivrn_uinput::handle_input(wivrn::from_headset::hid::input & e) { + if (kbd_fd.get_fd() < 0) + { + init_keyboard(); + init_mouse(); + } + std::visit(utils::overloaded{ [this](const wivrn::from_headset::hid::key_down & e) { send_key(e.key, true); @@ -111,6 +119,152 @@ void wivrn_uinput::handle_input(wivrn::from_headset::hid::input & e) e.input_data); } +namespace +{ +int16_t scale_stick(float v) +{ + v = std::clamp(v, -1.f, 1.f); + return (int16_t)std::lround(v * 32767.f); +} + +int16_t scale_trigger(float v) +{ + v = std::clamp(v, 0.f, 1.f); + return (int16_t)std::lround(v * 255.f); +} +} // namespace + +void wivrn_uinput::handle_gamepad(const wivrn::from_headset::inputs & inputs) +{ + using namespace wivrn; + if (gamepad_fd.get_fd() < 0) + { + // Inputs packets are mostly controller inputs: don't create the device + // until the headset actually sends gamepad inputs + if (std::ranges::none_of(inputs.values, [](const auto & value) { return map_gamepad(value.id).slot != gp_count; })) + return; + init_gamepad(); + } + int fd = gamepad_fd.get_fd(); + + bool dpad_left = false, dpad_right = false, dpad_up = false, dpad_down = false; + + for (const auto & value: inputs.values) + { + auto m = map_gamepad(value.id); + if (m.slot == gp_count) + continue; + switch (m.kind) + { + case gp_value::button: + emit_ev(fd, EV_KEY, m.ev_code, value.value != 0); + break; + case gp_value::trigger: + emit_ev(fd, EV_ABS, m.ev_code, scale_trigger(value.value)); + break; + case gp_value::stick_x: + case gp_value::stick_y: + emit_ev(fd, EV_ABS, m.ev_code, scale_stick(value.value)); + break; + case gp_value::dpad: + switch (m.slot) + { + case gp_dpad_left: + dpad_left = value.value != 0; + break; + case gp_dpad_right: + dpad_right = value.value != 0; + break; + case gp_dpad_up: + dpad_up = value.value != 0; + break; + case gp_dpad_down: + dpad_down = value.value != 0; + break; + default: + break; + } + break; + } + } + + emit_ev(fd, EV_ABS, ABS_HAT0X, (dpad_right ? 1 : 0) - (dpad_left ? 1 : 0)); + emit_ev(fd, EV_ABS, ABS_HAT0Y, (dpad_down ? 1 : 0) - (dpad_up ? 1 : 0)); + syn(fd); +} + +void wivrn_uinput::destroy_gamepad() +{ + if (gamepad_fd.get_fd() < 0) + return; + ioctl(gamepad_fd.get_fd(), UI_DEV_DESTROY); + gamepad_fd = {}; + ff_effects.clear(); +} + +std::vector wivrn_uinput::read_rumble() +{ + int fd = gamepad_fd.get_fd(); + if (fd < 0) + return {}; + + std::vector result; + auto motors = [&](float strong, float weak, uint16_t length_ms) { + // 0 length is a continuous effect; send a finite burst instead + const std::chrono::nanoseconds duration{int64_t(length_ms ? length_ms : 100) * 1'000'000}; + // strong/weak are motor weights, not locations, so drive both outputs at the combined intensity + const float amplitude = std::max(strong, weak); + result = { + {wivrn::device_id::GAMEPAD_HAPTIC_LEFT, duration, 0.f, amplitude}, + {wivrn::device_id::GAMEPAD_HAPTIC_RIGHT, duration, 0.f, amplitude}, + }; + }; + + input_event ev; + while (::read(fd, &ev, sizeof(ev)) == (ssize_t)sizeof(ev)) + { + if (ev.type == EV_UINPUT and ev.code == UI_FF_UPLOAD) + { + uinput_ff_upload upload{ + .request_id = (uint32_t)ev.value, + }; + if (ioctl(fd, UI_BEGIN_FF_UPLOAD, &upload) == 0) + { + ff_effects[upload.effect.id] = upload.effect; + upload.retval = 0; + ioctl(fd, UI_END_FF_UPLOAD, &upload); + } + } + else if (ev.type == EV_UINPUT and ev.code == UI_FF_ERASE) + { + uinput_ff_erase erase{ + .request_id = (uint32_t)ev.value, + }; + if (ioctl(fd, UI_BEGIN_FF_ERASE, &erase) == 0) + { + ff_effects.erase(erase.effect_id); + erase.retval = 0; + ioctl(fd, UI_END_FF_ERASE, &erase); + } + } + else if (ev.type == EV_FF) + { + // ev.code is the effect id, ev.value != 0 starts it, 0 stops it. + if (ev.value == 0) + { + motors(0.f, 0.f, 0); + } + else if (auto it = ff_effects.find(ev.code); it != ff_effects.end() and it->second.type == FF_RUMBLE) + { + const auto & rumble = it->second.u.rumble; + motors(rumble.strong_magnitude / 65535.f, rumble.weak_magnitude / 65535.f, (uint16_t)it->second.replay.length); + } + } + } + + return result; +} + void wivrn_uinput::send_key(uint16_t key, bool down) { emit_ev(kbd_fd, EV_KEY, key, down ? 1 : 0); @@ -187,3 +341,44 @@ void wivrn_uinput::init_mouse() write_or_throw(fd, &uidev, sizeof(uidev)); ioctl_or_throw(fd, UI_DEV_CREATE); } + +void wivrn_uinput::init_gamepad() +{ + // O_RDWR to read force-feedback (rumble) back from the device + gamepad_fd = open_uinput_or_throw(O_RDWR); + int fd = gamepad_fd.get_fd(); + + ioctl_or_throw(fd, UI_SET_EVBIT, EV_KEY); + ioctl_or_throw(fd, UI_SET_EVBIT, EV_ABS); + ioctl_or_throw(fd, UI_SET_EVBIT, EV_FF); + ioctl_or_throw(fd, UI_SET_FFBIT, FF_RUMBLE); + + // BTN_GAMEPAD (== BTN_SOUTH) is required or SDL ignores the device + for (int code: {BTN_SOUTH, BTN_EAST, BTN_NORTH, BTN_WEST, BTN_TL, BTN_TR, BTN_SELECT, BTN_START, BTN_MODE, BTN_THUMBL, BTN_THUMBR}) + ioctl_or_throw(fd, UI_SET_KEYBIT, code); + + for (int code: {ABS_X, ABS_Y, ABS_RX, ABS_RY, ABS_Z, ABS_RZ, ABS_HAT0X, ABS_HAT0Y}) + ioctl_or_throw(fd, UI_SET_ABSBIT, code); + + uinput_user_dev uidev; + // Microsoft X-Box vendor/product so Steam Input also recognizes it by GUID + fill_ids(uidev, 0x045e, 0x028e); + uidev.ff_effects_max = ff_effects_max; + std::snprintf(uidev.name, sizeof(uidev.name), "WiVRn Gamepad"); + + const auto set_abs = [&](int code, int32_t min, int32_t max, int32_t fuzz, int32_t flat) { + uidev.absmin[code] = min; + uidev.absmax[code] = max; + uidev.absfuzz[code] = fuzz; + uidev.absflat[code] = flat; + }; + for (int code: {ABS_X, ABS_Y, ABS_RX, ABS_RY}) + set_abs(code, -32768, 32767, 16, 128); + set_abs(ABS_Z, 0, 255, 0, 0); + set_abs(ABS_RZ, 0, 255, 0, 0); + set_abs(ABS_HAT0X, -1, 1, 0, 0); + set_abs(ABS_HAT0Y, -1, 1, 0, 0); + + write_or_throw(fd, &uidev, sizeof(uidev)); + ioctl_or_throw(fd, UI_DEV_CREATE); +} diff --git a/server/driver/wivrn_uinput.h b/server/driver/wivrn_uinput.h index ba20e685..1a0686ba 100644 --- a/server/driver/wivrn_uinput.h +++ b/server/driver/wivrn_uinput.h @@ -2,23 +2,42 @@ #include "wivrn_sockets.h" #include +#include +#include + +#include class wivrn_uinput { public: - wivrn_uinput(); + // Devices are created lazily on first use, so only forwarded classes are exposed. + wivrn_uinput() = default; void handle_input(wivrn::from_headset::hid::input &); + // The gamepad device is created on the first packet with gamepad inputs + void handle_gamepad(const wivrn::from_headset::inputs &); + // Remove the virtual gamepad, when the headset stops mirroring or the gamepad disconnects + void destroy_gamepad(); + + // Drains pending force-feedback requests from the virtual gamepad and returns the + // resulting haptics packets to forward to the headset, if any changed. + std::vector read_rumble(); + private: void init_keyboard(); void init_mouse(); + void init_gamepad(); void send_key(uint16_t key, bool down); void send_button(uint16_t mouse_button, bool down); void mouse_move_relative(int16_t x, int16_t y); void mouse_scroll(int16_t vertical, int16_t horizontal); + static constexpr int ff_effects_max = 16; + wivrn::fd_base kbd_fd; wivrn::fd_base mouse_fd; + wivrn::fd_base gamepad_fd; + std::map ff_effects; };