summaryrefslogtreecommitdiff
path: root/src/core
diff options
context:
space:
mode:
authorGravatar Fernando S2021-11-27 11:52:08 +0100
committerGravatar GitHub2021-11-27 11:52:08 +0100
commit564f10527745f870621c08bbb5d16badee0ed861 (patch)
treee8ac8dee60086facf1837393882865f5df18c95e /src/core
parentMerge pull request #7431 from liushuyu/fix-linux-decoding (diff)
parentconfig: Remove vibration configuration (diff)
downloadyuzu-564f10527745f870621c08bbb5d16badee0ed861.tar.gz
yuzu-564f10527745f870621c08bbb5d16badee0ed861.tar.xz
yuzu-564f10527745f870621c08bbb5d16badee0ed861.zip
Merge pull request #7255 from german77/kraken
Project Kraken: Input rewrite
Diffstat (limited to 'src/core')
-rw-r--r--src/core/CMakeLists.txt19
-rw-r--r--src/core/core.cpp14
-rw-r--r--src/core/core.h10
-rw-r--r--src/core/frontend/applets/controller.cpp45
-rw-r--r--src/core/frontend/applets/controller.h8
-rw-r--r--src/core/frontend/emu_window.cpp98
-rw-r--r--src/core/frontend/emu_window.h30
-rw-r--r--src/core/frontend/input.h217
-rw-r--r--src/core/hid/emulated_console.cpp229
-rw-r--r--src/core/hid/emulated_console.h188
-rw-r--r--src/core/hid/emulated_controller.cpp1061
-rw-r--r--src/core/hid/emulated_controller.h392
-rw-r--r--src/core/hid/emulated_devices.cpp451
-rw-r--r--src/core/hid/emulated_devices.h209
-rw-r--r--src/core/hid/hid_core.cpp168
-rw-r--r--src/core/hid/hid_core.h73
-rw-r--r--src/core/hid/hid_types.h631
-rw-r--r--src/core/hid/input_converter.cpp383
-rw-r--r--src/core/hid/input_converter.h95
-rw-r--r--src/core/hid/input_interpreter.cpp (renamed from src/core/frontend/input_interpreter.cpp)25
-rw-r--r--src/core/hid/input_interpreter.h (renamed from src/core/frontend/input_interpreter.h)54
-rw-r--r--src/core/hid/motion_input.cpp280
-rw-r--r--src/core/hid/motion_input.h87
-rw-r--r--src/core/hle/service/am/applets/applet_controller.cpp19
-rw-r--r--src/core/hle/service/am/applets/applet_controller.h6
-rw-r--r--src/core/hle/service/am/applets/applets.cpp2
-rw-r--r--src/core/hle/service/hid/controllers/console_sixaxis.cpp65
-rw-r--r--src/core/hle/service/hid/controllers/console_sixaxis.h44
-rw-r--r--src/core/hle/service/hid/controllers/controller_base.cpp4
-rw-r--r--src/core/hle/service/hid/controllers/controller_base.h21
-rw-r--r--src/core/hle/service/hid/controllers/debug_pad.cpp72
-rw-r--r--src/core/hle/service/hid/controllers/debug_pad.h82
-rw-r--r--src/core/hle/service/hid/controllers/gesture.cpp257
-rw-r--r--src/core/hle/service/hid/controllers/gesture.h109
-rw-r--r--src/core/hle/service/hid/controllers/keyboard.cpp59
-rw-r--r--src/core/hle/service/hid/controllers/keyboard.h59
-rw-r--r--src/core/hle/service/hid/controllers/mouse.cpp64
-rw-r--r--src/core/hle/service/hid/controllers/mouse.h63
-rw-r--r--src/core/hle/service/hid/controllers/npad.cpp1617
-rw-r--r--src/core/hle/service/hid/controllers/npad.h649
-rw-r--r--src/core/hle/service/hid/controllers/stubbed.cpp6
-rw-r--r--src/core/hle/service/hid/controllers/stubbed.h13
-rw-r--r--src/core/hle/service/hid/controllers/touchscreen.cpp139
-rw-r--r--src/core/hle/service/hid/controllers/touchscreen.h86
-rw-r--r--src/core/hle/service/hid/controllers/xpad.cpp32
-rw-r--r--src/core/hle/service/hid/controllers/xpad.h61
-rw-r--r--src/core/hle/service/hid/hid.cpp394
-rw-r--r--src/core/hle/service/hid/hid.h33
-rw-r--r--src/core/hle/service/hid/ring_lifo.h54
49 files changed, 6166 insertions, 2611 deletions
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index 9f0fbba2d..582c15f7e 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -132,11 +132,23 @@ add_library(core STATIC
132 frontend/emu_window.h 132 frontend/emu_window.h
133 frontend/framebuffer_layout.cpp 133 frontend/framebuffer_layout.cpp
134 frontend/framebuffer_layout.h 134 frontend/framebuffer_layout.h
135 frontend/input_interpreter.cpp
136 frontend/input_interpreter.h
137 frontend/input.h
138 hardware_interrupt_manager.cpp 135 hardware_interrupt_manager.cpp
139 hardware_interrupt_manager.h 136 hardware_interrupt_manager.h
137 hid/emulated_console.cpp
138 hid/emulated_console.h
139 hid/emulated_controller.cpp
140 hid/emulated_controller.h
141 hid/emulated_devices.cpp
142 hid/emulated_devices.h
143 hid/hid_core.cpp
144 hid/hid_core.h
145 hid/hid_types.h
146 hid/input_converter.cpp
147 hid/input_converter.h
148 hid/input_interpreter.cpp
149 hid/input_interpreter.h
150 hid/motion_input.cpp
151 hid/motion_input.h
140 hle/api_version.h 152 hle/api_version.h
141 hle/ipc.h 153 hle/ipc.h
142 hle/ipc_helpers.h 154 hle/ipc_helpers.h
@@ -402,6 +414,7 @@ add_library(core STATIC
402 hle/service/hid/hid.h 414 hle/service/hid/hid.h
403 hle/service/hid/irs.cpp 415 hle/service/hid/irs.cpp
404 hle/service/hid/irs.h 416 hle/service/hid/irs.h
417 hle/service/hid/ring_lifo.h
405 hle/service/hid/xcd.cpp 418 hle/service/hid/xcd.cpp
406 hle/service/hid/xcd.h 419 hle/service/hid/xcd.h
407 hle/service/hid/errors.h 420 hle/service/hid/errors.h
diff --git a/src/core/core.cpp b/src/core/core.cpp
index 07448fd29..473ab9f81 100644
--- a/src/core/core.cpp
+++ b/src/core/core.cpp
@@ -27,6 +27,7 @@
27#include "core/file_sys/vfs_concat.h" 27#include "core/file_sys/vfs_concat.h"
28#include "core/file_sys/vfs_real.h" 28#include "core/file_sys/vfs_real.h"
29#include "core/hardware_interrupt_manager.h" 29#include "core/hardware_interrupt_manager.h"
30#include "core/hid/hid_core.h"
30#include "core/hle/kernel/k_process.h" 31#include "core/hle/kernel/k_process.h"
31#include "core/hle/kernel/k_scheduler.h" 32#include "core/hle/kernel/k_scheduler.h"
32#include "core/hle/kernel/kernel.h" 33#include "core/hle/kernel/kernel.h"
@@ -126,7 +127,7 @@ FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
126 127
127struct System::Impl { 128struct System::Impl {
128 explicit Impl(System& system) 129 explicit Impl(System& system)
129 : kernel{system}, fs_controller{system}, memory{system}, 130 : kernel{system}, fs_controller{system}, memory{system}, hid_core{},
130 cpu_manager{system}, reporter{system}, applet_manager{system}, time_manager{system} {} 131 cpu_manager{system}, reporter{system}, applet_manager{system}, time_manager{system} {}
131 132
132 SystemResultStatus Run() { 133 SystemResultStatus Run() {
@@ -391,6 +392,7 @@ struct System::Impl {
391 std::unique_ptr<Hardware::InterruptManager> interrupt_manager; 392 std::unique_ptr<Hardware::InterruptManager> interrupt_manager;
392 std::unique_ptr<Core::DeviceMemory> device_memory; 393 std::unique_ptr<Core::DeviceMemory> device_memory;
393 Core::Memory::Memory memory; 394 Core::Memory::Memory memory;
395 Core::HID::HIDCore hid_core;
394 CpuManager cpu_manager; 396 CpuManager cpu_manager;
395 std::atomic_bool is_powered_on{}; 397 std::atomic_bool is_powered_on{};
396 bool exit_lock = false; 398 bool exit_lock = false;
@@ -615,6 +617,14 @@ const Kernel::KernelCore& System::Kernel() const {
615 return impl->kernel; 617 return impl->kernel;
616} 618}
617 619
620HID::HIDCore& System::HIDCore() {
621 return impl->hid_core;
622}
623
624const HID::HIDCore& System::HIDCore() const {
625 return impl->hid_core;
626}
627
618Timing::CoreTiming& System::CoreTiming() { 628Timing::CoreTiming& System::CoreTiming() {
619 return impl->core_timing; 629 return impl->core_timing;
620} 630}
@@ -825,8 +835,6 @@ void System::ApplySettings() {
825 if (IsPoweredOn()) { 835 if (IsPoweredOn()) {
826 Renderer().RefreshBaseSettings(); 836 Renderer().RefreshBaseSettings();
827 } 837 }
828
829 Service::HID::ReloadInputDevices();
830} 838}
831 839
832} // namespace Core 840} // namespace Core
diff --git a/src/core/core.h b/src/core/core.h
index 01bc0a2c7..645e5c241 100644
--- a/src/core/core.h
+++ b/src/core/core.h
@@ -89,6 +89,10 @@ namespace Core::Hardware {
89class InterruptManager; 89class InterruptManager;
90} 90}
91 91
92namespace Core::HID {
93class HIDCore;
94}
95
92namespace Core { 96namespace Core {
93 97
94class ARM_Interface; 98class ARM_Interface;
@@ -285,6 +289,12 @@ public:
285 /// Provides a constant reference to the kernel instance. 289 /// Provides a constant reference to the kernel instance.
286 [[nodiscard]] const Kernel::KernelCore& Kernel() const; 290 [[nodiscard]] const Kernel::KernelCore& Kernel() const;
287 291
292 /// Gets a mutable reference to the HID interface.
293 [[nodiscard]] HID::HIDCore& HIDCore();
294
295 /// Gets an immutable reference to the HID interface.
296 [[nodiscard]] const HID::HIDCore& HIDCore() const;
297
288 /// Provides a reference to the internal PerfStats instance. 298 /// Provides a reference to the internal PerfStats instance.
289 [[nodiscard]] Core::PerfStats& GetPerfStats(); 299 [[nodiscard]] Core::PerfStats& GetPerfStats();
290 300
diff --git a/src/core/frontend/applets/controller.cpp b/src/core/frontend/applets/controller.cpp
index 03bbedf8b..6dbd38ffa 100644
--- a/src/core/frontend/applets/controller.cpp
+++ b/src/core/frontend/applets/controller.cpp
@@ -5,16 +5,15 @@
5#include "common/assert.h" 5#include "common/assert.h"
6#include "common/logging/log.h" 6#include "common/logging/log.h"
7#include "core/frontend/applets/controller.h" 7#include "core/frontend/applets/controller.h"
8#include "core/hle/service/hid/controllers/npad.h" 8#include "core/hid/emulated_controller.h"
9#include "core/hle/service/hid/hid.h" 9#include "core/hid/hid_core.h"
10#include "core/hle/service/sm/sm.h" 10#include "core/hid/hid_types.h"
11 11
12namespace Core::Frontend { 12namespace Core::Frontend {
13 13
14ControllerApplet::~ControllerApplet() = default; 14ControllerApplet::~ControllerApplet() = default;
15 15
16DefaultControllerApplet::DefaultControllerApplet(Service::SM::ServiceManager& service_manager_) 16DefaultControllerApplet::DefaultControllerApplet(HID::HIDCore& hid_core_) : hid_core{hid_core_} {}
17 : service_manager{service_manager_} {}
18 17
19DefaultControllerApplet::~DefaultControllerApplet() = default; 18DefaultControllerApplet::~DefaultControllerApplet() = default;
20 19
@@ -22,24 +21,20 @@ void DefaultControllerApplet::ReconfigureControllers(std::function<void()> callb
22 const ControllerParameters& parameters) const { 21 const ControllerParameters& parameters) const {
23 LOG_INFO(Service_HID, "called, deducing the best configuration based on the given parameters!"); 22 LOG_INFO(Service_HID, "called, deducing the best configuration based on the given parameters!");
24 23
25 auto& npad =
26 service_manager.GetService<Service::HID::Hid>("hid")
27 ->GetAppletResource()
28 ->GetController<Service::HID::Controller_NPad>(Service::HID::HidController::NPad);
29
30 auto& players = Settings::values.players.GetValue();
31
32 const std::size_t min_supported_players = 24 const std::size_t min_supported_players =
33 parameters.enable_single_mode ? 1 : parameters.min_players; 25 parameters.enable_single_mode ? 1 : parameters.min_players;
34 26
35 // Disconnect Handheld first. 27 // Disconnect Handheld first.
36 npad.DisconnectNpadAtIndex(8); 28 auto* handheld = hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld);
29 handheld->Disconnect();
37 30
38 // Deduce the best configuration based on the input parameters. 31 // Deduce the best configuration based on the input parameters.
39 for (std::size_t index = 0; index < players.size() - 2; ++index) { 32 for (std::size_t index = 0; index < hid_core.available_controllers - 2; ++index) {
33 auto* controller = hid_core.GetEmulatedControllerByIndex(index);
34
40 // First, disconnect all controllers regardless of the value of keep_controllers_connected. 35 // First, disconnect all controllers regardless of the value of keep_controllers_connected.
41 // This makes it easy to connect the desired controllers. 36 // This makes it easy to connect the desired controllers.
42 npad.DisconnectNpadAtIndex(index); 37 controller->Disconnect();
43 38
44 // Only connect the minimum number of required players. 39 // Only connect the minimum number of required players.
45 if (index >= min_supported_players) { 40 if (index >= min_supported_players) {
@@ -49,27 +44,27 @@ void DefaultControllerApplet::ReconfigureControllers(std::function<void()> callb
49 // Connect controllers based on the following priority list from highest to lowest priority: 44 // Connect controllers based on the following priority list from highest to lowest priority:
50 // Pro Controller -> Dual Joycons -> Left Joycon/Right Joycon -> Handheld 45 // Pro Controller -> Dual Joycons -> Left Joycon/Right Joycon -> Handheld
51 if (parameters.allow_pro_controller) { 46 if (parameters.allow_pro_controller) {
52 npad.AddNewControllerAt( 47 controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::ProController);
53 npad.MapSettingsTypeToNPad(Settings::ControllerType::ProController), index); 48 controller->Connect();
54 } else if (parameters.allow_dual_joycons) { 49 } else if (parameters.allow_dual_joycons) {
55 npad.AddNewControllerAt( 50 controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::JoyconDual);
56 npad.MapSettingsTypeToNPad(Settings::ControllerType::DualJoyconDetached), index); 51 controller->Connect();
57 } else if (parameters.allow_left_joycon && parameters.allow_right_joycon) { 52 } else if (parameters.allow_left_joycon && parameters.allow_right_joycon) {
58 // Assign left joycons to even player indices and right joycons to odd player indices. 53 // Assign left joycons to even player indices and right joycons to odd player indices.
59 // We do this since Captain Toad Treasure Tracker expects a left joycon for Player 1 and 54 // We do this since Captain Toad Treasure Tracker expects a left joycon for Player 1 and
60 // a right Joycon for Player 2 in 2 Player Assist mode. 55 // a right Joycon for Player 2 in 2 Player Assist mode.
61 if (index % 2 == 0) { 56 if (index % 2 == 0) {
62 npad.AddNewControllerAt( 57 controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::JoyconLeft);
63 npad.MapSettingsTypeToNPad(Settings::ControllerType::LeftJoycon), index); 58 controller->Connect();
64 } else { 59 } else {
65 npad.AddNewControllerAt( 60 controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::JoyconRight);
66 npad.MapSettingsTypeToNPad(Settings::ControllerType::RightJoycon), index); 61 controller->Connect();
67 } 62 }
68 } else if (index == 0 && parameters.enable_single_mode && parameters.allow_handheld && 63 } else if (index == 0 && parameters.enable_single_mode && parameters.allow_handheld &&
69 !Settings::values.use_docked_mode.GetValue()) { 64 !Settings::values.use_docked_mode.GetValue()) {
70 // We should *never* reach here under any normal circumstances. 65 // We should *never* reach here under any normal circumstances.
71 npad.AddNewControllerAt(npad.MapSettingsTypeToNPad(Settings::ControllerType::Handheld), 66 controller->SetNpadStyleIndex(Core::HID::NpadStyleIndex::Handheld);
72 index); 67 controller->Connect();
73 } else { 68 } else {
74 UNREACHABLE_MSG("Unable to add a new controller based on the given parameters!"); 69 UNREACHABLE_MSG("Unable to add a new controller based on the given parameters!");
75 } 70 }
diff --git a/src/core/frontend/applets/controller.h b/src/core/frontend/applets/controller.h
index b0626a0f9..014bc8901 100644
--- a/src/core/frontend/applets/controller.h
+++ b/src/core/frontend/applets/controller.h
@@ -8,8 +8,8 @@
8 8
9#include "common/common_types.h" 9#include "common/common_types.h"
10 10
11namespace Service::SM { 11namespace Core::HID {
12class ServiceManager; 12class HIDCore;
13} 13}
14 14
15namespace Core::Frontend { 15namespace Core::Frontend {
@@ -44,14 +44,14 @@ public:
44 44
45class DefaultControllerApplet final : public ControllerApplet { 45class DefaultControllerApplet final : public ControllerApplet {
46public: 46public:
47 explicit DefaultControllerApplet(Service::SM::ServiceManager& service_manager_); 47 explicit DefaultControllerApplet(HID::HIDCore& hid_core_);
48 ~DefaultControllerApplet() override; 48 ~DefaultControllerApplet() override;
49 49
50 void ReconfigureControllers(std::function<void()> callback, 50 void ReconfigureControllers(std::function<void()> callback,
51 const ControllerParameters& parameters) const override; 51 const ControllerParameters& parameters) const override;
52 52
53private: 53private:
54 Service::SM::ServiceManager& service_manager; 54 HID::HIDCore& hid_core;
55}; 55};
56 56
57} // namespace Core::Frontend 57} // namespace Core::Frontend
diff --git a/src/core/frontend/emu_window.cpp b/src/core/frontend/emu_window.cpp
index e1f7e5886..57c6ffc43 100644
--- a/src/core/frontend/emu_window.cpp
+++ b/src/core/frontend/emu_window.cpp
@@ -3,87 +3,23 @@
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <mutex> 5#include <mutex>
6#include "common/settings.h"
7#include "core/frontend/emu_window.h" 6#include "core/frontend/emu_window.h"
8#include "core/frontend/input.h"
9 7
10namespace Core::Frontend { 8namespace Core::Frontend {
11 9
12GraphicsContext::~GraphicsContext() = default; 10GraphicsContext::~GraphicsContext() = default;
13 11
14class EmuWindow::TouchState : public Input::Factory<Input::TouchDevice>,
15 public std::enable_shared_from_this<TouchState> {
16public:
17 std::unique_ptr<Input::TouchDevice> Create(const Common::ParamPackage&) override {
18 return std::make_unique<Device>(shared_from_this());
19 }
20
21 std::mutex mutex;
22
23 Input::TouchStatus status;
24
25private:
26 class Device : public Input::TouchDevice {
27 public:
28 explicit Device(std::weak_ptr<TouchState>&& touch_state_) : touch_state(touch_state_) {}
29 Input::TouchStatus GetStatus() const override {
30 if (auto state = touch_state.lock()) {
31 std::lock_guard guard{state->mutex};
32 return state->status;
33 }
34 return {};
35 }
36
37 private:
38 std::weak_ptr<TouchState> touch_state;
39 };
40};
41
42EmuWindow::EmuWindow() { 12EmuWindow::EmuWindow() {
43 // TODO: Find a better place to set this. 13 // TODO: Find a better place to set this.
44 config.min_client_area_size = 14 config.min_client_area_size =
45 std::make_pair(Layout::MinimumSize::Width, Layout::MinimumSize::Height); 15 std::make_pair(Layout::MinimumSize::Width, Layout::MinimumSize::Height);
46 active_config = config; 16 active_config = config;
47 touch_state = std::make_shared<TouchState>();
48 Input::RegisterFactory<Input::TouchDevice>("emu_window", touch_state);
49}
50
51EmuWindow::~EmuWindow() {
52 Input::UnregisterFactory<Input::TouchDevice>("emu_window");
53}
54
55/**
56 * Check if the given x/y coordinates are within the touchpad specified by the framebuffer layout
57 * @param layout FramebufferLayout object describing the framebuffer size and screen positions
58 * @param framebuffer_x Framebuffer x-coordinate to check
59 * @param framebuffer_y Framebuffer y-coordinate to check
60 * @return True if the coordinates are within the touchpad, otherwise false
61 */
62static bool IsWithinTouchscreen(const Layout::FramebufferLayout& layout, u32 framebuffer_x,
63 u32 framebuffer_y) {
64 return (framebuffer_y >= layout.screen.top && framebuffer_y < layout.screen.bottom &&
65 framebuffer_x >= layout.screen.left && framebuffer_x < layout.screen.right);
66}
67
68std::pair<u32, u32> EmuWindow::ClipToTouchScreen(u32 new_x, u32 new_y) const {
69 new_x = std::max(new_x, framebuffer_layout.screen.left);
70 new_x = std::min(new_x, framebuffer_layout.screen.right - 1);
71
72 new_y = std::max(new_y, framebuffer_layout.screen.top);
73 new_y = std::min(new_y, framebuffer_layout.screen.bottom - 1);
74
75 return std::make_pair(new_x, new_y);
76} 17}
77 18
78void EmuWindow::TouchPressed(u32 framebuffer_x, u32 framebuffer_y, size_t id) { 19EmuWindow::~EmuWindow() {}
79 if (!IsWithinTouchscreen(framebuffer_layout, framebuffer_x, framebuffer_y)) {
80 return;
81 }
82 if (id >= touch_state->status.size()) {
83 return;
84 }
85 20
86 std::lock_guard guard{touch_state->mutex}; 21std::pair<f32, f32> EmuWindow::MapToTouchScreen(u32 framebuffer_x, u32 framebuffer_y) const {
22 std::tie(framebuffer_x, framebuffer_y) = ClipToTouchScreen(framebuffer_x, framebuffer_y);
87 const float x = 23 const float x =
88 static_cast<float>(framebuffer_x - framebuffer_layout.screen.left) / 24 static_cast<float>(framebuffer_x - framebuffer_layout.screen.left) /
89 static_cast<float>(framebuffer_layout.screen.right - framebuffer_layout.screen.left); 25 static_cast<float>(framebuffer_layout.screen.right - framebuffer_layout.screen.left);
@@ -91,31 +27,17 @@ void EmuWindow::TouchPressed(u32 framebuffer_x, u32 framebuffer_y, size_t id) {
91 static_cast<float>(framebuffer_y - framebuffer_layout.screen.top) / 27 static_cast<float>(framebuffer_y - framebuffer_layout.screen.top) /
92 static_cast<float>(framebuffer_layout.screen.bottom - framebuffer_layout.screen.top); 28 static_cast<float>(framebuffer_layout.screen.bottom - framebuffer_layout.screen.top);
93 29
94 touch_state->status[id] = std::make_tuple(x, y, true); 30 return std::make_pair(x, y);
95}
96
97void EmuWindow::TouchReleased(size_t id) {
98 if (id >= touch_state->status.size()) {
99 return;
100 }
101 std::lock_guard guard{touch_state->mutex};
102 touch_state->status[id] = std::make_tuple(0.0f, 0.0f, false);
103} 31}
104 32
105void EmuWindow::TouchMoved(u32 framebuffer_x, u32 framebuffer_y, size_t id) { 33std::pair<u32, u32> EmuWindow::ClipToTouchScreen(u32 new_x, u32 new_y) const {
106 if (id >= touch_state->status.size()) { 34 new_x = std::max(new_x, framebuffer_layout.screen.left);
107 return; 35 new_x = std::min(new_x, framebuffer_layout.screen.right - 1);
108 }
109
110 if (!std::get<2>(touch_state->status[id])) {
111 return;
112 }
113 36
114 if (!IsWithinTouchscreen(framebuffer_layout, framebuffer_x, framebuffer_y)) { 37 new_y = std::max(new_y, framebuffer_layout.screen.top);
115 std::tie(framebuffer_x, framebuffer_y) = ClipToTouchScreen(framebuffer_x, framebuffer_y); 38 new_y = std::min(new_y, framebuffer_layout.screen.bottom - 1);
116 }
117 39
118 TouchPressed(framebuffer_x, framebuffer_y, id); 40 return std::make_pair(new_x, new_y);
119} 41}
120 42
121void EmuWindow::UpdateCurrentFramebufferLayout(u32 width, u32 height) { 43void EmuWindow::UpdateCurrentFramebufferLayout(u32 width, u32 height) {
diff --git a/src/core/frontend/emu_window.h b/src/core/frontend/emu_window.h
index 8a86a1d27..e413a520a 100644
--- a/src/core/frontend/emu_window.h
+++ b/src/core/frontend/emu_window.h
@@ -113,28 +113,6 @@ public:
113 virtual bool IsShown() const = 0; 113 virtual bool IsShown() const = 0;
114 114
115 /** 115 /**
116 * Signal that a touch pressed event has occurred (e.g. mouse click pressed)
117 * @param framebuffer_x Framebuffer x-coordinate that was pressed
118 * @param framebuffer_y Framebuffer y-coordinate that was pressed
119 * @param id Touch event ID
120 */
121 void TouchPressed(u32 framebuffer_x, u32 framebuffer_y, size_t id);
122
123 /**
124 * Signal that a touch released event has occurred (e.g. mouse click released)
125 * @param id Touch event ID
126 */
127 void TouchReleased(size_t id);
128
129 /**
130 * Signal that a touch movement event has occurred (e.g. mouse was moved over the emu window)
131 * @param framebuffer_x Framebuffer x-coordinate
132 * @param framebuffer_y Framebuffer y-coordinate
133 * @param id Touch event ID
134 */
135 void TouchMoved(u32 framebuffer_x, u32 framebuffer_y, size_t id);
136
137 /**
138 * Returns currently active configuration. 116 * Returns currently active configuration.
139 * @note Accesses to the returned object need not be consistent because it may be modified in 117 * @note Accesses to the returned object need not be consistent because it may be modified in
140 * another thread 118 * another thread
@@ -212,6 +190,11 @@ protected:
212 client_area_height = size.second; 190 client_area_height = size.second;
213 } 191 }
214 192
193 /**
194 * Converts a screen postion into the equivalent touchscreen position.
195 */
196 std::pair<f32, f32> MapToTouchScreen(u32 framebuffer_x, u32 framebuffer_y) const;
197
215 WindowSystemInfo window_info; 198 WindowSystemInfo window_info;
216 199
217private: 200private:
@@ -237,9 +220,6 @@ private:
237 WindowConfig config; ///< Internal configuration (changes pending for being applied in 220 WindowConfig config; ///< Internal configuration (changes pending for being applied in
238 /// ProcessConfigurationChanges) 221 /// ProcessConfigurationChanges)
239 WindowConfig active_config; ///< Internal active configuration 222 WindowConfig active_config; ///< Internal active configuration
240
241 class TouchState;
242 std::shared_ptr<TouchState> touch_state;
243}; 223};
244 224
245} // namespace Core::Frontend 225} // namespace Core::Frontend
diff --git a/src/core/frontend/input.h b/src/core/frontend/input.h
deleted file mode 100644
index f1747c5b2..000000000
--- a/src/core/frontend/input.h
+++ /dev/null
@@ -1,217 +0,0 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <functional>
8#include <memory>
9#include <string>
10#include <tuple>
11#include <unordered_map>
12#include <utility>
13#include "common/logging/log.h"
14#include "common/param_package.h"
15#include "common/quaternion.h"
16#include "common/vector_math.h"
17
18namespace Input {
19
20enum class AnalogDirection : u8 {
21 RIGHT,
22 LEFT,
23 UP,
24 DOWN,
25};
26struct AnalogProperties {
27 float deadzone;
28 float range;
29 float threshold;
30};
31template <typename StatusType>
32struct InputCallback {
33 std::function<void(StatusType)> on_change;
34};
35
36/// An abstract class template for an input device (a button, an analog input, etc.).
37template <typename StatusType>
38class InputDevice {
39public:
40 virtual ~InputDevice() = default;
41 virtual StatusType GetStatus() const {
42 return {};
43 }
44 virtual StatusType GetRawStatus() const {
45 return GetStatus();
46 }
47 virtual AnalogProperties GetAnalogProperties() const {
48 return {};
49 }
50 virtual bool GetAnalogDirectionStatus([[maybe_unused]] AnalogDirection direction) const {
51 return {};
52 }
53 virtual bool SetRumblePlay([[maybe_unused]] f32 amp_low, [[maybe_unused]] f32 freq_low,
54 [[maybe_unused]] f32 amp_high,
55 [[maybe_unused]] f32 freq_high) const {
56 return {};
57 }
58 void SetCallback(InputCallback<StatusType> callback_) {
59 callback = std::move(callback_);
60 }
61 void TriggerOnChange() {
62 if (callback.on_change) {
63 callback.on_change(GetStatus());
64 }
65 }
66
67private:
68 InputCallback<StatusType> callback;
69};
70
71/// An abstract class template for a factory that can create input devices.
72template <typename InputDeviceType>
73class Factory {
74public:
75 virtual ~Factory() = default;
76 virtual std::unique_ptr<InputDeviceType> Create(const Common::ParamPackage&) = 0;
77};
78
79namespace Impl {
80
81template <typename InputDeviceType>
82using FactoryListType = std::unordered_map<std::string, std::shared_ptr<Factory<InputDeviceType>>>;
83
84template <typename InputDeviceType>
85struct FactoryList {
86 static FactoryListType<InputDeviceType> list;
87};
88
89template <typename InputDeviceType>
90FactoryListType<InputDeviceType> FactoryList<InputDeviceType>::list;
91
92} // namespace Impl
93
94/**
95 * Registers an input device factory.
96 * @tparam InputDeviceType the type of input devices the factory can create
97 * @param name the name of the factory. Will be used to match the "engine" parameter when creating
98 * a device
99 * @param factory the factory object to register
100 */
101template <typename InputDeviceType>
102void RegisterFactory(const std::string& name, std::shared_ptr<Factory<InputDeviceType>> factory) {
103 auto pair = std::make_pair(name, std::move(factory));
104 if (!Impl::FactoryList<InputDeviceType>::list.insert(std::move(pair)).second) {
105 LOG_ERROR(Input, "Factory '{}' already registered", name);
106 }
107}
108
109/**
110 * Unregisters an input device factory.
111 * @tparam InputDeviceType the type of input devices the factory can create
112 * @param name the name of the factory to unregister
113 */
114template <typename InputDeviceType>
115void UnregisterFactory(const std::string& name) {
116 if (Impl::FactoryList<InputDeviceType>::list.erase(name) == 0) {
117 LOG_ERROR(Input, "Factory '{}' not registered", name);
118 }
119}
120
121/**
122 * Create an input device from given paramters.
123 * @tparam InputDeviceType the type of input devices to create
124 * @param params a serialized ParamPackage string contains all parameters for creating the device
125 */
126template <typename InputDeviceType>
127std::unique_ptr<InputDeviceType> CreateDevice(const std::string& params) {
128 const Common::ParamPackage package(params);
129 const std::string engine = package.Get("engine", "null");
130 const auto& factory_list = Impl::FactoryList<InputDeviceType>::list;
131 const auto pair = factory_list.find(engine);
132 if (pair == factory_list.end()) {
133 if (engine != "null") {
134 LOG_ERROR(Input, "Unknown engine name: {}", engine);
135 }
136 return std::make_unique<InputDeviceType>();
137 }
138 return pair->second->Create(package);
139}
140
141/**
142 * A button device is an input device that returns bool as status.
143 * true for pressed; false for released.
144 */
145using ButtonDevice = InputDevice<bool>;
146
147/**
148 * An analog device is an input device that returns a tuple of x and y coordinates as status. The
149 * coordinates are within the unit circle. x+ is defined as right direction, and y+ is defined as up
150 * direction
151 */
152using AnalogDevice = InputDevice<std::tuple<float, float>>;
153
154/**
155 * A vibration device is an input device that returns an unsigned byte as status.
156 * It represents whether the vibration device supports vibration or not.
157 * If the status returns 1, it supports vibration. Otherwise, it does not support vibration.
158 */
159using VibrationDevice = InputDevice<u8>;
160
161/**
162 * A motion status is an object that returns a tuple of accelerometer state vector,
163 * gyroscope state vector, rotation state vector, orientation state matrix and quaterion state
164 * vector.
165 *
166 * For both 3D vectors:
167 * x+ is the same direction as RIGHT on D-pad.
168 * y+ is normal to the touch screen, pointing outward.
169 * z+ is the same direction as UP on D-pad.
170 *
171 * For accelerometer state vector
172 * Units: g (gravitational acceleration)
173 *
174 * For gyroscope state vector:
175 * Orientation is determined by right-hand rule.
176 * Units: deg/sec
177 *
178 * For rotation state vector
179 * Units: rotations
180 *
181 * For orientation state matrix
182 * x vector
183 * y vector
184 * z vector
185 *
186 * For quaternion state vector
187 * xyz vector
188 * w float
189 */
190using MotionStatus = std::tuple<Common::Vec3<float>, Common::Vec3<float>, Common::Vec3<float>,
191 std::array<Common::Vec3f, 3>, Common::Quaternion<f32>>;
192
193/**
194 * A motion device is an input device that returns a motion status object
195 */
196using MotionDevice = InputDevice<MotionStatus>;
197
198/**
199 * A touch status is an object that returns an array of 16 tuple elements of two floats and a bool.
200 * The floats are x and y coordinates in the range 0.0 - 1.0, and the bool indicates whether it is
201 * pressed.
202 */
203using TouchStatus = std::array<std::tuple<float, float, bool>, 16>;
204
205/**
206 * A touch device is an input device that returns a touch status object
207 */
208using TouchDevice = InputDevice<TouchStatus>;
209
210/**
211 * A mouse device is an input device that returns a tuple of two floats and four ints.
212 * The first two floats are X and Y device coordinates of the mouse (from 0-1).
213 * The s32s are the mouse wheel.
214 */
215using MouseDevice = InputDevice<std::tuple<float, float, s32, s32>>;
216
217} // namespace Input
diff --git a/src/core/hid/emulated_console.cpp b/src/core/hid/emulated_console.cpp
new file mode 100644
index 000000000..80db8e9c6
--- /dev/null
+++ b/src/core/hid/emulated_console.cpp
@@ -0,0 +1,229 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included
4
5#include "common/settings.h"
6#include "core/hid/emulated_console.h"
7#include "core/hid/input_converter.h"
8
9namespace Core::HID {
10EmulatedConsole::EmulatedConsole() = default;
11
12EmulatedConsole::~EmulatedConsole() = default;
13
14void EmulatedConsole::ReloadFromSettings() {
15 // Using first motion device from player 1. No need to assign any unique config at the moment
16 const auto& player = Settings::values.players.GetValue()[0];
17 motion_params = Common::ParamPackage(player.motions[0]);
18
19 ReloadInput();
20}
21
22void EmulatedConsole::SetTouchParams() {
23 // TODO(german77): Support any number of fingers
24 std::size_t index = 0;
25
26 // Hardcode mouse, touchscreen and cemuhook parameters
27 if (!Settings::values.mouse_enabled) {
28 // We can't use mouse as touch if native mouse is enabled
29 touch_params[index++] = Common::ParamPackage{"engine:mouse,axis_x:10,axis_y:11,button:0"};
30 }
31 touch_params[index++] = Common::ParamPackage{"engine:touch,axis_x:0,axis_y:1,button:0"};
32 touch_params[index++] = Common::ParamPackage{"engine:touch,axis_x:2,axis_y:3,button:1"};
33 touch_params[index++] =
34 Common::ParamPackage{"engine:cemuhookudp,axis_x:17,axis_y:18,button:65536"};
35 touch_params[index++] =
36 Common::ParamPackage{"engine:cemuhookudp,axis_x:19,axis_y:20,button:131072"};
37
38 const auto button_index =
39 static_cast<u64>(Settings::values.touch_from_button_map_index.GetValue());
40 const auto& touch_buttons = Settings::values.touch_from_button_maps[button_index].buttons;
41
42 // Map the rest of the fingers from touch from button configuration
43 for (const auto& config_entry : touch_buttons) {
44 if (index >= touch_params.size()) {
45 continue;
46 }
47 Common::ParamPackage params{config_entry};
48 Common::ParamPackage touch_button_params;
49 const int x = params.Get("x", 0);
50 const int y = params.Get("y", 0);
51 params.Erase("x");
52 params.Erase("y");
53 touch_button_params.Set("engine", "touch_from_button");
54 touch_button_params.Set("button", params.Serialize());
55 touch_button_params.Set("x", x);
56 touch_button_params.Set("y", y);
57 touch_button_params.Set("touch_id", static_cast<int>(index));
58 touch_params[index] = touch_button_params;
59 index++;
60 }
61}
62
63void EmulatedConsole::ReloadInput() {
64 // If you load any device here add the equivalent to the UnloadInput() function
65 SetTouchParams();
66
67 motion_devices = Common::Input::CreateDevice<Common::Input::InputDevice>(motion_params);
68 if (motion_devices) {
69 Common::Input::InputCallback motion_callback{
70 [this](Common::Input::CallbackStatus callback) { SetMotion(callback); }};
71 motion_devices->SetCallback(motion_callback);
72 }
73
74 // Unique index for identifying touch device source
75 std::size_t index = 0;
76 for (auto& touch_device : touch_devices) {
77 touch_device = Common::Input::CreateDevice<Common::Input::InputDevice>(touch_params[index]);
78 if (!touch_device) {
79 continue;
80 }
81 Common::Input::InputCallback touch_callback{
82 [this, index](Common::Input::CallbackStatus callback) { SetTouch(callback, index); }};
83 touch_device->SetCallback(touch_callback);
84 index++;
85 }
86}
87
88void EmulatedConsole::UnloadInput() {
89 motion_devices.reset();
90 for (auto& touch : touch_devices) {
91 touch.reset();
92 }
93}
94
95void EmulatedConsole::EnableConfiguration() {
96 is_configuring = true;
97 SaveCurrentConfig();
98}
99
100void EmulatedConsole::DisableConfiguration() {
101 is_configuring = false;
102}
103
104bool EmulatedConsole::IsConfiguring() const {
105 return is_configuring;
106}
107
108void EmulatedConsole::SaveCurrentConfig() {
109 if (!is_configuring) {
110 return;
111 }
112}
113
114void EmulatedConsole::RestoreConfig() {
115 if (!is_configuring) {
116 return;
117 }
118 ReloadFromSettings();
119}
120
121Common::ParamPackage EmulatedConsole::GetMotionParam() const {
122 return motion_params;
123}
124
125void EmulatedConsole::SetMotionParam(Common::ParamPackage param) {
126 motion_params = param;
127 ReloadInput();
128}
129
130void EmulatedConsole::SetMotion(Common::Input::CallbackStatus callback) {
131 std::lock_guard lock{mutex};
132 auto& raw_status = console.motion_values.raw_status;
133 auto& emulated = console.motion_values.emulated;
134
135 raw_status = TransformToMotion(callback);
136 emulated.SetAcceleration(Common::Vec3f{
137 raw_status.accel.x.value,
138 raw_status.accel.y.value,
139 raw_status.accel.z.value,
140 });
141 emulated.SetGyroscope(Common::Vec3f{
142 raw_status.gyro.x.value,
143 raw_status.gyro.y.value,
144 raw_status.gyro.z.value,
145 });
146 emulated.UpdateRotation(raw_status.delta_timestamp);
147 emulated.UpdateOrientation(raw_status.delta_timestamp);
148
149 if (is_configuring) {
150 TriggerOnChange(ConsoleTriggerType::Motion);
151 return;
152 }
153
154 auto& motion = console.motion_state;
155 motion.accel = emulated.GetAcceleration();
156 motion.gyro = emulated.GetGyroscope();
157 motion.rotation = emulated.GetGyroscope();
158 motion.orientation = emulated.GetOrientation();
159 motion.quaternion = emulated.GetQuaternion();
160 motion.is_at_rest = !emulated.IsMoving(motion_sensitivity);
161
162 TriggerOnChange(ConsoleTriggerType::Motion);
163}
164
165void EmulatedConsole::SetTouch(Common::Input::CallbackStatus callback,
166 [[maybe_unused]] std::size_t index) {
167 if (index >= console.touch_values.size()) {
168 return;
169 }
170 std::lock_guard lock{mutex};
171
172 console.touch_values[index] = TransformToTouch(callback);
173
174 if (is_configuring) {
175 TriggerOnChange(ConsoleTriggerType::Touch);
176 return;
177 }
178
179 // TODO(german77): Remap touch id in sequential order
180 console.touch_state[index] = {
181 .position = {console.touch_values[index].x.value, console.touch_values[index].y.value},
182 .id = static_cast<u32>(console.touch_values[index].id),
183 .pressed = console.touch_values[index].pressed.value,
184 };
185
186 TriggerOnChange(ConsoleTriggerType::Touch);
187}
188
189ConsoleMotionValues EmulatedConsole::GetMotionValues() const {
190 return console.motion_values;
191}
192
193TouchValues EmulatedConsole::GetTouchValues() const {
194 return console.touch_values;
195}
196
197ConsoleMotion EmulatedConsole::GetMotion() const {
198 return console.motion_state;
199}
200
201TouchFingerState EmulatedConsole::GetTouch() const {
202 return console.touch_state;
203}
204
205void EmulatedConsole::TriggerOnChange(ConsoleTriggerType type) {
206 for (const auto& poller_pair : callback_list) {
207 const ConsoleUpdateCallback& poller = poller_pair.second;
208 if (poller.on_change) {
209 poller.on_change(type);
210 }
211 }
212}
213
214int EmulatedConsole::SetCallback(ConsoleUpdateCallback update_callback) {
215 std::lock_guard lock{mutex};
216 callback_list.insert_or_assign(last_callback_key, update_callback);
217 return last_callback_key++;
218}
219
220void EmulatedConsole::DeleteCallback(int key) {
221 std::lock_guard lock{mutex};
222 const auto& iterator = callback_list.find(key);
223 if (iterator == callback_list.end()) {
224 LOG_ERROR(Input, "Tried to delete non-existent callback {}", key);
225 return;
226 }
227 callback_list.erase(iterator);
228}
229} // namespace Core::HID
diff --git a/src/core/hid/emulated_console.h b/src/core/hid/emulated_console.h
new file mode 100644
index 000000000..25c183eee
--- /dev/null
+++ b/src/core/hid/emulated_console.h
@@ -0,0 +1,188 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <functional>
9#include <memory>
10#include <mutex>
11#include <unordered_map>
12
13#include "common/common_types.h"
14#include "common/input.h"
15#include "common/param_package.h"
16#include "common/point.h"
17#include "common/quaternion.h"
18#include "common/vector_math.h"
19#include "core/hid/hid_types.h"
20#include "core/hid/motion_input.h"
21
22namespace Core::HID {
23
24struct ConsoleMotionInfo {
25 Common::Input::MotionStatus raw_status{};
26 MotionInput emulated{};
27};
28
29using ConsoleMotionDevices = std::unique_ptr<Common::Input::InputDevice>;
30using TouchDevices = std::array<std::unique_ptr<Common::Input::InputDevice>, 16>;
31
32using ConsoleMotionParams = Common::ParamPackage;
33using TouchParams = std::array<Common::ParamPackage, 16>;
34
35using ConsoleMotionValues = ConsoleMotionInfo;
36using TouchValues = std::array<Common::Input::TouchStatus, 16>;
37
38struct TouchFinger {
39 u64 last_touch{};
40 Common::Point<float> position{};
41 u32 id{};
42 TouchAttribute attribute{};
43 bool pressed{};
44};
45
46// Contains all motion related data that is used on the services
47struct ConsoleMotion {
48 Common::Vec3f accel{};
49 Common::Vec3f gyro{};
50 Common::Vec3f rotation{};
51 std::array<Common::Vec3f, 3> orientation{};
52 Common::Quaternion<f32> quaternion{};
53 bool is_at_rest{};
54};
55
56using TouchFingerState = std::array<TouchFinger, 16>;
57
58struct ConsoleStatus {
59 // Data from input_common
60 ConsoleMotionValues motion_values{};
61 TouchValues touch_values{};
62
63 // Data for HID services
64 ConsoleMotion motion_state{};
65 TouchFingerState touch_state{};
66};
67
68enum class ConsoleTriggerType {
69 Motion,
70 Touch,
71 All,
72};
73
74struct ConsoleUpdateCallback {
75 std::function<void(ConsoleTriggerType)> on_change;
76};
77
78class EmulatedConsole {
79public:
80 /**
81 * Contains all input data related to the console like motion and touch input
82 */
83 EmulatedConsole();
84 ~EmulatedConsole();
85
86 YUZU_NON_COPYABLE(EmulatedConsole);
87 YUZU_NON_MOVEABLE(EmulatedConsole);
88
89 /// Removes all callbacks created from input devices
90 void UnloadInput();
91
92 /// Sets the emulated console into configuring mode. Locking all HID service events from being
93 /// moddified
94 void EnableConfiguration();
95
96 /// Returns the emulated console to the normal behaivour
97 void DisableConfiguration();
98
99 /// Returns true if the emulated console is on configuring mode
100 bool IsConfiguring() const;
101
102 /// Reload all input devices
103 void ReloadInput();
104
105 /// Overrides current mapped devices with the stored configuration and reloads all input devices
106 void ReloadFromSettings();
107
108 /// Saves the current mapped configuration
109 void SaveCurrentConfig();
110
111 /// Reverts any mapped changes made that weren't saved
112 void RestoreConfig();
113
114 // Returns the current mapped motion device
115 Common::ParamPackage GetMotionParam() const;
116
117 /**
118 * Updates the current mapped motion device
119 * @param ParamPackage with controller data to be mapped
120 */
121 void SetMotionParam(Common::ParamPackage param);
122
123 /// Returns the latest status of motion input from the console with parameters
124 ConsoleMotionValues GetMotionValues() const;
125
126 /// Returns the latest status of touch input from the console with parameters
127 TouchValues GetTouchValues() const;
128
129 /// Returns the latest status of motion input from the console
130 ConsoleMotion GetMotion() const;
131
132 /// Returns the latest status of touch input from the console
133 TouchFingerState GetTouch() const;
134
135 /**
136 * Adds a callback to the list of events
137 * @param ConsoleUpdateCallback that will be triggered
138 * @return an unique key corresponding to the callback index in the list
139 */
140 int SetCallback(ConsoleUpdateCallback update_callback);
141
142 /**
143 * Removes a callback from the list stopping any future events to this object
144 * @param Key corresponding to the callback index in the list
145 */
146 void DeleteCallback(int key);
147
148private:
149 /// Creates and stores the touch params
150 void SetTouchParams();
151
152 /**
153 * Updates the motion status of the console
154 * @param A CallbackStatus containing gyro and accelerometer data
155 */
156 void SetMotion(Common::Input::CallbackStatus callback);
157
158 /**
159 * Updates the touch status of the console
160 * @param callback: A CallbackStatus containing the touch position
161 * @param index: Finger ID to be updated
162 */
163 void SetTouch(Common::Input::CallbackStatus callback, std::size_t index);
164
165 /**
166 * Triggers a callback that something has changed on the console status
167 * @param Input type of the event to trigger
168 */
169 void TriggerOnChange(ConsoleTriggerType type);
170
171 bool is_configuring{false};
172 f32 motion_sensitivity{0.01f};
173
174 ConsoleMotionParams motion_params;
175 TouchParams touch_params;
176
177 ConsoleMotionDevices motion_devices;
178 TouchDevices touch_devices;
179
180 mutable std::mutex mutex;
181 std::unordered_map<int, ConsoleUpdateCallback> callback_list;
182 int last_callback_key = 0;
183
184 // Stores the current status of all console input
185 ConsoleStatus console;
186};
187
188} // namespace Core::HID
diff --git a/src/core/hid/emulated_controller.cpp b/src/core/hid/emulated_controller.cpp
new file mode 100644
index 000000000..06ae41c3e
--- /dev/null
+++ b/src/core/hid/emulated_controller.cpp
@@ -0,0 +1,1061 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included
4
5#include "core/hid/emulated_controller.h"
6#include "core/hid/input_converter.h"
7
8namespace Core::HID {
9constexpr s32 HID_JOYSTICK_MAX = 0x7fff;
10constexpr s32 HID_TRIGGER_MAX = 0x7fff;
11
12EmulatedController::EmulatedController(NpadIdType npad_id_type_) : npad_id_type(npad_id_type_) {}
13
14EmulatedController::~EmulatedController() = default;
15
16NpadStyleIndex EmulatedController::MapSettingsTypeToNPad(Settings::ControllerType type) {
17 switch (type) {
18 case Settings::ControllerType::ProController:
19 return NpadStyleIndex::ProController;
20 case Settings::ControllerType::DualJoyconDetached:
21 return NpadStyleIndex::JoyconDual;
22 case Settings::ControllerType::LeftJoycon:
23 return NpadStyleIndex::JoyconLeft;
24 case Settings::ControllerType::RightJoycon:
25 return NpadStyleIndex::JoyconRight;
26 case Settings::ControllerType::Handheld:
27 return NpadStyleIndex::Handheld;
28 case Settings::ControllerType::GameCube:
29 return NpadStyleIndex::GameCube;
30 default:
31 return NpadStyleIndex::ProController;
32 }
33}
34
35Settings::ControllerType EmulatedController::MapNPadToSettingsType(NpadStyleIndex type) {
36 switch (type) {
37 case NpadStyleIndex::ProController:
38 return Settings::ControllerType::ProController;
39 case NpadStyleIndex::JoyconDual:
40 return Settings::ControllerType::DualJoyconDetached;
41 case NpadStyleIndex::JoyconLeft:
42 return Settings::ControllerType::LeftJoycon;
43 case NpadStyleIndex::JoyconRight:
44 return Settings::ControllerType::RightJoycon;
45 case NpadStyleIndex::Handheld:
46 return Settings::ControllerType::Handheld;
47 case NpadStyleIndex::GameCube:
48 return Settings::ControllerType::GameCube;
49 default:
50 return Settings::ControllerType::ProController;
51 }
52}
53
54void EmulatedController::ReloadFromSettings() {
55 const auto player_index = NpadIdTypeToIndex(npad_id_type);
56 const auto& player = Settings::values.players.GetValue()[player_index];
57
58 for (std::size_t index = 0; index < player.buttons.size(); ++index) {
59 button_params[index] = Common::ParamPackage(player.buttons[index]);
60 }
61 for (std::size_t index = 0; index < player.analogs.size(); ++index) {
62 stick_params[index] = Common::ParamPackage(player.analogs[index]);
63 }
64 for (std::size_t index = 0; index < player.motions.size(); ++index) {
65 motion_params[index] = Common::ParamPackage(player.motions[index]);
66 }
67
68 controller.colors_state.left = {
69 .body = player.body_color_left,
70 .button = player.button_color_left,
71 };
72
73 controller.colors_state.right = {
74 .body = player.body_color_right,
75 .button = player.button_color_right,
76 };
77
78 controller.colors_state.fullkey = controller.colors_state.left;
79
80 // Other or debug controller should always be a pro controller
81 if (npad_id_type != NpadIdType::Other) {
82 SetNpadStyleIndex(MapSettingsTypeToNPad(player.controller_type));
83 } else {
84 SetNpadStyleIndex(NpadStyleIndex::ProController);
85 }
86
87 if (player.connected) {
88 Connect();
89 } else {
90 Disconnect();
91 }
92
93 ReloadInput();
94}
95
96void EmulatedController::LoadDevices() {
97 // TODO(german77): Use more buttons to detect the correct device
98 const auto left_joycon = button_params[Settings::NativeButton::DRight];
99 const auto right_joycon = button_params[Settings::NativeButton::A];
100
101 // Triggers for GC controllers
102 trigger_params[LeftIndex] = button_params[Settings::NativeButton::ZL];
103 trigger_params[RightIndex] = button_params[Settings::NativeButton::ZR];
104
105 battery_params[LeftIndex] = left_joycon;
106 battery_params[RightIndex] = right_joycon;
107 battery_params[LeftIndex].Set("battery", true);
108 battery_params[RightIndex].Set("battery", true);
109
110 output_params[LeftIndex] = left_joycon;
111 output_params[RightIndex] = right_joycon;
112 output_params[LeftIndex].Set("output", true);
113 output_params[RightIndex].Set("output", true);
114
115 LoadTASParams();
116
117 std::transform(button_params.begin() + Settings::NativeButton::BUTTON_HID_BEGIN,
118 button_params.begin() + Settings::NativeButton::BUTTON_NS_END,
119 button_devices.begin(), Common::Input::CreateDevice<Common::Input::InputDevice>);
120 std::transform(stick_params.begin() + Settings::NativeAnalog::STICK_HID_BEGIN,
121 stick_params.begin() + Settings::NativeAnalog::STICK_HID_END,
122 stick_devices.begin(), Common::Input::CreateDevice<Common::Input::InputDevice>);
123 std::transform(motion_params.begin() + Settings::NativeMotion::MOTION_HID_BEGIN,
124 motion_params.begin() + Settings::NativeMotion::MOTION_HID_END,
125 motion_devices.begin(), Common::Input::CreateDevice<Common::Input::InputDevice>);
126 std::transform(trigger_params.begin(), trigger_params.end(), trigger_devices.begin(),
127 Common::Input::CreateDevice<Common::Input::InputDevice>);
128 std::transform(battery_params.begin(), battery_params.begin(), battery_devices.end(),
129 Common::Input::CreateDevice<Common::Input::InputDevice>);
130 std::transform(output_params.begin(), output_params.end(), output_devices.begin(),
131 Common::Input::CreateDevice<Common::Input::OutputDevice>);
132
133 // Initialize TAS devices
134 std::transform(tas_button_params.begin(), tas_button_params.end(), tas_button_devices.begin(),
135 Common::Input::CreateDevice<Common::Input::InputDevice>);
136 std::transform(tas_stick_params.begin(), tas_stick_params.end(), tas_stick_devices.begin(),
137 Common::Input::CreateDevice<Common::Input::InputDevice>);
138}
139
140void EmulatedController::LoadTASParams() {
141 const auto player_index = NpadIdTypeToIndex(npad_id_type);
142 Common::ParamPackage common_params{};
143 common_params.Set("engine", "tas");
144 common_params.Set("port", static_cast<int>(player_index));
145 for (auto& param : tas_button_params) {
146 param = common_params;
147 }
148 for (auto& param : tas_stick_params) {
149 param = common_params;
150 }
151
152 // TODO(german77): Replace this with an input profile or something better
153 tas_button_params[Settings::NativeButton::A].Set("button", 0);
154 tas_button_params[Settings::NativeButton::B].Set("button", 1);
155 tas_button_params[Settings::NativeButton::X].Set("button", 2);
156 tas_button_params[Settings::NativeButton::Y].Set("button", 3);
157 tas_button_params[Settings::NativeButton::LStick].Set("button", 4);
158 tas_button_params[Settings::NativeButton::RStick].Set("button", 5);
159 tas_button_params[Settings::NativeButton::L].Set("button", 6);
160 tas_button_params[Settings::NativeButton::R].Set("button", 7);
161 tas_button_params[Settings::NativeButton::ZL].Set("button", 8);
162 tas_button_params[Settings::NativeButton::ZR].Set("button", 9);
163 tas_button_params[Settings::NativeButton::Plus].Set("button", 10);
164 tas_button_params[Settings::NativeButton::Minus].Set("button", 11);
165 tas_button_params[Settings::NativeButton::DLeft].Set("button", 12);
166 tas_button_params[Settings::NativeButton::DUp].Set("button", 13);
167 tas_button_params[Settings::NativeButton::DRight].Set("button", 14);
168 tas_button_params[Settings::NativeButton::DDown].Set("button", 15);
169 tas_button_params[Settings::NativeButton::SL].Set("button", 16);
170 tas_button_params[Settings::NativeButton::SR].Set("button", 17);
171 tas_button_params[Settings::NativeButton::Home].Set("button", 18);
172 tas_button_params[Settings::NativeButton::Screenshot].Set("button", 19);
173
174 tas_stick_params[Settings::NativeAnalog::LStick].Set("axis_x", 0);
175 tas_stick_params[Settings::NativeAnalog::LStick].Set("axis_y", 1);
176 tas_stick_params[Settings::NativeAnalog::RStick].Set("axis_x", 2);
177 tas_stick_params[Settings::NativeAnalog::RStick].Set("axis_y", 3);
178}
179
180void EmulatedController::ReloadInput() {
181 // If you load any device here add the equivalent to the UnloadInput() function
182 LoadDevices();
183 for (std::size_t index = 0; index < button_devices.size(); ++index) {
184 if (!button_devices[index]) {
185 continue;
186 }
187 const auto uuid = Common::UUID{button_params[index].Get("guid", "")};
188 Common::Input::InputCallback button_callback{
189 [this, index, uuid](Common::Input::CallbackStatus callback) {
190 SetButton(callback, index, uuid);
191 }};
192 button_devices[index]->SetCallback(button_callback);
193 button_devices[index]->ForceUpdate();
194 }
195
196 for (std::size_t index = 0; index < stick_devices.size(); ++index) {
197 if (!stick_devices[index]) {
198 continue;
199 }
200 const auto uuid = Common::UUID{stick_params[index].Get("guid", "")};
201 Common::Input::InputCallback stick_callback{
202 [this, index, uuid](Common::Input::CallbackStatus callback) {
203 SetStick(callback, index, uuid);
204 }};
205 stick_devices[index]->SetCallback(stick_callback);
206 stick_devices[index]->ForceUpdate();
207 }
208
209 for (std::size_t index = 0; index < trigger_devices.size(); ++index) {
210 if (!trigger_devices[index]) {
211 continue;
212 }
213 const auto uuid = Common::UUID{trigger_params[index].Get("guid", "")};
214 Common::Input::InputCallback trigger_callback{
215 [this, index, uuid](Common::Input::CallbackStatus callback) {
216 SetTrigger(callback, index, uuid);
217 }};
218 trigger_devices[index]->SetCallback(trigger_callback);
219 trigger_devices[index]->ForceUpdate();
220 }
221
222 for (std::size_t index = 0; index < battery_devices.size(); ++index) {
223 if (!battery_devices[index]) {
224 continue;
225 }
226 Common::Input::InputCallback battery_callback{
227 [this, index](Common::Input::CallbackStatus callback) { SetBattery(callback, index); }};
228 battery_devices[index]->SetCallback(battery_callback);
229 battery_devices[index]->ForceUpdate();
230 }
231
232 for (std::size_t index = 0; index < motion_devices.size(); ++index) {
233 if (!motion_devices[index]) {
234 continue;
235 }
236 Common::Input::InputCallback motion_callback{
237 [this, index](Common::Input::CallbackStatus callback) { SetMotion(callback, index); }};
238 motion_devices[index]->SetCallback(motion_callback);
239 motion_devices[index]->ForceUpdate();
240 }
241
242 // Use a common UUID for TAS
243 const auto tas_uuid = Common::UUID{0x0, 0x7A5};
244
245 // Register TAS devices. No need to force update
246 for (std::size_t index = 0; index < tas_button_devices.size(); ++index) {
247 if (!tas_button_devices[index]) {
248 continue;
249 }
250 Common::Input::InputCallback button_callback{
251 [this, index, tas_uuid](Common::Input::CallbackStatus callback) {
252 SetButton(callback, index, tas_uuid);
253 }};
254 tas_button_devices[index]->SetCallback(button_callback);
255 }
256
257 for (std::size_t index = 0; index < tas_stick_devices.size(); ++index) {
258 if (!tas_stick_devices[index]) {
259 continue;
260 }
261 Common::Input::InputCallback stick_callback{
262 [this, index, tas_uuid](Common::Input::CallbackStatus callback) {
263 SetStick(callback, index, tas_uuid);
264 }};
265 tas_stick_devices[index]->SetCallback(stick_callback);
266 }
267}
268
269void EmulatedController::UnloadInput() {
270 for (auto& button : button_devices) {
271 button.reset();
272 }
273 for (auto& stick : stick_devices) {
274 stick.reset();
275 }
276 for (auto& motion : motion_devices) {
277 motion.reset();
278 }
279 for (auto& trigger : trigger_devices) {
280 trigger.reset();
281 }
282 for (auto& battery : battery_devices) {
283 battery.reset();
284 }
285 for (auto& output : output_devices) {
286 output.reset();
287 }
288 for (auto& button : tas_button_devices) {
289 button.reset();
290 }
291 for (auto& stick : tas_stick_devices) {
292 stick.reset();
293 }
294}
295
296void EmulatedController::EnableConfiguration() {
297 is_configuring = true;
298 tmp_is_connected = is_connected;
299 tmp_npad_type = npad_type;
300}
301
302void EmulatedController::DisableConfiguration() {
303 is_configuring = false;
304
305 // Apply temporary npad type to the real controller
306 if (tmp_npad_type != npad_type) {
307 if (is_connected) {
308 Disconnect();
309 }
310 SetNpadStyleIndex(tmp_npad_type);
311 }
312
313 // Apply temporary connected status to the real controller
314 if (tmp_is_connected != is_connected) {
315 if (tmp_is_connected) {
316 Connect();
317 return;
318 }
319 Disconnect();
320 }
321}
322
323bool EmulatedController::IsConfiguring() const {
324 return is_configuring;
325}
326
327void EmulatedController::SaveCurrentConfig() {
328 const auto player_index = NpadIdTypeToIndex(npad_id_type);
329 auto& player = Settings::values.players.GetValue()[player_index];
330 player.connected = is_connected;
331 player.controller_type = MapNPadToSettingsType(npad_type);
332 for (std::size_t index = 0; index < player.buttons.size(); ++index) {
333 player.buttons[index] = button_params[index].Serialize();
334 }
335 for (std::size_t index = 0; index < player.analogs.size(); ++index) {
336 player.analogs[index] = stick_params[index].Serialize();
337 }
338 for (std::size_t index = 0; index < player.motions.size(); ++index) {
339 player.motions[index] = motion_params[index].Serialize();
340 }
341}
342
343void EmulatedController::RestoreConfig() {
344 if (!is_configuring) {
345 return;
346 }
347 ReloadFromSettings();
348}
349
350std::vector<Common::ParamPackage> EmulatedController::GetMappedDevices(
351 EmulatedDeviceIndex device_index) const {
352 std::vector<Common::ParamPackage> devices;
353 for (const auto& param : button_params) {
354 if (!param.Has("engine")) {
355 continue;
356 }
357 const auto devices_it = std::find_if(
358 devices.begin(), devices.end(), [param](const Common::ParamPackage param_) {
359 return param.Get("engine", "") == param_.Get("engine", "") &&
360 param.Get("guid", "") == param_.Get("guid", "") &&
361 param.Get("port", 0) == param_.Get("port", 0);
362 });
363 if (devices_it != devices.end()) {
364 continue;
365 }
366 Common::ParamPackage device{};
367 device.Set("engine", param.Get("engine", ""));
368 device.Set("guid", param.Get("guid", ""));
369 device.Set("port", param.Get("port", 0));
370 devices.push_back(device);
371 }
372
373 for (const auto& param : stick_params) {
374 if (!param.Has("engine")) {
375 continue;
376 }
377 if (param.Get("engine", "") == "analog_from_button") {
378 continue;
379 }
380 const auto devices_it = std::find_if(
381 devices.begin(), devices.end(), [param](const Common::ParamPackage param_) {
382 return param.Get("engine", "") == param_.Get("engine", "") &&
383 param.Get("guid", "") == param_.Get("guid", "") &&
384 param.Get("port", 0) == param_.Get("port", 0);
385 });
386 if (devices_it != devices.end()) {
387 continue;
388 }
389 Common::ParamPackage device{};
390 device.Set("engine", param.Get("engine", ""));
391 device.Set("guid", param.Get("guid", ""));
392 device.Set("port", param.Get("port", 0));
393 devices.push_back(device);
394 }
395 return devices;
396}
397
398Common::ParamPackage EmulatedController::GetButtonParam(std::size_t index) const {
399 if (index >= button_params.size()) {
400 return {};
401 }
402 return button_params[index];
403}
404
405Common::ParamPackage EmulatedController::GetStickParam(std::size_t index) const {
406 if (index >= stick_params.size()) {
407 return {};
408 }
409 return stick_params[index];
410}
411
412Common::ParamPackage EmulatedController::GetMotionParam(std::size_t index) const {
413 if (index >= motion_params.size()) {
414 return {};
415 }
416 return motion_params[index];
417}
418
419void EmulatedController::SetButtonParam(std::size_t index, Common::ParamPackage param) {
420 if (index >= button_params.size()) {
421 return;
422 }
423 button_params[index] = param;
424 ReloadInput();
425}
426
427void EmulatedController::SetStickParam(std::size_t index, Common::ParamPackage param) {
428 if (index >= stick_params.size()) {
429 return;
430 }
431 stick_params[index] = param;
432 ReloadInput();
433}
434
435void EmulatedController::SetMotionParam(std::size_t index, Common::ParamPackage param) {
436 if (index >= motion_params.size()) {
437 return;
438 }
439 motion_params[index] = param;
440 ReloadInput();
441}
442
443void EmulatedController::SetButton(Common::Input::CallbackStatus callback, std::size_t index,
444 Common::UUID uuid) {
445 if (index >= controller.button_values.size()) {
446 return;
447 }
448 {
449 std::lock_guard lock{mutex};
450 bool value_changed = false;
451 const auto new_status = TransformToButton(callback);
452 auto& current_status = controller.button_values[index];
453
454 // Only read button values that have the same uuid or are pressed once
455 if (current_status.uuid != uuid) {
456 if (!new_status.value) {
457 return;
458 }
459 }
460
461 current_status.toggle = new_status.toggle;
462 current_status.uuid = uuid;
463
464 // Update button status with current
465 if (!current_status.toggle) {
466 current_status.locked = false;
467 if (current_status.value != new_status.value) {
468 current_status.value = new_status.value;
469 value_changed = true;
470 }
471 } else {
472 // Toggle button and lock status
473 if (new_status.value && !current_status.locked) {
474 current_status.locked = true;
475 current_status.value = !current_status.value;
476 value_changed = true;
477 }
478
479 // Unlock button ready for next press
480 if (!new_status.value && current_status.locked) {
481 current_status.locked = false;
482 }
483 }
484
485 if (!value_changed) {
486 return;
487 }
488
489 if (is_configuring) {
490 controller.npad_button_state.raw = NpadButton::None;
491 controller.debug_pad_button_state.raw = 0;
492 TriggerOnChange(ControllerTriggerType::Button, false);
493 return;
494 }
495
496 switch (index) {
497 case Settings::NativeButton::A:
498 controller.npad_button_state.a.Assign(current_status.value);
499 controller.debug_pad_button_state.a.Assign(current_status.value);
500 break;
501 case Settings::NativeButton::B:
502 controller.npad_button_state.b.Assign(current_status.value);
503 controller.debug_pad_button_state.b.Assign(current_status.value);
504 break;
505 case Settings::NativeButton::X:
506 controller.npad_button_state.x.Assign(current_status.value);
507 controller.debug_pad_button_state.x.Assign(current_status.value);
508 break;
509 case Settings::NativeButton::Y:
510 controller.npad_button_state.y.Assign(current_status.value);
511 controller.debug_pad_button_state.y.Assign(current_status.value);
512 break;
513 case Settings::NativeButton::LStick:
514 controller.npad_button_state.stick_l.Assign(current_status.value);
515 break;
516 case Settings::NativeButton::RStick:
517 controller.npad_button_state.stick_r.Assign(current_status.value);
518 break;
519 case Settings::NativeButton::L:
520 controller.npad_button_state.l.Assign(current_status.value);
521 controller.debug_pad_button_state.l.Assign(current_status.value);
522 break;
523 case Settings::NativeButton::R:
524 controller.npad_button_state.r.Assign(current_status.value);
525 controller.debug_pad_button_state.r.Assign(current_status.value);
526 break;
527 case Settings::NativeButton::ZL:
528 controller.npad_button_state.zl.Assign(current_status.value);
529 controller.debug_pad_button_state.zl.Assign(current_status.value);
530 break;
531 case Settings::NativeButton::ZR:
532 controller.npad_button_state.zr.Assign(current_status.value);
533 controller.debug_pad_button_state.zr.Assign(current_status.value);
534 break;
535 case Settings::NativeButton::Plus:
536 controller.npad_button_state.plus.Assign(current_status.value);
537 controller.debug_pad_button_state.plus.Assign(current_status.value);
538 break;
539 case Settings::NativeButton::Minus:
540 controller.npad_button_state.minus.Assign(current_status.value);
541 controller.debug_pad_button_state.minus.Assign(current_status.value);
542 break;
543 case Settings::NativeButton::DLeft:
544 controller.npad_button_state.left.Assign(current_status.value);
545 controller.debug_pad_button_state.d_left.Assign(current_status.value);
546 break;
547 case Settings::NativeButton::DUp:
548 controller.npad_button_state.up.Assign(current_status.value);
549 controller.debug_pad_button_state.d_up.Assign(current_status.value);
550 break;
551 case Settings::NativeButton::DRight:
552 controller.npad_button_state.right.Assign(current_status.value);
553 controller.debug_pad_button_state.d_right.Assign(current_status.value);
554 break;
555 case Settings::NativeButton::DDown:
556 controller.npad_button_state.down.Assign(current_status.value);
557 controller.debug_pad_button_state.d_down.Assign(current_status.value);
558 break;
559 case Settings::NativeButton::SL:
560 controller.npad_button_state.left_sl.Assign(current_status.value);
561 controller.npad_button_state.right_sl.Assign(current_status.value);
562 break;
563 case Settings::NativeButton::SR:
564 controller.npad_button_state.left_sr.Assign(current_status.value);
565 controller.npad_button_state.right_sr.Assign(current_status.value);
566 break;
567 case Settings::NativeButton::Home:
568 case Settings::NativeButton::Screenshot:
569 break;
570 }
571 }
572 if (!is_connected) {
573 if (npad_id_type == NpadIdType::Player1 && npad_type != NpadStyleIndex::Handheld) {
574 Connect();
575 }
576 if (npad_id_type == NpadIdType::Handheld && npad_type == NpadStyleIndex::Handheld) {
577 Connect();
578 }
579 }
580 TriggerOnChange(ControllerTriggerType::Button, true);
581}
582
583void EmulatedController::SetStick(Common::Input::CallbackStatus callback, std::size_t index,
584 Common::UUID uuid) {
585 if (index >= controller.stick_values.size()) {
586 return;
587 }
588 std::lock_guard lock{mutex};
589 const auto stick_value = TransformToStick(callback);
590
591 // Only read stick values that have the same uuid or are over the threshold to avoid flapping
592 if (controller.stick_values[index].uuid != uuid) {
593 if (!stick_value.down && !stick_value.up && !stick_value.left && !stick_value.right) {
594 return;
595 }
596 }
597
598 controller.stick_values[index] = stick_value;
599 controller.stick_values[index].uuid = uuid;
600
601 if (is_configuring) {
602 controller.analog_stick_state.left = {};
603 controller.analog_stick_state.right = {};
604 TriggerOnChange(ControllerTriggerType::Stick, false);
605 return;
606 }
607
608 const AnalogStickState stick{
609 .x = static_cast<s32>(controller.stick_values[index].x.value * HID_JOYSTICK_MAX),
610 .y = static_cast<s32>(controller.stick_values[index].y.value * HID_JOYSTICK_MAX),
611 };
612
613 switch (index) {
614 case Settings::NativeAnalog::LStick:
615 controller.analog_stick_state.left = stick;
616 controller.npad_button_state.stick_l_left.Assign(controller.stick_values[index].left);
617 controller.npad_button_state.stick_l_up.Assign(controller.stick_values[index].up);
618 controller.npad_button_state.stick_l_right.Assign(controller.stick_values[index].right);
619 controller.npad_button_state.stick_l_down.Assign(controller.stick_values[index].down);
620 break;
621 case Settings::NativeAnalog::RStick:
622 controller.analog_stick_state.right = stick;
623 controller.npad_button_state.stick_r_left.Assign(controller.stick_values[index].left);
624 controller.npad_button_state.stick_r_up.Assign(controller.stick_values[index].up);
625 controller.npad_button_state.stick_r_right.Assign(controller.stick_values[index].right);
626 controller.npad_button_state.stick_r_down.Assign(controller.stick_values[index].down);
627 break;
628 }
629
630 TriggerOnChange(ControllerTriggerType::Stick, true);
631}
632
633void EmulatedController::SetTrigger(Common::Input::CallbackStatus callback, std::size_t index,
634 Common::UUID uuid) {
635 if (index >= controller.trigger_values.size()) {
636 return;
637 }
638 std::lock_guard lock{mutex};
639 const auto trigger_value = TransformToTrigger(callback);
640
641 // Only read trigger values that have the same uuid or are pressed once
642 if (controller.stick_values[index].uuid != uuid) {
643 if (!trigger_value.pressed.value) {
644 return;
645 }
646 }
647
648 controller.trigger_values[index] = trigger_value;
649 controller.trigger_values[index].uuid = uuid;
650
651 if (is_configuring) {
652 controller.gc_trigger_state.left = 0;
653 controller.gc_trigger_state.right = 0;
654 TriggerOnChange(ControllerTriggerType::Trigger, false);
655 return;
656 }
657
658 const auto trigger = controller.trigger_values[index];
659
660 switch (index) {
661 case Settings::NativeTrigger::LTrigger:
662 controller.gc_trigger_state.left = static_cast<s32>(trigger.analog.value * HID_TRIGGER_MAX);
663 controller.npad_button_state.zl.Assign(trigger.pressed.value);
664 break;
665 case Settings::NativeTrigger::RTrigger:
666 controller.gc_trigger_state.right =
667 static_cast<s32>(trigger.analog.value * HID_TRIGGER_MAX);
668 controller.npad_button_state.zr.Assign(trigger.pressed.value);
669 break;
670 }
671
672 TriggerOnChange(ControllerTriggerType::Trigger, true);
673}
674
675void EmulatedController::SetMotion(Common::Input::CallbackStatus callback, std::size_t index) {
676 if (index >= controller.motion_values.size()) {
677 return;
678 }
679 std::lock_guard lock{mutex};
680 auto& raw_status = controller.motion_values[index].raw_status;
681 auto& emulated = controller.motion_values[index].emulated;
682
683 raw_status = TransformToMotion(callback);
684 emulated.SetAcceleration(Common::Vec3f{
685 raw_status.accel.x.value,
686 raw_status.accel.y.value,
687 raw_status.accel.z.value,
688 });
689 emulated.SetGyroscope(Common::Vec3f{
690 raw_status.gyro.x.value,
691 raw_status.gyro.y.value,
692 raw_status.gyro.z.value,
693 });
694 emulated.UpdateRotation(raw_status.delta_timestamp);
695 emulated.UpdateOrientation(raw_status.delta_timestamp);
696 force_update_motion = raw_status.force_update;
697
698 if (is_configuring) {
699 TriggerOnChange(ControllerTriggerType::Motion, false);
700 return;
701 }
702
703 auto& motion = controller.motion_state[index];
704 motion.accel = emulated.GetAcceleration();
705 motion.gyro = emulated.GetGyroscope();
706 motion.rotation = emulated.GetRotations();
707 motion.orientation = emulated.GetOrientation();
708 motion.is_at_rest = !emulated.IsMoving(motion_sensitivity);
709
710 TriggerOnChange(ControllerTriggerType::Motion, true);
711}
712
713void EmulatedController::SetBattery(Common::Input::CallbackStatus callback, std::size_t index) {
714 if (index >= controller.battery_values.size()) {
715 return;
716 }
717 std::lock_guard lock{mutex};
718 controller.battery_values[index] = TransformToBattery(callback);
719
720 if (is_configuring) {
721 TriggerOnChange(ControllerTriggerType::Battery, false);
722 return;
723 }
724
725 bool is_charging = false;
726 bool is_powered = false;
727 NpadBatteryLevel battery_level = 0;
728 switch (controller.battery_values[index]) {
729 case Common::Input::BatteryLevel::Charging:
730 is_charging = true;
731 is_powered = true;
732 battery_level = 6;
733 break;
734 case Common::Input::BatteryLevel::Medium:
735 battery_level = 6;
736 break;
737 case Common::Input::BatteryLevel::Low:
738 battery_level = 4;
739 break;
740 case Common::Input::BatteryLevel::Critical:
741 battery_level = 2;
742 break;
743 case Common::Input::BatteryLevel::Empty:
744 battery_level = 0;
745 break;
746 case Common::Input::BatteryLevel::None:
747 case Common::Input::BatteryLevel::Full:
748 default:
749 is_powered = true;
750 battery_level = 8;
751 break;
752 }
753
754 switch (index) {
755 case LeftIndex:
756 controller.battery_state.left = {
757 .is_powered = is_powered,
758 .is_charging = is_charging,
759 .battery_level = battery_level,
760 };
761 break;
762 case RightIndex:
763 controller.battery_state.right = {
764 .is_powered = is_powered,
765 .is_charging = is_charging,
766 .battery_level = battery_level,
767 };
768 break;
769 case DualIndex:
770 controller.battery_state.dual = {
771 .is_powered = is_powered,
772 .is_charging = is_charging,
773 .battery_level = battery_level,
774 };
775 break;
776 }
777 TriggerOnChange(ControllerTriggerType::Battery, true);
778}
779
780bool EmulatedController::SetVibration(std::size_t device_index, VibrationValue vibration) {
781 if (device_index >= output_devices.size()) {
782 return false;
783 }
784 if (!output_devices[device_index]) {
785 return false;
786 }
787 const auto player_index = NpadIdTypeToIndex(npad_id_type);
788 const auto& player = Settings::values.players.GetValue()[player_index];
789 const f32 strength = static_cast<f32>(player.vibration_strength) / 100.0f;
790
791 if (!player.vibration_enabled) {
792 return false;
793 }
794
795 // Exponential amplification is too strong at low amplitudes. Switch to a linear
796 // amplification if strength is set below 0.7f
797 const Common::Input::VibrationAmplificationType type =
798 strength > 0.7f ? Common::Input::VibrationAmplificationType::Exponential
799 : Common::Input::VibrationAmplificationType::Linear;
800
801 const Common::Input::VibrationStatus status = {
802 .low_amplitude = std::min(vibration.low_amplitude * strength, 1.0f),
803 .low_frequency = vibration.low_frequency,
804 .high_amplitude = std::min(vibration.high_amplitude * strength, 1.0f),
805 .high_frequency = vibration.high_frequency,
806 .type = type,
807 };
808 return output_devices[device_index]->SetVibration(status) ==
809 Common::Input::VibrationError::None;
810}
811
812bool EmulatedController::TestVibration(std::size_t device_index) {
813 if (device_index >= output_devices.size()) {
814 return false;
815 }
816 if (!output_devices[device_index]) {
817 return false;
818 }
819
820 // Send a slight vibration to test for rumble support
821 constexpr Common::Input::VibrationStatus status = {
822 .low_amplitude = 0.001f,
823 .low_frequency = 160.0f,
824 .high_amplitude = 0.001f,
825 .high_frequency = 320.0f,
826 .type = Common::Input::VibrationAmplificationType::Linear,
827 };
828 return output_devices[device_index]->SetVibration(status) ==
829 Common::Input::VibrationError::None;
830}
831
832void EmulatedController::SetLedPattern() {
833 for (auto& device : output_devices) {
834 if (!device) {
835 continue;
836 }
837
838 const LedPattern pattern = GetLedPattern();
839 const Common::Input::LedStatus status = {
840 .led_1 = pattern.position1 != 0,
841 .led_2 = pattern.position2 != 0,
842 .led_3 = pattern.position3 != 0,
843 .led_4 = pattern.position4 != 0,
844 };
845 device->SetLED(status);
846 }
847}
848
849void EmulatedController::Connect() {
850 {
851 std::lock_guard lock{mutex};
852 if (is_configuring) {
853 tmp_is_connected = true;
854 TriggerOnChange(ControllerTriggerType::Connected, false);
855 return;
856 }
857
858 if (is_connected) {
859 return;
860 }
861 is_connected = true;
862 }
863 TriggerOnChange(ControllerTriggerType::Connected, true);
864}
865
866void EmulatedController::Disconnect() {
867 {
868 std::lock_guard lock{mutex};
869 if (is_configuring) {
870 tmp_is_connected = false;
871 TriggerOnChange(ControllerTriggerType::Disconnected, false);
872 return;
873 }
874
875 if (!is_connected) {
876 return;
877 }
878 is_connected = false;
879 }
880 TriggerOnChange(ControllerTriggerType::Disconnected, true);
881}
882
883bool EmulatedController::IsConnected(bool get_temporary_value) const {
884 if (get_temporary_value && is_configuring) {
885 return tmp_is_connected;
886 }
887 return is_connected;
888}
889
890bool EmulatedController::IsVibrationEnabled() const {
891 const auto player_index = NpadIdTypeToIndex(npad_id_type);
892 const auto& player = Settings::values.players.GetValue()[player_index];
893 return player.vibration_enabled;
894}
895
896NpadIdType EmulatedController::GetNpadIdType() const {
897 return npad_id_type;
898}
899
900NpadStyleIndex EmulatedController::GetNpadStyleIndex(bool get_temporary_value) const {
901 if (get_temporary_value && is_configuring) {
902 return tmp_npad_type;
903 }
904 return npad_type;
905}
906
907void EmulatedController::SetNpadStyleIndex(NpadStyleIndex npad_type_) {
908 {
909 std::lock_guard lock{mutex};
910
911 if (is_configuring) {
912 if (tmp_npad_type == npad_type_) {
913 return;
914 }
915 tmp_npad_type = npad_type_;
916 TriggerOnChange(ControllerTriggerType::Type, false);
917 return;
918 }
919
920 if (npad_type == npad_type_) {
921 return;
922 }
923 if (is_connected) {
924 LOG_WARNING(Service_HID, "Controller {} type changed while it's connected",
925 NpadIdTypeToIndex(npad_id_type));
926 }
927 npad_type = npad_type_;
928 }
929 TriggerOnChange(ControllerTriggerType::Type, true);
930}
931
932LedPattern EmulatedController::GetLedPattern() const {
933 switch (npad_id_type) {
934 case NpadIdType::Player1:
935 return LedPattern{1, 0, 0, 0};
936 case NpadIdType::Player2:
937 return LedPattern{1, 1, 0, 0};
938 case NpadIdType::Player3:
939 return LedPattern{1, 1, 1, 0};
940 case NpadIdType::Player4:
941 return LedPattern{1, 1, 1, 1};
942 case NpadIdType::Player5:
943 return LedPattern{1, 0, 0, 1};
944 case NpadIdType::Player6:
945 return LedPattern{1, 0, 1, 0};
946 case NpadIdType::Player7:
947 return LedPattern{1, 0, 1, 1};
948 case NpadIdType::Player8:
949 return LedPattern{0, 1, 1, 0};
950 default:
951 return LedPattern{0, 0, 0, 0};
952 }
953}
954
955ButtonValues EmulatedController::GetButtonsValues() const {
956 return controller.button_values;
957}
958
959SticksValues EmulatedController::GetSticksValues() const {
960 return controller.stick_values;
961}
962
963TriggerValues EmulatedController::GetTriggersValues() const {
964 return controller.trigger_values;
965}
966
967ControllerMotionValues EmulatedController::GetMotionValues() const {
968 return controller.motion_values;
969}
970
971ColorValues EmulatedController::GetColorsValues() const {
972 return controller.color_values;
973}
974
975BatteryValues EmulatedController::GetBatteryValues() const {
976 return controller.battery_values;
977}
978
979NpadButtonState EmulatedController::GetNpadButtons() const {
980 if (is_configuring) {
981 return {};
982 }
983 return controller.npad_button_state;
984}
985
986DebugPadButton EmulatedController::GetDebugPadButtons() const {
987 if (is_configuring) {
988 return {};
989 }
990 return controller.debug_pad_button_state;
991}
992
993AnalogSticks EmulatedController::GetSticks() const {
994 if (is_configuring) {
995 return {};
996 }
997 // Some drivers like stick from buttons need constant refreshing
998 for (auto& device : stick_devices) {
999 if (!device) {
1000 continue;
1001 }
1002 device->SoftUpdate();
1003 }
1004 return controller.analog_stick_state;
1005}
1006
1007NpadGcTriggerState EmulatedController::GetTriggers() const {
1008 if (is_configuring) {
1009 return {};
1010 }
1011 return controller.gc_trigger_state;
1012}
1013
1014MotionState EmulatedController::GetMotions() const {
1015 if (force_update_motion) {
1016 for (auto& device : motion_devices) {
1017 if (!device) {
1018 continue;
1019 }
1020 device->ForceUpdate();
1021 }
1022 }
1023 return controller.motion_state;
1024}
1025
1026ControllerColors EmulatedController::GetColors() const {
1027 return controller.colors_state;
1028}
1029
1030BatteryLevelState EmulatedController::GetBattery() const {
1031 return controller.battery_state;
1032}
1033
1034void EmulatedController::TriggerOnChange(ControllerTriggerType type, bool is_npad_service_update) {
1035 for (const auto& poller_pair : callback_list) {
1036 const ControllerUpdateCallback& poller = poller_pair.second;
1037 if (!is_npad_service_update && poller.is_npad_service) {
1038 continue;
1039 }
1040 if (poller.on_change) {
1041 poller.on_change(type);
1042 }
1043 }
1044}
1045
1046int EmulatedController::SetCallback(ControllerUpdateCallback update_callback) {
1047 std::lock_guard lock{mutex};
1048 callback_list.insert_or_assign(last_callback_key, update_callback);
1049 return last_callback_key++;
1050}
1051
1052void EmulatedController::DeleteCallback(int key) {
1053 std::lock_guard lock{mutex};
1054 const auto& iterator = callback_list.find(key);
1055 if (iterator == callback_list.end()) {
1056 LOG_ERROR(Input, "Tried to delete non-existent callback {}", key);
1057 return;
1058 }
1059 callback_list.erase(iterator);
1060}
1061} // namespace Core::HID
diff --git a/src/core/hid/emulated_controller.h b/src/core/hid/emulated_controller.h
new file mode 100644
index 000000000..2c5d51bc8
--- /dev/null
+++ b/src/core/hid/emulated_controller.h
@@ -0,0 +1,392 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <functional>
9#include <memory>
10#include <mutex>
11#include <unordered_map>
12
13#include "common/common_types.h"
14#include "common/input.h"
15#include "common/param_package.h"
16#include "common/point.h"
17#include "common/quaternion.h"
18#include "common/settings.h"
19#include "common/vector_math.h"
20#include "core/hid/hid_types.h"
21#include "core/hid/motion_input.h"
22
23namespace Core::HID {
24const std::size_t max_emulated_controllers = 2;
25struct ControllerMotionInfo {
26 Common::Input::MotionStatus raw_status{};
27 MotionInput emulated{};
28};
29
30using ButtonDevices =
31 std::array<std::unique_ptr<Common::Input::InputDevice>, Settings::NativeButton::NumButtons>;
32using StickDevices =
33 std::array<std::unique_ptr<Common::Input::InputDevice>, Settings::NativeAnalog::NumAnalogs>;
34using ControllerMotionDevices =
35 std::array<std::unique_ptr<Common::Input::InputDevice>, Settings::NativeMotion::NumMotions>;
36using TriggerDevices =
37 std::array<std::unique_ptr<Common::Input::InputDevice>, Settings::NativeTrigger::NumTriggers>;
38using BatteryDevices =
39 std::array<std::unique_ptr<Common::Input::InputDevice>, max_emulated_controllers>;
40using OutputDevices =
41 std::array<std::unique_ptr<Common::Input::OutputDevice>, max_emulated_controllers>;
42
43using ButtonParams = std::array<Common::ParamPackage, Settings::NativeButton::NumButtons>;
44using StickParams = std::array<Common::ParamPackage, Settings::NativeAnalog::NumAnalogs>;
45using ControllerMotionParams = std::array<Common::ParamPackage, Settings::NativeMotion::NumMotions>;
46using TriggerParams = std::array<Common::ParamPackage, Settings::NativeTrigger::NumTriggers>;
47using BatteryParams = std::array<Common::ParamPackage, max_emulated_controllers>;
48using OutputParams = std::array<Common::ParamPackage, max_emulated_controllers>;
49
50using ButtonValues = std::array<Common::Input::ButtonStatus, Settings::NativeButton::NumButtons>;
51using SticksValues = std::array<Common::Input::StickStatus, Settings::NativeAnalog::NumAnalogs>;
52using TriggerValues =
53 std::array<Common::Input::TriggerStatus, Settings::NativeTrigger::NumTriggers>;
54using ControllerMotionValues = std::array<ControllerMotionInfo, Settings::NativeMotion::NumMotions>;
55using ColorValues = std::array<Common::Input::BodyColorStatus, max_emulated_controllers>;
56using BatteryValues = std::array<Common::Input::BatteryStatus, max_emulated_controllers>;
57using VibrationValues = std::array<Common::Input::VibrationStatus, max_emulated_controllers>;
58
59struct AnalogSticks {
60 AnalogStickState left{};
61 AnalogStickState right{};
62};
63
64struct ControllerColors {
65 NpadControllerColor fullkey{};
66 NpadControllerColor left{};
67 NpadControllerColor right{};
68};
69
70struct BatteryLevelState {
71 NpadPowerInfo dual{};
72 NpadPowerInfo left{};
73 NpadPowerInfo right{};
74};
75
76struct ControllerMotion {
77 Common::Vec3f accel{};
78 Common::Vec3f gyro{};
79 Common::Vec3f rotation{};
80 std::array<Common::Vec3f, 3> orientation{};
81 bool is_at_rest{};
82};
83
84enum EmulatedDeviceIndex : u8 {
85 LeftIndex,
86 RightIndex,
87 DualIndex,
88 AllDevices,
89};
90
91using MotionState = std::array<ControllerMotion, 2>;
92
93struct ControllerStatus {
94 // Data from input_common
95 ButtonValues button_values{};
96 SticksValues stick_values{};
97 ControllerMotionValues motion_values{};
98 TriggerValues trigger_values{};
99 ColorValues color_values{};
100 BatteryValues battery_values{};
101 VibrationValues vibration_values{};
102
103 // Data for HID serices
104 NpadButtonState npad_button_state{};
105 DebugPadButton debug_pad_button_state{};
106 AnalogSticks analog_stick_state{};
107 MotionState motion_state{};
108 NpadGcTriggerState gc_trigger_state{};
109 ControllerColors colors_state{};
110 BatteryLevelState battery_state{};
111};
112
113enum class ControllerTriggerType {
114 Button,
115 Stick,
116 Trigger,
117 Motion,
118 Color,
119 Battery,
120 Vibration,
121 Connected,
122 Disconnected,
123 Type,
124 All,
125};
126
127struct ControllerUpdateCallback {
128 std::function<void(ControllerTriggerType)> on_change;
129 bool is_npad_service;
130};
131
132class EmulatedController {
133public:
134 /**
135 * Contains all input data related to this controller. Like buttons, joysticks, motion.
136 * @param Npad id type for this specific controller
137 */
138 explicit EmulatedController(NpadIdType npad_id_type_);
139 ~EmulatedController();
140
141 YUZU_NON_COPYABLE(EmulatedController);
142 YUZU_NON_MOVEABLE(EmulatedController);
143
144 /// Converts the controller type from settings to npad type
145 static NpadStyleIndex MapSettingsTypeToNPad(Settings::ControllerType type);
146
147 /// Converts npad type to the equivalent of controller type from settings
148 static Settings::ControllerType MapNPadToSettingsType(NpadStyleIndex type);
149
150 /// Gets the NpadIdType for this controller
151 NpadIdType GetNpadIdType() const;
152
153 /// Sets the NpadStyleIndex for this controller
154 void SetNpadStyleIndex(NpadStyleIndex npad_type_);
155
156 /**
157 * Gets the NpadStyleIndex for this controller
158 * @param If true tmp_npad_type will be returned
159 * @return NpadStyleIndex set on the controller
160 */
161 NpadStyleIndex GetNpadStyleIndex(bool get_temporary_value = false) const;
162
163 /// Sets the connected status to true
164 void Connect();
165
166 /// Sets the connected status to false
167 void Disconnect();
168
169 /**
170 * Is the emulated connected
171 * @param If true tmp_is_connected will be returned
172 * @return true if the controller has the connected status
173 */
174 bool IsConnected(bool get_temporary_value = false) const;
175
176 /// Returns true if vibration is enabled
177 bool IsVibrationEnabled() const;
178
179 /// Removes all callbacks created from input devices
180 void UnloadInput();
181
182 /// Sets the emulated console into configuring mode. Locking all HID service events from being
183 /// moddified
184 void EnableConfiguration();
185
186 /// Returns the emulated console to the normal behaivour
187 void DisableConfiguration();
188
189 /// Returns true if the emulated device is on configuring mode
190 bool IsConfiguring() const;
191
192 /// Reload all input devices
193 void ReloadInput();
194
195 /// Overrides current mapped devices with the stored configuration and reloads all input devices
196 void ReloadFromSettings();
197
198 /// Saves the current mapped configuration
199 void SaveCurrentConfig();
200
201 /// Reverts any mapped changes made that weren't saved
202 void RestoreConfig();
203
204 /// Returns a vector of mapped devices from the mapped button and stick parameters
205 std::vector<Common::ParamPackage> GetMappedDevices(EmulatedDeviceIndex device_index) const;
206
207 // Returns the current mapped button device
208 Common::ParamPackage GetButtonParam(std::size_t index) const;
209
210 // Returns the current mapped stick device
211 Common::ParamPackage GetStickParam(std::size_t index) const;
212
213 // Returns the current mapped motion device
214 Common::ParamPackage GetMotionParam(std::size_t index) const;
215
216 /**
217 * Updates the current mapped button device
218 * @param ParamPackage with controller data to be mapped
219 */
220 void SetButtonParam(std::size_t index, Common::ParamPackage param);
221
222 /**
223 * Updates the current mapped stick device
224 * @param ParamPackage with controller data to be mapped
225 */
226 void SetStickParam(std::size_t index, Common::ParamPackage param);
227
228 /**
229 * Updates the current mapped motion device
230 * @param ParamPackage with controller data to be mapped
231 */
232 void SetMotionParam(std::size_t index, Common::ParamPackage param);
233
234 /// Returns the latest button status from the controller with parameters
235 ButtonValues GetButtonsValues() const;
236
237 /// Returns the latest analog stick status from the controller with parameters
238 SticksValues GetSticksValues() const;
239
240 /// Returns the latest trigger status from the controller with parameters
241 TriggerValues GetTriggersValues() const;
242
243 /// Returns the latest motion status from the controller with parameters
244 ControllerMotionValues GetMotionValues() const;
245
246 /// Returns the latest color status from the controller with parameters
247 ColorValues GetColorsValues() const;
248
249 /// Returns the latest battery status from the controller with parameters
250 BatteryValues GetBatteryValues() const;
251
252 /// Returns the latest status of button input for the npad service
253 NpadButtonState GetNpadButtons() const;
254
255 /// Returns the latest status of button input for the debug pad service
256 DebugPadButton GetDebugPadButtons() const;
257
258 /// Returns the latest status of stick input from the mouse
259 AnalogSticks GetSticks() const;
260
261 /// Returns the latest status of trigger input from the mouse
262 NpadGcTriggerState GetTriggers() const;
263
264 /// Returns the latest status of motion input from the mouse
265 MotionState GetMotions() const;
266
267 /// Returns the latest color value from the controller
268 ControllerColors GetColors() const;
269
270 /// Returns the latest battery status from the controller
271 BatteryLevelState GetBattery() const;
272
273 /*
274 * Sends a specific vibration to the output device
275 * @return returns true if vibration had no errors
276 */
277 bool SetVibration(std::size_t device_index, VibrationValue vibration);
278
279 /*
280 * Sends a small vibration to the output device
281 * @return returns true if SetVibration was successfull
282 */
283 bool TestVibration(std::size_t device_index);
284
285 /// Returns the led pattern corresponding to this emulated controller
286 LedPattern GetLedPattern() const;
287
288 /// Asks the output device to change the player led pattern
289 void SetLedPattern();
290
291 /**
292 * Adds a callback to the list of events
293 * @param ConsoleUpdateCallback that will be triggered
294 * @return an unique key corresponding to the callback index in the list
295 */
296 int SetCallback(ControllerUpdateCallback update_callback);
297
298 /**
299 * Removes a callback from the list stopping any future events to this object
300 * @param Key corresponding to the callback index in the list
301 */
302 void DeleteCallback(int key);
303
304private:
305 /// creates input devices from params
306 void LoadDevices();
307
308 /// Set the params for TAS devices
309 void LoadTASParams();
310
311 /**
312 * Updates the button status of the controller
313 * @param callback: A CallbackStatus containing the button status
314 * @param index: Button ID of the to be updated
315 */
316 void SetButton(Common::Input::CallbackStatus callback, std::size_t index, Common::UUID uuid);
317
318 /**
319 * Updates the analog stick status of the controller
320 * @param callback: A CallbackStatus containing the analog stick status
321 * @param index: stick ID of the to be updated
322 */
323 void SetStick(Common::Input::CallbackStatus callback, std::size_t index, Common::UUID uuid);
324
325 /**
326 * Updates the trigger status of the controller
327 * @param callback: A CallbackStatus containing the trigger status
328 * @param index: trigger ID of the to be updated
329 */
330 void SetTrigger(Common::Input::CallbackStatus callback, std::size_t index, Common::UUID uuid);
331
332 /**
333 * Updates the motion status of the controller
334 * @param callback: A CallbackStatus containing gyro and accelerometer data
335 * @param index: motion ID of the to be updated
336 */
337 void SetMotion(Common::Input::CallbackStatus callback, std::size_t index);
338
339 /**
340 * Updates the battery status of the controller
341 * @param callback: A CallbackStatus containing the battery status
342 * @param index: Button ID of the to be updated
343 */
344 void SetBattery(Common::Input::CallbackStatus callback, std::size_t index);
345
346 /**
347 * Triggers a callback that something has changed on the controller status
348 * @param type: Input type of the event to trigger
349 * @param is_service_update: indicates if this event should be sended to only services
350 */
351 void TriggerOnChange(ControllerTriggerType type, bool is_service_update);
352
353 NpadIdType npad_id_type;
354 NpadStyleIndex npad_type{NpadStyleIndex::None};
355 bool is_connected{false};
356 bool is_configuring{false};
357 f32 motion_sensitivity{0.01f};
358 bool force_update_motion{false};
359
360 // Temporary values to avoid doing changes while the controller is on configuration mode
361 NpadStyleIndex tmp_npad_type{NpadStyleIndex::None};
362 bool tmp_is_connected{false};
363
364 ButtonParams button_params;
365 StickParams stick_params;
366 ControllerMotionParams motion_params;
367 TriggerParams trigger_params;
368 BatteryParams battery_params;
369 OutputParams output_params;
370
371 ButtonDevices button_devices;
372 StickDevices stick_devices;
373 ControllerMotionDevices motion_devices;
374 TriggerDevices trigger_devices;
375 BatteryDevices battery_devices;
376 OutputDevices output_devices;
377
378 // TAS related variables
379 ButtonParams tas_button_params;
380 StickParams tas_stick_params;
381 ButtonDevices tas_button_devices;
382 StickDevices tas_stick_devices;
383
384 mutable std::mutex mutex;
385 std::unordered_map<int, ControllerUpdateCallback> callback_list;
386 int last_callback_key = 0;
387
388 // Stores the current status of all controller input
389 ControllerStatus controller;
390};
391
392} // namespace Core::HID
diff --git a/src/core/hid/emulated_devices.cpp b/src/core/hid/emulated_devices.cpp
new file mode 100644
index 000000000..874780ec2
--- /dev/null
+++ b/src/core/hid/emulated_devices.cpp
@@ -0,0 +1,451 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included
4
5#include <algorithm>
6#include <fmt/format.h>
7
8#include "core/hid/emulated_devices.h"
9#include "core/hid/input_converter.h"
10
11namespace Core::HID {
12
13EmulatedDevices::EmulatedDevices() = default;
14
15EmulatedDevices::~EmulatedDevices() = default;
16
17void EmulatedDevices::ReloadFromSettings() {
18 ReloadInput();
19}
20
21void EmulatedDevices::ReloadInput() {
22 // If you load any device here add the equivalent to the UnloadInput() function
23 std::size_t key_index = 0;
24 for (auto& mouse_device : mouse_button_devices) {
25 Common::ParamPackage mouse_params;
26 mouse_params.Set("engine", "mouse");
27 mouse_params.Set("button", static_cast<int>(key_index));
28 mouse_device = Common::Input::CreateDevice<Common::Input::InputDevice>(mouse_params);
29 key_index++;
30 }
31
32 mouse_stick_device = Common::Input::CreateDeviceFromString<Common::Input::InputDevice>(
33 "engine:mouse,axis_x:0,axis_y:1");
34
35 // First two axis are reserved for mouse position
36 key_index = 2;
37 for (auto& mouse_device : mouse_analog_devices) {
38 Common::ParamPackage mouse_params;
39 mouse_params.Set("engine", "mouse");
40 mouse_params.Set("axis", static_cast<int>(key_index));
41 mouse_device = Common::Input::CreateDevice<Common::Input::InputDevice>(mouse_params);
42 key_index++;
43 }
44
45 key_index = 0;
46 for (auto& keyboard_device : keyboard_devices) {
47 // Keyboard keys are only mapped on port 1, pad 0
48 Common::ParamPackage keyboard_params;
49 keyboard_params.Set("engine", "keyboard");
50 keyboard_params.Set("button", static_cast<int>(key_index));
51 keyboard_params.Set("port", 1);
52 keyboard_params.Set("pad", 0);
53 keyboard_device = Common::Input::CreateDevice<Common::Input::InputDevice>(keyboard_params);
54 key_index++;
55 }
56
57 key_index = 0;
58 for (auto& keyboard_device : keyboard_modifier_devices) {
59 // Keyboard moddifiers are only mapped on port 1, pad 1
60 Common::ParamPackage keyboard_params;
61 keyboard_params.Set("engine", "keyboard");
62 keyboard_params.Set("button", static_cast<int>(key_index));
63 keyboard_params.Set("port", 1);
64 keyboard_params.Set("pad", 1);
65 keyboard_device = Common::Input::CreateDevice<Common::Input::InputDevice>(keyboard_params);
66 key_index++;
67 }
68
69 for (std::size_t index = 0; index < mouse_button_devices.size(); ++index) {
70 if (!mouse_button_devices[index]) {
71 continue;
72 }
73 Common::Input::InputCallback button_callback{
74 [this, index](Common::Input::CallbackStatus callback) {
75 SetMouseButton(callback, index);
76 }};
77 mouse_button_devices[index]->SetCallback(button_callback);
78 }
79
80 for (std::size_t index = 0; index < mouse_analog_devices.size(); ++index) {
81 if (!mouse_analog_devices[index]) {
82 continue;
83 }
84 Common::Input::InputCallback button_callback{
85 [this, index](Common::Input::CallbackStatus callback) {
86 SetMouseAnalog(callback, index);
87 }};
88 mouse_analog_devices[index]->SetCallback(button_callback);
89 }
90
91 if (mouse_stick_device) {
92 Common::Input::InputCallback button_callback{
93 [this](Common::Input::CallbackStatus callback) { SetMouseStick(callback); }};
94 mouse_stick_device->SetCallback(button_callback);
95 }
96
97 for (std::size_t index = 0; index < keyboard_devices.size(); ++index) {
98 if (!keyboard_devices[index]) {
99 continue;
100 }
101 Common::Input::InputCallback button_callback{
102 [this, index](Common::Input::CallbackStatus callback) {
103 SetKeyboardButton(callback, index);
104 }};
105 keyboard_devices[index]->SetCallback(button_callback);
106 }
107
108 for (std::size_t index = 0; index < keyboard_modifier_devices.size(); ++index) {
109 if (!keyboard_modifier_devices[index]) {
110 continue;
111 }
112 Common::Input::InputCallback button_callback{
113 [this, index](Common::Input::CallbackStatus callback) {
114 SetKeyboardModifier(callback, index);
115 }};
116 keyboard_modifier_devices[index]->SetCallback(button_callback);
117 }
118}
119
120void EmulatedDevices::UnloadInput() {
121 for (auto& button : mouse_button_devices) {
122 button.reset();
123 }
124 for (auto& analog : mouse_analog_devices) {
125 analog.reset();
126 }
127 mouse_stick_device.reset();
128 for (auto& button : keyboard_devices) {
129 button.reset();
130 }
131 for (auto& button : keyboard_modifier_devices) {
132 button.reset();
133 }
134}
135
136void EmulatedDevices::EnableConfiguration() {
137 is_configuring = true;
138 SaveCurrentConfig();
139}
140
141void EmulatedDevices::DisableConfiguration() {
142 is_configuring = false;
143}
144
145bool EmulatedDevices::IsConfiguring() const {
146 return is_configuring;
147}
148
149void EmulatedDevices::SaveCurrentConfig() {
150 if (!is_configuring) {
151 return;
152 }
153}
154
155void EmulatedDevices::RestoreConfig() {
156 if (!is_configuring) {
157 return;
158 }
159 ReloadFromSettings();
160}
161
162void EmulatedDevices::SetKeyboardButton(Common::Input::CallbackStatus callback, std::size_t index) {
163 if (index >= device_status.keyboard_values.size()) {
164 return;
165 }
166 std::lock_guard lock{mutex};
167 bool value_changed = false;
168 const auto new_status = TransformToButton(callback);
169 auto& current_status = device_status.keyboard_values[index];
170 current_status.toggle = new_status.toggle;
171
172 // Update button status with current status
173 if (!current_status.toggle) {
174 current_status.locked = false;
175 if (current_status.value != new_status.value) {
176 current_status.value = new_status.value;
177 value_changed = true;
178 }
179 } else {
180 // Toggle button and lock status
181 if (new_status.value && !current_status.locked) {
182 current_status.locked = true;
183 current_status.value = !current_status.value;
184 value_changed = true;
185 }
186
187 // Unlock button, ready for next press
188 if (!new_status.value && current_status.locked) {
189 current_status.locked = false;
190 }
191 }
192
193 if (!value_changed) {
194 return;
195 }
196
197 if (is_configuring) {
198 TriggerOnChange(DeviceTriggerType::Keyboard);
199 return;
200 }
201
202 // Index should be converted from NativeKeyboard to KeyboardKeyIndex
203 UpdateKey(index, current_status.value);
204
205 TriggerOnChange(DeviceTriggerType::Keyboard);
206}
207
208void EmulatedDevices::UpdateKey(std::size_t key_index, bool status) {
209 constexpr std::size_t KEYS_PER_BYTE = 8;
210 auto& entry = device_status.keyboard_state.key[key_index / KEYS_PER_BYTE];
211 const u8 mask = static_cast<u8>(1 << (key_index % KEYS_PER_BYTE));
212 if (status) {
213 entry = entry | mask;
214 } else {
215 entry = static_cast<u8>(entry & ~mask);
216 }
217}
218
219void EmulatedDevices::SetKeyboardModifier(Common::Input::CallbackStatus callback,
220 std::size_t index) {
221 if (index >= device_status.keyboard_moddifier_values.size()) {
222 return;
223 }
224 std::lock_guard lock{mutex};
225 bool value_changed = false;
226 const auto new_status = TransformToButton(callback);
227 auto& current_status = device_status.keyboard_moddifier_values[index];
228 current_status.toggle = new_status.toggle;
229
230 // Update button status with current
231 if (!current_status.toggle) {
232 current_status.locked = false;
233 if (current_status.value != new_status.value) {
234 current_status.value = new_status.value;
235 value_changed = true;
236 }
237 } else {
238 // Toggle button and lock status
239 if (new_status.value && !current_status.locked) {
240 current_status.locked = true;
241 current_status.value = !current_status.value;
242 value_changed = true;
243 }
244
245 // Unlock button ready for next press
246 if (!new_status.value && current_status.locked) {
247 current_status.locked = false;
248 }
249 }
250
251 if (!value_changed) {
252 return;
253 }
254
255 if (is_configuring) {
256 TriggerOnChange(DeviceTriggerType::KeyboardModdifier);
257 return;
258 }
259
260 switch (index) {
261 case Settings::NativeKeyboard::LeftControl:
262 case Settings::NativeKeyboard::RightControl:
263 device_status.keyboard_moddifier_state.control.Assign(current_status.value);
264 break;
265 case Settings::NativeKeyboard::LeftShift:
266 case Settings::NativeKeyboard::RightShift:
267 device_status.keyboard_moddifier_state.shift.Assign(current_status.value);
268 break;
269 case Settings::NativeKeyboard::LeftAlt:
270 device_status.keyboard_moddifier_state.left_alt.Assign(current_status.value);
271 break;
272 case Settings::NativeKeyboard::RightAlt:
273 device_status.keyboard_moddifier_state.right_alt.Assign(current_status.value);
274 break;
275 case Settings::NativeKeyboard::CapsLock:
276 device_status.keyboard_moddifier_state.caps_lock.Assign(current_status.value);
277 break;
278 case Settings::NativeKeyboard::ScrollLock:
279 device_status.keyboard_moddifier_state.scroll_lock.Assign(current_status.value);
280 break;
281 case Settings::NativeKeyboard::NumLock:
282 device_status.keyboard_moddifier_state.num_lock.Assign(current_status.value);
283 break;
284 }
285
286 TriggerOnChange(DeviceTriggerType::KeyboardModdifier);
287}
288
289void EmulatedDevices::SetMouseButton(Common::Input::CallbackStatus callback, std::size_t index) {
290 if (index >= device_status.mouse_button_values.size()) {
291 return;
292 }
293 std::lock_guard lock{mutex};
294 bool value_changed = false;
295 const auto new_status = TransformToButton(callback);
296 auto& current_status = device_status.mouse_button_values[index];
297 current_status.toggle = new_status.toggle;
298
299 // Update button status with current
300 if (!current_status.toggle) {
301 current_status.locked = false;
302 if (current_status.value != new_status.value) {
303 current_status.value = new_status.value;
304 value_changed = true;
305 }
306 } else {
307 // Toggle button and lock status
308 if (new_status.value && !current_status.locked) {
309 current_status.locked = true;
310 current_status.value = !current_status.value;
311 value_changed = true;
312 }
313
314 // Unlock button ready for next press
315 if (!new_status.value && current_status.locked) {
316 current_status.locked = false;
317 }
318 }
319
320 if (!value_changed) {
321 return;
322 }
323
324 if (is_configuring) {
325 TriggerOnChange(DeviceTriggerType::Mouse);
326 return;
327 }
328
329 switch (index) {
330 case Settings::NativeMouseButton::Left:
331 device_status.mouse_button_state.left.Assign(current_status.value);
332 break;
333 case Settings::NativeMouseButton::Right:
334 device_status.mouse_button_state.right.Assign(current_status.value);
335 break;
336 case Settings::NativeMouseButton::Middle:
337 device_status.mouse_button_state.middle.Assign(current_status.value);
338 break;
339 case Settings::NativeMouseButton::Forward:
340 device_status.mouse_button_state.forward.Assign(current_status.value);
341 break;
342 case Settings::NativeMouseButton::Back:
343 device_status.mouse_button_state.back.Assign(current_status.value);
344 break;
345 }
346
347 TriggerOnChange(DeviceTriggerType::Mouse);
348}
349
350void EmulatedDevices::SetMouseAnalog(Common::Input::CallbackStatus callback, std::size_t index) {
351 if (index >= device_status.mouse_analog_values.size()) {
352 return;
353 }
354 std::lock_guard lock{mutex};
355 const auto analog_value = TransformToAnalog(callback);
356
357 device_status.mouse_analog_values[index] = analog_value;
358
359 if (is_configuring) {
360 device_status.mouse_position_state = {};
361 TriggerOnChange(DeviceTriggerType::Mouse);
362 return;
363 }
364
365 switch (index) {
366 case Settings::NativeMouseWheel::X:
367 device_status.mouse_wheel_state.x = static_cast<s32>(analog_value.value);
368 break;
369 case Settings::NativeMouseWheel::Y:
370 device_status.mouse_wheel_state.y = static_cast<s32>(analog_value.value);
371 break;
372 }
373
374 TriggerOnChange(DeviceTriggerType::Mouse);
375}
376
377void EmulatedDevices::SetMouseStick(Common::Input::CallbackStatus callback) {
378 std::lock_guard lock{mutex};
379 const auto touch_value = TransformToTouch(callback);
380
381 device_status.mouse_stick_value = touch_value;
382
383 if (is_configuring) {
384 device_status.mouse_position_state = {};
385 TriggerOnChange(DeviceTriggerType::Mouse);
386 return;
387 }
388
389 device_status.mouse_position_state.x = touch_value.x.value;
390 device_status.mouse_position_state.y = touch_value.y.value;
391
392 TriggerOnChange(DeviceTriggerType::Mouse);
393}
394
395KeyboardValues EmulatedDevices::GetKeyboardValues() const {
396 return device_status.keyboard_values;
397}
398
399KeyboardModifierValues EmulatedDevices::GetKeyboardModdifierValues() const {
400 return device_status.keyboard_moddifier_values;
401}
402
403MouseButtonValues EmulatedDevices::GetMouseButtonsValues() const {
404 return device_status.mouse_button_values;
405}
406
407KeyboardKey EmulatedDevices::GetKeyboard() const {
408 return device_status.keyboard_state;
409}
410
411KeyboardModifier EmulatedDevices::GetKeyboardModifier() const {
412 return device_status.keyboard_moddifier_state;
413}
414
415MouseButton EmulatedDevices::GetMouseButtons() const {
416 return device_status.mouse_button_state;
417}
418
419MousePosition EmulatedDevices::GetMousePosition() const {
420 return device_status.mouse_position_state;
421}
422
423AnalogStickState EmulatedDevices::GetMouseWheel() const {
424 return device_status.mouse_wheel_state;
425}
426
427void EmulatedDevices::TriggerOnChange(DeviceTriggerType type) {
428 for (const auto& poller_pair : callback_list) {
429 const InterfaceUpdateCallback& poller = poller_pair.second;
430 if (poller.on_change) {
431 poller.on_change(type);
432 }
433 }
434}
435
436int EmulatedDevices::SetCallback(InterfaceUpdateCallback update_callback) {
437 std::lock_guard lock{mutex};
438 callback_list.insert_or_assign(last_callback_key, update_callback);
439 return last_callback_key++;
440}
441
442void EmulatedDevices::DeleteCallback(int key) {
443 std::lock_guard lock{mutex};
444 const auto& iterator = callback_list.find(key);
445 if (iterator == callback_list.end()) {
446 LOG_ERROR(Input, "Tried to delete non-existent callback {}", key);
447 return;
448 }
449 callback_list.erase(iterator);
450}
451} // namespace Core::HID
diff --git a/src/core/hid/emulated_devices.h b/src/core/hid/emulated_devices.h
new file mode 100644
index 000000000..05a945d08
--- /dev/null
+++ b/src/core/hid/emulated_devices.h
@@ -0,0 +1,209 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <functional>
9#include <memory>
10#include <mutex>
11#include <unordered_map>
12
13#include "common/common_types.h"
14#include "common/input.h"
15#include "common/param_package.h"
16#include "common/settings.h"
17#include "core/hid/hid_types.h"
18
19namespace Core::HID {
20using KeyboardDevices = std::array<std::unique_ptr<Common::Input::InputDevice>,
21 Settings::NativeKeyboard::NumKeyboardKeys>;
22using KeyboardModifierDevices = std::array<std::unique_ptr<Common::Input::InputDevice>,
23 Settings::NativeKeyboard::NumKeyboardMods>;
24using MouseButtonDevices = std::array<std::unique_ptr<Common::Input::InputDevice>,
25 Settings::NativeMouseButton::NumMouseButtons>;
26using MouseAnalogDevices = std::array<std::unique_ptr<Common::Input::InputDevice>,
27 Settings::NativeMouseWheel::NumMouseWheels>;
28using MouseStickDevice = std::unique_ptr<Common::Input::InputDevice>;
29
30using MouseButtonParams =
31 std::array<Common::ParamPackage, Settings::NativeMouseButton::NumMouseButtons>;
32
33using KeyboardValues =
34 std::array<Common::Input::ButtonStatus, Settings::NativeKeyboard::NumKeyboardKeys>;
35using KeyboardModifierValues =
36 std::array<Common::Input::ButtonStatus, Settings::NativeKeyboard::NumKeyboardMods>;
37using MouseButtonValues =
38 std::array<Common::Input::ButtonStatus, Settings::NativeMouseButton::NumMouseButtons>;
39using MouseAnalogValues =
40 std::array<Common::Input::AnalogStatus, Settings::NativeMouseWheel::NumMouseWheels>;
41using MouseStickValue = Common::Input::TouchStatus;
42
43struct MousePosition {
44 f32 x;
45 f32 y;
46};
47
48struct DeviceStatus {
49 // Data from input_common
50 KeyboardValues keyboard_values{};
51 KeyboardModifierValues keyboard_moddifier_values{};
52 MouseButtonValues mouse_button_values{};
53 MouseAnalogValues mouse_analog_values{};
54 MouseStickValue mouse_stick_value{};
55
56 // Data for HID serices
57 KeyboardKey keyboard_state{};
58 KeyboardModifier keyboard_moddifier_state{};
59 MouseButton mouse_button_state{};
60 MousePosition mouse_position_state{};
61 AnalogStickState mouse_wheel_state{};
62};
63
64enum class DeviceTriggerType {
65 Keyboard,
66 KeyboardModdifier,
67 Mouse,
68};
69
70struct InterfaceUpdateCallback {
71 std::function<void(DeviceTriggerType)> on_change;
72};
73
74class EmulatedDevices {
75public:
76 /**
77 * Contains all input data related to external devices that aren't necesarily a controller
78 * like keyboard and mouse
79 */
80 EmulatedDevices();
81 ~EmulatedDevices();
82
83 YUZU_NON_COPYABLE(EmulatedDevices);
84 YUZU_NON_MOVEABLE(EmulatedDevices);
85
86 /// Removes all callbacks created from input devices
87 void UnloadInput();
88
89 /// Sets the emulated console into configuring mode. Locking all HID service events from being
90 /// moddified
91 void EnableConfiguration();
92
93 /// Returns the emulated console to the normal behaivour
94 void DisableConfiguration();
95
96 /// Returns true if the emulated device is on configuring mode
97 bool IsConfiguring() const;
98
99 /// Reload all input devices
100 void ReloadInput();
101
102 /// Overrides current mapped devices with the stored configuration and reloads all input devices
103 void ReloadFromSettings();
104
105 /// Saves the current mapped configuration
106 void SaveCurrentConfig();
107
108 /// Reverts any mapped changes made that weren't saved
109 void RestoreConfig();
110
111 /// Returns the latest status of button input from the keyboard with parameters
112 KeyboardValues GetKeyboardValues() const;
113
114 /// Returns the latest status of button input from the keyboard modifiers with parameters
115 KeyboardModifierValues GetKeyboardModdifierValues() const;
116
117 /// Returns the latest status of button input from the mouse with parameters
118 MouseButtonValues GetMouseButtonsValues() const;
119
120 /// Returns the latest status of button input from the keyboard
121 KeyboardKey GetKeyboard() const;
122
123 /// Returns the latest status of button input from the keyboard modifiers
124 KeyboardModifier GetKeyboardModifier() const;
125
126 /// Returns the latest status of button input from the mouse
127 MouseButton GetMouseButtons() const;
128
129 /// Returns the latest mouse coordinates
130 MousePosition GetMousePosition() const;
131
132 /// Returns the latest mouse wheel change
133 AnalogStickState GetMouseWheel() const;
134
135 /**
136 * Adds a callback to the list of events
137 * @param InterfaceUpdateCallback that will be triggered
138 * @return an unique key corresponding to the callback index in the list
139 */
140 int SetCallback(InterfaceUpdateCallback update_callback);
141
142 /**
143 * Removes a callback from the list stopping any future events to this object
144 * @param Key corresponding to the callback index in the list
145 */
146 void DeleteCallback(int key);
147
148private:
149 /// Helps assigning a value to keyboard_state
150 void UpdateKey(std::size_t key_index, bool status);
151
152 /**
153 * Updates the touch status of the keyboard device
154 * @param callback: A CallbackStatus containing the key status
155 * @param index: key ID to be updated
156 */
157 void SetKeyboardButton(Common::Input::CallbackStatus callback, std::size_t index);
158
159 /**
160 * Updates the keyboard status of the keyboard device
161 * @param callback: A CallbackStatus containing the modifier key status
162 * @param index: modifier key ID to be updated
163 */
164 void SetKeyboardModifier(Common::Input::CallbackStatus callback, std::size_t index);
165
166 /**
167 * Updates the mouse button status of the mouse device
168 * @param callback: A CallbackStatus containing the button status
169 * @param index: Button ID to be updated
170 */
171 void SetMouseButton(Common::Input::CallbackStatus callback, std::size_t index);
172
173 /**
174 * Updates the mouse wheel status of the mouse device
175 * @param callback: A CallbackStatus containing the wheel status
176 * @param index: wheel ID to be updated
177 */
178 void SetMouseAnalog(Common::Input::CallbackStatus callback, std::size_t index);
179
180 /**
181 * Updates the mouse position status of the mouse device
182 * @param callback: A CallbackStatus containing the position status
183 * @param index: stick ID to be updated
184 */
185 void SetMouseStick(Common::Input::CallbackStatus callback);
186
187 /**
188 * Triggers a callback that something has changed on the device status
189 * @param Input type of the event to trigger
190 */
191 void TriggerOnChange(DeviceTriggerType type);
192
193 bool is_configuring{false};
194
195 KeyboardDevices keyboard_devices;
196 KeyboardModifierDevices keyboard_modifier_devices;
197 MouseButtonDevices mouse_button_devices;
198 MouseAnalogDevices mouse_analog_devices;
199 MouseStickDevice mouse_stick_device;
200
201 mutable std::mutex mutex;
202 std::unordered_map<int, InterfaceUpdateCallback> callback_list;
203 int last_callback_key = 0;
204
205 // Stores the current status of all external device input
206 DeviceStatus device_status;
207};
208
209} // namespace Core::HID
diff --git a/src/core/hid/hid_core.cpp b/src/core/hid/hid_core.cpp
new file mode 100644
index 000000000..741a69c3c
--- /dev/null
+++ b/src/core/hid/hid_core.cpp
@@ -0,0 +1,168 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "common/assert.h"
6#include "core/hid/emulated_console.h"
7#include "core/hid/emulated_controller.h"
8#include "core/hid/emulated_devices.h"
9#include "core/hid/hid_core.h"
10
11namespace Core::HID {
12
13HIDCore::HIDCore()
14 : player_1{std::make_unique<EmulatedController>(NpadIdType::Player1)},
15 player_2{std::make_unique<EmulatedController>(NpadIdType::Player2)},
16 player_3{std::make_unique<EmulatedController>(NpadIdType::Player3)},
17 player_4{std::make_unique<EmulatedController>(NpadIdType::Player4)},
18 player_5{std::make_unique<EmulatedController>(NpadIdType::Player5)},
19 player_6{std::make_unique<EmulatedController>(NpadIdType::Player6)},
20 player_7{std::make_unique<EmulatedController>(NpadIdType::Player7)},
21 player_8{std::make_unique<EmulatedController>(NpadIdType::Player8)},
22 other{std::make_unique<EmulatedController>(NpadIdType::Other)},
23 handheld{std::make_unique<EmulatedController>(NpadIdType::Handheld)},
24 console{std::make_unique<EmulatedConsole>()}, devices{std::make_unique<EmulatedDevices>()} {}
25
26HIDCore::~HIDCore() = default;
27
28EmulatedController* HIDCore::GetEmulatedController(NpadIdType npad_id_type) {
29 switch (npad_id_type) {
30 case NpadIdType::Player1:
31 return player_1.get();
32 case NpadIdType::Player2:
33 return player_2.get();
34 case NpadIdType::Player3:
35 return player_3.get();
36 case NpadIdType::Player4:
37 return player_4.get();
38 case NpadIdType::Player5:
39 return player_5.get();
40 case NpadIdType::Player6:
41 return player_6.get();
42 case NpadIdType::Player7:
43 return player_7.get();
44 case NpadIdType::Player8:
45 return player_8.get();
46 case NpadIdType::Other:
47 return other.get();
48 case NpadIdType::Handheld:
49 return handheld.get();
50 case NpadIdType::Invalid:
51 default:
52 UNREACHABLE_MSG("Invalid NpadIdType={}", npad_id_type);
53 return nullptr;
54 }
55}
56
57const EmulatedController* HIDCore::GetEmulatedController(NpadIdType npad_id_type) const {
58 switch (npad_id_type) {
59 case NpadIdType::Player1:
60 return player_1.get();
61 case NpadIdType::Player2:
62 return player_2.get();
63 case NpadIdType::Player3:
64 return player_3.get();
65 case NpadIdType::Player4:
66 return player_4.get();
67 case NpadIdType::Player5:
68 return player_5.get();
69 case NpadIdType::Player6:
70 return player_6.get();
71 case NpadIdType::Player7:
72 return player_7.get();
73 case NpadIdType::Player8:
74 return player_8.get();
75 case NpadIdType::Other:
76 return other.get();
77 case NpadIdType::Handheld:
78 return handheld.get();
79 case NpadIdType::Invalid:
80 default:
81 UNREACHABLE_MSG("Invalid NpadIdType={}", npad_id_type);
82 return nullptr;
83 }
84}
85EmulatedConsole* HIDCore::GetEmulatedConsole() {
86 return console.get();
87}
88
89const EmulatedConsole* HIDCore::GetEmulatedConsole() const {
90 return console.get();
91}
92
93EmulatedDevices* HIDCore::GetEmulatedDevices() {
94 return devices.get();
95}
96
97const EmulatedDevices* HIDCore::GetEmulatedDevices() const {
98 return devices.get();
99}
100
101EmulatedController* HIDCore::GetEmulatedControllerByIndex(std::size_t index) {
102 return GetEmulatedController(IndexToNpadIdType(index));
103}
104
105const EmulatedController* HIDCore::GetEmulatedControllerByIndex(std::size_t index) const {
106 return GetEmulatedController(IndexToNpadIdType(index));
107}
108
109void HIDCore::SetSupportedStyleTag(NpadStyleTag style_tag) {
110 supported_style_tag.raw = style_tag.raw;
111}
112
113NpadStyleTag HIDCore::GetSupportedStyleTag() const {
114 return supported_style_tag;
115}
116
117s8 HIDCore::GetPlayerCount() const {
118 s8 active_players = 0;
119 for (std::size_t player_index = 0; player_index < available_controllers - 2; ++player_index) {
120 const auto* const controller = GetEmulatedControllerByIndex(player_index);
121 if (controller->IsConnected()) {
122 active_players++;
123 }
124 }
125 return active_players;
126}
127
128NpadIdType HIDCore::GetFirstNpadId() const {
129 for (std::size_t player_index = 0; player_index < available_controllers; ++player_index) {
130 const auto* const controller = GetEmulatedControllerByIndex(player_index);
131 if (controller->IsConnected()) {
132 return controller->GetNpadIdType();
133 }
134 }
135 return NpadIdType::Player1;
136}
137
138void HIDCore::ReloadInputDevices() {
139 player_1->ReloadFromSettings();
140 player_2->ReloadFromSettings();
141 player_3->ReloadFromSettings();
142 player_4->ReloadFromSettings();
143 player_5->ReloadFromSettings();
144 player_6->ReloadFromSettings();
145 player_7->ReloadFromSettings();
146 player_8->ReloadFromSettings();
147 other->ReloadFromSettings();
148 handheld->ReloadFromSettings();
149 console->ReloadFromSettings();
150 devices->ReloadFromSettings();
151}
152
153void HIDCore::UnloadInputDevices() {
154 player_1->UnloadInput();
155 player_2->UnloadInput();
156 player_3->UnloadInput();
157 player_4->UnloadInput();
158 player_5->UnloadInput();
159 player_6->UnloadInput();
160 player_7->UnloadInput();
161 player_8->UnloadInput();
162 other->UnloadInput();
163 handheld->UnloadInput();
164 console->UnloadInput();
165 devices->UnloadInput();
166}
167
168} // namespace Core::HID
diff --git a/src/core/hid/hid_core.h b/src/core/hid/hid_core.h
new file mode 100644
index 000000000..609f40f3b
--- /dev/null
+++ b/src/core/hid/hid_core.h
@@ -0,0 +1,73 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <memory>
8
9#include "core/hid/hid_types.h"
10
11namespace Core::HID {
12class EmulatedConsole;
13class EmulatedController;
14class EmulatedDevices;
15} // namespace Core::HID
16
17namespace Core::HID {
18
19class HIDCore {
20public:
21 explicit HIDCore();
22 ~HIDCore();
23
24 YUZU_NON_COPYABLE(HIDCore);
25 YUZU_NON_MOVEABLE(HIDCore);
26
27 EmulatedController* GetEmulatedController(NpadIdType npad_id_type);
28 const EmulatedController* GetEmulatedController(NpadIdType npad_id_type) const;
29
30 EmulatedController* GetEmulatedControllerByIndex(std::size_t index);
31 const EmulatedController* GetEmulatedControllerByIndex(std::size_t index) const;
32
33 EmulatedConsole* GetEmulatedConsole();
34 const EmulatedConsole* GetEmulatedConsole() const;
35
36 EmulatedDevices* GetEmulatedDevices();
37 const EmulatedDevices* GetEmulatedDevices() const;
38
39 void SetSupportedStyleTag(NpadStyleTag style_tag);
40 NpadStyleTag GetSupportedStyleTag() const;
41
42 /// Counts the connected players from P1-P8
43 s8 GetPlayerCount() const;
44
45 /// Returns the first connected npad id
46 NpadIdType GetFirstNpadId() const;
47
48 /// Reloads all input devices from settings
49 void ReloadInputDevices();
50
51 /// Removes all callbacks from input common
52 void UnloadInputDevices();
53
54 /// Number of emulated controllers
55 static constexpr std::size_t available_controllers{10};
56
57private:
58 std::unique_ptr<EmulatedController> player_1;
59 std::unique_ptr<EmulatedController> player_2;
60 std::unique_ptr<EmulatedController> player_3;
61 std::unique_ptr<EmulatedController> player_4;
62 std::unique_ptr<EmulatedController> player_5;
63 std::unique_ptr<EmulatedController> player_6;
64 std::unique_ptr<EmulatedController> player_7;
65 std::unique_ptr<EmulatedController> player_8;
66 std::unique_ptr<EmulatedController> other;
67 std::unique_ptr<EmulatedController> handheld;
68 std::unique_ptr<EmulatedConsole> console;
69 std::unique_ptr<EmulatedDevices> devices;
70 NpadStyleTag supported_style_tag;
71};
72
73} // namespace Core::HID
diff --git a/src/core/hid/hid_types.h b/src/core/hid/hid_types.h
new file mode 100644
index 000000000..acf54e233
--- /dev/null
+++ b/src/core/hid/hid_types.h
@@ -0,0 +1,631 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include "common/bit_field.h"
8#include "common/common_funcs.h"
9#include "common/common_types.h"
10#include "common/point.h"
11#include "common/uuid.h"
12
13namespace Core::HID {
14
15enum class DeviceIndex : u8 {
16 Left = 0,
17 Right = 1,
18 None = 2,
19 MaxDeviceIndex = 3,
20};
21
22// This is nn::hid::NpadButton
23enum class NpadButton : u64 {
24 None = 0,
25 A = 1U << 0,
26 B = 1U << 1,
27 X = 1U << 2,
28 Y = 1U << 3,
29 StickL = 1U << 4,
30 StickR = 1U << 5,
31 L = 1U << 6,
32 R = 1U << 7,
33 ZL = 1U << 8,
34 ZR = 1U << 9,
35 Plus = 1U << 10,
36 Minus = 1U << 11,
37
38 Left = 1U << 12,
39 Up = 1U << 13,
40 Right = 1U << 14,
41 Down = 1U << 15,
42
43 StickLLeft = 1U << 16,
44 StickLUp = 1U << 17,
45 StickLRight = 1U << 18,
46 StickLDown = 1U << 19,
47
48 StickRLeft = 1U << 20,
49 StickRUp = 1U << 21,
50 StickRRight = 1U << 22,
51 StickRDown = 1U << 23,
52
53 LeftSL = 1U << 24,
54 LeftSR = 1U << 25,
55
56 RightSL = 1U << 26,
57 RightSR = 1U << 27,
58
59 Palma = 1U << 28,
60 Verification = 1U << 29,
61 HandheldLeftB = 1U << 30,
62 LagonCLeft = 1U << 31,
63 LagonCUp = 1ULL << 32,
64 LagonCRight = 1ULL << 33,
65 LagonCDown = 1ULL << 34,
66};
67DECLARE_ENUM_FLAG_OPERATORS(NpadButton);
68
69enum class KeyboardKeyIndex : u32 {
70 A = 4,
71 B = 5,
72 C = 6,
73 D = 7,
74 E = 8,
75 F = 9,
76 G = 10,
77 H = 11,
78 I = 12,
79 J = 13,
80 K = 14,
81 L = 15,
82 M = 16,
83 N = 17,
84 O = 18,
85 P = 19,
86 Q = 20,
87 R = 21,
88 S = 22,
89 T = 23,
90 U = 24,
91 V = 25,
92 W = 26,
93 X = 27,
94 Y = 28,
95 Z = 29,
96 D1 = 30,
97 D2 = 31,
98 D3 = 32,
99 D4 = 33,
100 D5 = 34,
101 D6 = 35,
102 D7 = 36,
103 D8 = 37,
104 D9 = 38,
105 D0 = 39,
106 Return = 40,
107 Escape = 41,
108 Backspace = 42,
109 Tab = 43,
110 Space = 44,
111 Minus = 45,
112 Plus = 46,
113 OpenBracket = 47,
114 CloseBracket = 48,
115 Pipe = 49,
116 Tilde = 50,
117 Semicolon = 51,
118 Quote = 52,
119 Backquote = 53,
120 Comma = 54,
121 Period = 55,
122 Slash = 56,
123 CapsLock = 57,
124 F1 = 58,
125 F2 = 59,
126 F3 = 60,
127 F4 = 61,
128 F5 = 62,
129 F6 = 63,
130 F7 = 64,
131 F8 = 65,
132 F9 = 66,
133 F10 = 67,
134 F11 = 68,
135 F12 = 69,
136 PrintScreen = 70,
137 ScrollLock = 71,
138 Pause = 72,
139 Insert = 73,
140 Home = 74,
141 PageUp = 75,
142 Delete = 76,
143 End = 77,
144 PageDown = 78,
145 RightArrow = 79,
146 LeftArrow = 80,
147 DownArrow = 81,
148 UpArrow = 82,
149 NumLock = 83,
150 NumPadDivide = 84,
151 NumPadMultiply = 85,
152 NumPadSubtract = 86,
153 NumPadAdd = 87,
154 NumPadEnter = 88,
155 NumPad1 = 89,
156 NumPad2 = 90,
157 NumPad3 = 91,
158 NumPad4 = 92,
159 NumPad5 = 93,
160 NumPad6 = 94,
161 NumPad7 = 95,
162 NumPad8 = 96,
163 NumPad9 = 97,
164 NumPad0 = 98,
165 NumPadDot = 99,
166 Backslash = 100,
167 Application = 101,
168 Power = 102,
169 NumPadEquals = 103,
170 F13 = 104,
171 F14 = 105,
172 F15 = 106,
173 F16 = 107,
174 F17 = 108,
175 F18 = 109,
176 F19 = 110,
177 F20 = 111,
178 F21 = 112,
179 F22 = 113,
180 F23 = 114,
181 F24 = 115,
182 NumPadComma = 133,
183 Ro = 135,
184 KatakanaHiragana = 136,
185 Yen = 137,
186 Henkan = 138,
187 Muhenkan = 139,
188 NumPadCommaPc98 = 140,
189 HangulEnglish = 144,
190 Hanja = 145,
191 Katakana = 146,
192 Hiragana = 147,
193 ZenkakuHankaku = 148,
194 LeftControl = 224,
195 LeftShift = 225,
196 LeftAlt = 226,
197 LeftGui = 227,
198 RightControl = 228,
199 RightShift = 229,
200 RightAlt = 230,
201 RightGui = 231,
202};
203
204// This is nn::hid::NpadIdType
205enum class NpadIdType : u32 {
206 Player1 = 0x0,
207 Player2 = 0x1,
208 Player3 = 0x2,
209 Player4 = 0x3,
210 Player5 = 0x4,
211 Player6 = 0x5,
212 Player7 = 0x6,
213 Player8 = 0x7,
214 Other = 0x10,
215 Handheld = 0x20,
216
217 Invalid = 0xFFFFFFFF,
218};
219
220// This is nn::hid::NpadStyleIndex
221enum class NpadStyleIndex : u8 {
222 None = 0,
223 ProController = 3,
224 Handheld = 4,
225 HandheldNES = 4,
226 JoyconDual = 5,
227 JoyconLeft = 6,
228 JoyconRight = 7,
229 GameCube = 8,
230 Pokeball = 9,
231 NES = 10,
232 SNES = 12,
233 N64 = 13,
234 SegaGenesis = 14,
235 SystemExt = 32,
236 System = 33,
237 MaxNpadType = 34,
238};
239
240// This is nn::hid::NpadStyleSet
241enum class NpadStyleSet : u32 {
242 None = 0,
243 Fullkey = 1U << 0,
244 Handheld = 1U << 1,
245 JoyDual = 1U << 2,
246 JoyLeft = 1U << 3,
247 JoyRight = 1U << 4,
248 Gc = 1U << 5,
249 Palma = 1U << 6,
250 Lark = 1U << 7,
251 HandheldLark = 1U << 8,
252 Lucia = 1U << 9,
253 Lagoon = 1U << 10,
254 Lager = 1U << 11,
255 SystemExt = 1U << 29,
256 System = 1U << 30,
257};
258static_assert(sizeof(NpadStyleSet) == 4, "NpadStyleSet is an invalid size");
259
260// This is nn::hid::VibrationDevicePosition
261enum class VibrationDevicePosition : u32 {
262 None = 0,
263 Left = 1,
264 Right = 2,
265};
266
267// This is nn::hid::VibrationDeviceType
268enum class VibrationDeviceType : u32 {
269 Unknown = 0,
270 LinearResonantActuator = 1,
271 GcErm = 2,
272};
273
274// This is nn::hid::VibrationGcErmCommand
275enum class VibrationGcErmCommand : u64 {
276 Stop = 0,
277 Start = 1,
278 StopHard = 2,
279};
280
281// This is nn::hid::NpadStyleTag
282struct NpadStyleTag {
283 union {
284 NpadStyleSet raw{};
285
286 BitField<0, 1, u32> fullkey;
287 BitField<1, 1, u32> handheld;
288 BitField<2, 1, u32> joycon_dual;
289 BitField<3, 1, u32> joycon_left;
290 BitField<4, 1, u32> joycon_right;
291 BitField<5, 1, u32> gamecube;
292 BitField<6, 1, u32> palma;
293 BitField<7, 1, u32> lark;
294 BitField<8, 1, u32> handheld_lark;
295 BitField<9, 1, u32> lucia;
296 BitField<10, 1, u32> lagoon;
297 BitField<11, 1, u32> lager;
298 BitField<29, 1, u32> system_ext;
299 BitField<30, 1, u32> system;
300 };
301};
302static_assert(sizeof(NpadStyleTag) == 4, "NpadStyleTag is an invalid size");
303
304// This is nn::hid::TouchAttribute
305struct TouchAttribute {
306 union {
307 u32 raw{};
308 BitField<0, 1, u32> start_touch;
309 BitField<1, 1, u32> end_touch;
310 };
311};
312static_assert(sizeof(TouchAttribute) == 0x4, "TouchAttribute is an invalid size");
313
314// This is nn::hid::TouchState
315struct TouchState {
316 u64 delta_time;
317 TouchAttribute attribute;
318 u32 finger;
319 Common::Point<u32> position;
320 u32 diameter_x;
321 u32 diameter_y;
322 u32 rotation_angle;
323};
324static_assert(sizeof(TouchState) == 0x28, "Touchstate is an invalid size");
325
326// This is nn::hid::NpadControllerColor
327struct NpadControllerColor {
328 u32 body;
329 u32 button;
330};
331static_assert(sizeof(NpadControllerColor) == 8, "NpadControllerColor is an invalid size");
332
333// This is nn::hid::AnalogStickState
334struct AnalogStickState {
335 s32 x;
336 s32 y;
337};
338static_assert(sizeof(AnalogStickState) == 8, "AnalogStickState is an invalid size");
339
340// This is nn::hid::server::NpadGcTriggerState
341struct NpadGcTriggerState {
342 s64 sampling_number{};
343 s32 left{};
344 s32 right{};
345};
346static_assert(sizeof(NpadGcTriggerState) == 0x10, "NpadGcTriggerState is an invalid size");
347
348// This is nn::hid::system::NpadBatteryLevel
349using NpadBatteryLevel = u32;
350static_assert(sizeof(NpadBatteryLevel) == 0x4, "NpadBatteryLevel is an invalid size");
351
352// This is nn::hid::system::NpadPowerInfo
353struct NpadPowerInfo {
354 bool is_powered;
355 bool is_charging;
356 INSERT_PADDING_BYTES(0x6);
357 NpadBatteryLevel battery_level;
358};
359static_assert(sizeof(NpadPowerInfo) == 0xC, "NpadPowerInfo is an invalid size");
360
361struct LedPattern {
362 explicit LedPattern(u64 light1, u64 light2, u64 light3, u64 light4) {
363 position1.Assign(light1);
364 position2.Assign(light2);
365 position3.Assign(light3);
366 position4.Assign(light4);
367 }
368 union {
369 u64 raw{};
370 BitField<0, 1, u64> position1;
371 BitField<1, 1, u64> position2;
372 BitField<2, 1, u64> position3;
373 BitField<3, 1, u64> position4;
374 };
375};
376
377struct NpadButtonState {
378 union {
379 NpadButton raw{};
380
381 // Buttons
382 BitField<0, 1, u64> a;
383 BitField<1, 1, u64> b;
384 BitField<2, 1, u64> x;
385 BitField<3, 1, u64> y;
386 BitField<4, 1, u64> stick_l;
387 BitField<5, 1, u64> stick_r;
388 BitField<6, 1, u64> l;
389 BitField<7, 1, u64> r;
390 BitField<8, 1, u64> zl;
391 BitField<9, 1, u64> zr;
392 BitField<10, 1, u64> plus;
393 BitField<11, 1, u64> minus;
394
395 // D-Pad
396 BitField<12, 1, u64> left;
397 BitField<13, 1, u64> up;
398 BitField<14, 1, u64> right;
399 BitField<15, 1, u64> down;
400
401 // Left JoyStick
402 BitField<16, 1, u64> stick_l_left;
403 BitField<17, 1, u64> stick_l_up;
404 BitField<18, 1, u64> stick_l_right;
405 BitField<19, 1, u64> stick_l_down;
406
407 // Right JoyStick
408 BitField<20, 1, u64> stick_r_left;
409 BitField<21, 1, u64> stick_r_up;
410 BitField<22, 1, u64> stick_r_right;
411 BitField<23, 1, u64> stick_r_down;
412
413 BitField<24, 1, u64> left_sl;
414 BitField<25, 1, u64> left_sr;
415
416 BitField<26, 1, u64> right_sl;
417 BitField<27, 1, u64> right_sr;
418
419 BitField<28, 1, u64> palma;
420 BitField<29, 1, u64> verification;
421 BitField<30, 1, u64> handheld_left_b;
422 BitField<31, 1, u64> lagon_c_left;
423 BitField<32, 1, u64> lagon_c_up;
424 BitField<33, 1, u64> lagon_c_right;
425 BitField<34, 1, u64> lagon_c_down;
426 };
427};
428static_assert(sizeof(NpadButtonState) == 0x8, "NpadButtonState has incorrect size.");
429
430// This is nn::hid::DebugPadButton
431struct DebugPadButton {
432 union {
433 u32 raw{};
434 BitField<0, 1, u32> a;
435 BitField<1, 1, u32> b;
436 BitField<2, 1, u32> x;
437 BitField<3, 1, u32> y;
438 BitField<4, 1, u32> l;
439 BitField<5, 1, u32> r;
440 BitField<6, 1, u32> zl;
441 BitField<7, 1, u32> zr;
442 BitField<8, 1, u32> plus;
443 BitField<9, 1, u32> minus;
444 BitField<10, 1, u32> d_left;
445 BitField<11, 1, u32> d_up;
446 BitField<12, 1, u32> d_right;
447 BitField<13, 1, u32> d_down;
448 };
449};
450static_assert(sizeof(DebugPadButton) == 0x4, "DebugPadButton is an invalid size");
451
452// This is nn::hid::ConsoleSixAxisSensorHandle
453struct ConsoleSixAxisSensorHandle {
454 u8 unknown_1;
455 u8 unknown_2;
456 INSERT_PADDING_BYTES_NOINIT(2);
457};
458static_assert(sizeof(ConsoleSixAxisSensorHandle) == 4,
459 "ConsoleSixAxisSensorHandle is an invalid size");
460
461// This is nn::hid::SixAxisSensorHandle
462struct SixAxisSensorHandle {
463 NpadStyleIndex npad_type;
464 u8 npad_id;
465 DeviceIndex device_index;
466 INSERT_PADDING_BYTES_NOINIT(1);
467};
468static_assert(sizeof(SixAxisSensorHandle) == 4, "SixAxisSensorHandle is an invalid size");
469
470struct SixAxisSensorFusionParameters {
471 f32 parameter1;
472 f32 parameter2;
473};
474static_assert(sizeof(SixAxisSensorFusionParameters) == 8,
475 "SixAxisSensorFusionParameters is an invalid size");
476
477// This is nn::hid::VibrationDeviceHandle
478struct VibrationDeviceHandle {
479 NpadStyleIndex npad_type;
480 u8 npad_id;
481 DeviceIndex device_index;
482 INSERT_PADDING_BYTES_NOINIT(1);
483};
484static_assert(sizeof(VibrationDeviceHandle) == 4, "SixAxisSensorHandle is an invalid size");
485
486// This is nn::hid::VibrationValue
487struct VibrationValue {
488 f32 low_amplitude;
489 f32 low_frequency;
490 f32 high_amplitude;
491 f32 high_frequency;
492};
493static_assert(sizeof(VibrationValue) == 0x10, "VibrationValue has incorrect size.");
494
495// This is nn::hid::VibrationDeviceInfo
496struct VibrationDeviceInfo {
497 VibrationDeviceType type{};
498 VibrationDevicePosition position{};
499};
500static_assert(sizeof(VibrationDeviceInfo) == 0x8, "VibrationDeviceInfo has incorrect size.");
501
502// This is nn::hid::KeyboardModifier
503struct KeyboardModifier {
504 union {
505 u32 raw{};
506 BitField<0, 1, u32> control;
507 BitField<1, 1, u32> shift;
508 BitField<2, 1, u32> left_alt;
509 BitField<3, 1, u32> right_alt;
510 BitField<4, 1, u32> gui;
511 BitField<8, 1, u32> caps_lock;
512 BitField<9, 1, u32> scroll_lock;
513 BitField<10, 1, u32> num_lock;
514 BitField<11, 1, u32> katakana;
515 BitField<12, 1, u32> hiragana;
516 };
517};
518
519static_assert(sizeof(KeyboardModifier) == 0x4, "KeyboardModifier is an invalid size");
520
521// This is nn::hid::KeyboardAttribute
522struct KeyboardAttribute {
523 union {
524 u32 raw{};
525 BitField<0, 1, u32> is_connected;
526 };
527};
528static_assert(sizeof(KeyboardAttribute) == 0x4, "KeyboardAttribute is an invalid size");
529
530// This is nn::hid::KeyboardKey
531struct KeyboardKey {
532 // This should be a 256 bit flag
533 std::array<u8, 32> key;
534};
535static_assert(sizeof(KeyboardKey) == 0x20, "KeyboardKey is an invalid size");
536
537// This is nn::hid::MouseButton
538struct MouseButton {
539 union {
540 u32_le raw{};
541 BitField<0, 1, u32> left;
542 BitField<1, 1, u32> right;
543 BitField<2, 1, u32> middle;
544 BitField<3, 1, u32> forward;
545 BitField<4, 1, u32> back;
546 };
547};
548static_assert(sizeof(MouseButton) == 0x4, "MouseButton is an invalid size");
549
550// This is nn::hid::MouseAttribute
551struct MouseAttribute {
552 union {
553 u32 raw{};
554 BitField<0, 1, u32> transferable;
555 BitField<1, 1, u32> is_connected;
556 };
557};
558static_assert(sizeof(MouseAttribute) == 0x4, "MouseAttribute is an invalid size");
559
560// This is nn::hid::detail::MouseState
561struct MouseState {
562 s64 sampling_number;
563 s32 x;
564 s32 y;
565 s32 delta_x;
566 s32 delta_y;
567 // Axis Order in HW is switched for the wheel
568 s32 delta_wheel_y;
569 s32 delta_wheel_x;
570 MouseButton button;
571 MouseAttribute attribute;
572};
573static_assert(sizeof(MouseState) == 0x28, "MouseState is an invalid size");
574
575/// Converts a NpadIdType to an array index.
576constexpr size_t NpadIdTypeToIndex(NpadIdType npad_id_type) {
577 switch (npad_id_type) {
578 case NpadIdType::Player1:
579 return 0;
580 case NpadIdType::Player2:
581 return 1;
582 case NpadIdType::Player3:
583 return 2;
584 case NpadIdType::Player4:
585 return 3;
586 case NpadIdType::Player5:
587 return 4;
588 case NpadIdType::Player6:
589 return 5;
590 case NpadIdType::Player7:
591 return 6;
592 case NpadIdType::Player8:
593 return 7;
594 case NpadIdType::Handheld:
595 return 8;
596 case NpadIdType::Other:
597 return 9;
598 default:
599 return 0;
600 }
601}
602
603/// Converts an array index to a NpadIdType
604constexpr NpadIdType IndexToNpadIdType(size_t index) {
605 switch (index) {
606 case 0:
607 return NpadIdType::Player1;
608 case 1:
609 return NpadIdType::Player2;
610 case 2:
611 return NpadIdType::Player3;
612 case 3:
613 return NpadIdType::Player4;
614 case 4:
615 return NpadIdType::Player5;
616 case 5:
617 return NpadIdType::Player6;
618 case 6:
619 return NpadIdType::Player7;
620 case 7:
621 return NpadIdType::Player8;
622 case 8:
623 return NpadIdType::Handheld;
624 case 9:
625 return NpadIdType::Other;
626 default:
627 return NpadIdType::Invalid;
628 }
629}
630
631} // namespace Core::HID
diff --git a/src/core/hid/input_converter.cpp b/src/core/hid/input_converter.cpp
new file mode 100644
index 000000000..f5acff6e0
--- /dev/null
+++ b/src/core/hid/input_converter.cpp
@@ -0,0 +1,383 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included
4
5#include <random>
6
7#include "common/input.h"
8#include "core/hid/input_converter.h"
9
10namespace Core::HID {
11
12Common::Input::BatteryStatus TransformToBattery(const Common::Input::CallbackStatus& callback) {
13 Common::Input::BatteryStatus battery{Common::Input::BatteryStatus::None};
14 switch (callback.type) {
15 case Common::Input::InputType::Analog:
16 case Common::Input::InputType::Trigger: {
17 const auto value = TransformToTrigger(callback).analog.value;
18 battery = Common::Input::BatteryLevel::Empty;
19 if (value > 0.2f) {
20 battery = Common::Input::BatteryLevel::Critical;
21 }
22 if (value > 0.4f) {
23 battery = Common::Input::BatteryLevel::Low;
24 }
25 if (value > 0.6f) {
26 battery = Common::Input::BatteryLevel::Medium;
27 }
28 if (value > 0.8f) {
29 battery = Common::Input::BatteryLevel::Full;
30 }
31 if (value >= 1.0f) {
32 battery = Common::Input::BatteryLevel::Charging;
33 }
34 break;
35 }
36 case Common::Input::InputType::Button:
37 battery = callback.button_status.value ? Common::Input::BatteryLevel::Charging
38 : Common::Input::BatteryLevel::Critical;
39 break;
40 case Common::Input::InputType::Battery:
41 battery = callback.battery_status;
42 break;
43 default:
44 LOG_ERROR(Input, "Conversion from type {} to battery not implemented", callback.type);
45 break;
46 }
47
48 return battery;
49}
50
51Common::Input::ButtonStatus TransformToButton(const Common::Input::CallbackStatus& callback) {
52 Common::Input::ButtonStatus status{};
53 switch (callback.type) {
54 case Common::Input::InputType::Analog:
55 case Common::Input::InputType::Trigger:
56 status.value = TransformToTrigger(callback).pressed.value;
57 break;
58 case Common::Input::InputType::Button:
59 status = callback.button_status;
60 break;
61 default:
62 LOG_ERROR(Input, "Conversion from type {} to button not implemented", callback.type);
63 break;
64 }
65
66 if (status.inverted) {
67 status.value = !status.value;
68 }
69
70 return status;
71}
72
73Common::Input::MotionStatus TransformToMotion(const Common::Input::CallbackStatus& callback) {
74 Common::Input::MotionStatus status{};
75 switch (callback.type) {
76 case Common::Input::InputType::Button: {
77 Common::Input::AnalogProperties properties{
78 .deadzone = 0.0f,
79 .range = 1.0f,
80 .offset = 0.0f,
81 };
82 status.delta_timestamp = 5000;
83 status.force_update = true;
84 status.accel.x = {
85 .value = 0.0f,
86 .raw_value = 0.0f,
87 .properties = properties,
88 };
89 status.accel.y = {
90 .value = 0.0f,
91 .raw_value = 0.0f,
92 .properties = properties,
93 };
94 status.accel.z = {
95 .value = 0.0f,
96 .raw_value = -1.0f,
97 .properties = properties,
98 };
99 status.gyro.x = {
100 .value = 0.0f,
101 .raw_value = 0.0f,
102 .properties = properties,
103 };
104 status.gyro.y = {
105 .value = 0.0f,
106 .raw_value = 0.0f,
107 .properties = properties,
108 };
109 status.gyro.z = {
110 .value = 0.0f,
111 .raw_value = 0.0f,
112 .properties = properties,
113 };
114 if (TransformToButton(callback).value) {
115 std::random_device device;
116 std::mt19937 gen(device());
117 std::uniform_int_distribution<s16> distribution(-1000, 1000);
118 status.accel.x.raw_value = static_cast<f32>(distribution(gen)) * 0.001f;
119 status.accel.y.raw_value = static_cast<f32>(distribution(gen)) * 0.001f;
120 status.accel.z.raw_value = static_cast<f32>(distribution(gen)) * 0.001f;
121 status.gyro.x.raw_value = static_cast<f32>(distribution(gen)) * 0.001f;
122 status.gyro.y.raw_value = static_cast<f32>(distribution(gen)) * 0.001f;
123 status.gyro.z.raw_value = static_cast<f32>(distribution(gen)) * 0.001f;
124 }
125 break;
126 }
127 case Common::Input::InputType::Motion:
128 status = callback.motion_status;
129 break;
130 default:
131 LOG_ERROR(Input, "Conversion from type {} to motion not implemented", callback.type);
132 break;
133 }
134 SanitizeAnalog(status.accel.x, false);
135 SanitizeAnalog(status.accel.y, false);
136 SanitizeAnalog(status.accel.z, false);
137 SanitizeAnalog(status.gyro.x, false);
138 SanitizeAnalog(status.gyro.y, false);
139 SanitizeAnalog(status.gyro.z, false);
140
141 return status;
142}
143
144Common::Input::StickStatus TransformToStick(const Common::Input::CallbackStatus& callback) {
145 Common::Input::StickStatus status{};
146
147 switch (callback.type) {
148 case Common::Input::InputType::Stick:
149 status = callback.stick_status;
150 break;
151 default:
152 LOG_ERROR(Input, "Conversion from type {} to stick not implemented", callback.type);
153 break;
154 }
155
156 SanitizeStick(status.x, status.y, true);
157 const auto& properties_x = status.x.properties;
158 const auto& properties_y = status.y.properties;
159 const float x = status.x.value;
160 const float y = status.y.value;
161
162 // Set directional buttons
163 status.right = x > properties_x.threshold;
164 status.left = x < -properties_x.threshold;
165 status.up = y > properties_y.threshold;
166 status.down = y < -properties_y.threshold;
167
168 return status;
169}
170
171Common::Input::TouchStatus TransformToTouch(const Common::Input::CallbackStatus& callback) {
172 Common::Input::TouchStatus status{};
173
174 switch (callback.type) {
175 case Common::Input::InputType::Touch:
176 status = callback.touch_status;
177 break;
178 case Common::Input::InputType::Stick:
179 status.x = callback.stick_status.x;
180 status.y = callback.stick_status.y;
181 break;
182 default:
183 LOG_ERROR(Input, "Conversion from type {} to touch not implemented", callback.type);
184 break;
185 }
186
187 SanitizeAnalog(status.x, true);
188 SanitizeAnalog(status.y, true);
189 float& x = status.x.value;
190 float& y = status.y.value;
191
192 // Adjust if value is inverted
193 x = status.x.properties.inverted ? 1.0f + x : x;
194 y = status.y.properties.inverted ? 1.0f + y : y;
195
196 // clamp value
197 x = std::clamp(x, 0.0f, 1.0f);
198 y = std::clamp(y, 0.0f, 1.0f);
199
200 if (status.pressed.inverted) {
201 status.pressed.value = !status.pressed.value;
202 }
203
204 return status;
205}
206
207Common::Input::TriggerStatus TransformToTrigger(const Common::Input::CallbackStatus& callback) {
208 Common::Input::TriggerStatus status{};
209 float& raw_value = status.analog.raw_value;
210 bool calculate_button_value = true;
211
212 switch (callback.type) {
213 case Common::Input::InputType::Analog:
214 status.analog.properties = callback.analog_status.properties;
215 raw_value = callback.analog_status.raw_value;
216 break;
217 case Common::Input::InputType::Button:
218 status.analog.properties.range = 1.0f;
219 status.analog.properties.inverted = callback.button_status.inverted;
220 raw_value = callback.button_status.value ? 1.0f : 0.0f;
221 break;
222 case Common::Input::InputType::Trigger:
223 status = callback.trigger_status;
224 calculate_button_value = false;
225 break;
226 default:
227 LOG_ERROR(Input, "Conversion from type {} to trigger not implemented", callback.type);
228 break;
229 }
230
231 SanitizeAnalog(status.analog, true);
232 const auto& properties = status.analog.properties;
233 float& value = status.analog.value;
234
235 // Set button status
236 if (calculate_button_value) {
237 status.pressed.value = value > properties.threshold;
238 }
239
240 // Adjust if value is inverted
241 value = properties.inverted ? 1.0f + value : value;
242
243 // clamp value
244 value = std::clamp(value, 0.0f, 1.0f);
245
246 return status;
247}
248
249Common::Input::AnalogStatus TransformToAnalog(const Common::Input::CallbackStatus& callback) {
250 Common::Input::AnalogStatus status{};
251
252 switch (callback.type) {
253 case Common::Input::InputType::Analog:
254 status.properties = callback.analog_status.properties;
255 status.raw_value = callback.analog_status.raw_value;
256 break;
257 default:
258 LOG_ERROR(Input, "Conversion from type {} to analog not implemented", callback.type);
259 break;
260 }
261
262 SanitizeAnalog(status, false);
263
264 // Adjust if value is inverted
265 status.value = status.properties.inverted ? -status.value : status.value;
266
267 return status;
268}
269
270void SanitizeAnalog(Common::Input::AnalogStatus& analog, bool clamp_value) {
271 const auto& properties = analog.properties;
272 float& raw_value = analog.raw_value;
273 float& value = analog.value;
274
275 if (!std::isnormal(raw_value)) {
276 raw_value = 0;
277 }
278
279 // Apply center offset
280 raw_value -= properties.offset;
281
282 // Set initial values to be formated
283 value = raw_value;
284
285 // Calculate vector size
286 const float r = std::abs(value);
287
288 // Return zero if value is smaller than the deadzone
289 if (r <= properties.deadzone || properties.deadzone == 1.0f) {
290 analog.value = 0;
291 return;
292 }
293
294 // Adjust range of value
295 const float deadzone_factor =
296 1.0f / r * (r - properties.deadzone) / (1.0f - properties.deadzone);
297 value = value * deadzone_factor / properties.range;
298
299 // Invert direction if needed
300 if (properties.inverted) {
301 value = -value;
302 }
303
304 // Clamp value
305 if (clamp_value) {
306 value = std::clamp(value, -1.0f, 1.0f);
307 }
308}
309
310void SanitizeStick(Common::Input::AnalogStatus& analog_x, Common::Input::AnalogStatus& analog_y,
311 bool clamp_value) {
312 const auto& properties_x = analog_x.properties;
313 const auto& properties_y = analog_y.properties;
314 float& raw_x = analog_x.raw_value;
315 float& raw_y = analog_y.raw_value;
316 float& x = analog_x.value;
317 float& y = analog_y.value;
318
319 if (!std::isnormal(raw_x)) {
320 raw_x = 0;
321 }
322 if (!std::isnormal(raw_y)) {
323 raw_y = 0;
324 }
325
326 // Apply center offset
327 raw_x += properties_x.offset;
328 raw_y += properties_y.offset;
329
330 // Apply X scale correction from offset
331 if (std::abs(properties_x.offset) < 0.5f) {
332 if (raw_x > 0) {
333 raw_x /= 1 + properties_x.offset;
334 } else {
335 raw_x /= 1 - properties_x.offset;
336 }
337 }
338
339 // Apply Y scale correction from offset
340 if (std::abs(properties_y.offset) < 0.5f) {
341 if (raw_y > 0) {
342 raw_y /= 1 + properties_y.offset;
343 } else {
344 raw_y /= 1 - properties_y.offset;
345 }
346 }
347
348 // Invert direction if needed
349 raw_x = properties_x.inverted ? -raw_x : raw_x;
350 raw_y = properties_y.inverted ? -raw_y : raw_y;
351
352 // Set initial values to be formated
353 x = raw_x;
354 y = raw_y;
355
356 // Calculate vector size
357 float r = x * x + y * y;
358 r = std::sqrt(r);
359
360 // TODO(German77): Use deadzone and range of both axis
361
362 // Return zero if values are smaller than the deadzone
363 if (r <= properties_x.deadzone || properties_x.deadzone >= 1.0f) {
364 x = 0;
365 y = 0;
366 return;
367 }
368
369 // Adjust range of joystick
370 const float deadzone_factor =
371 1.0f / r * (r - properties_x.deadzone) / (1.0f - properties_x.deadzone);
372 x = x * deadzone_factor / properties_x.range;
373 y = y * deadzone_factor / properties_x.range;
374 r = r * deadzone_factor / properties_x.range;
375
376 // Normalize joystick
377 if (clamp_value && r > 1.0f) {
378 x /= r;
379 y /= r;
380 }
381}
382
383} // namespace Core::HID
diff --git a/src/core/hid/input_converter.h b/src/core/hid/input_converter.h
new file mode 100644
index 000000000..1492489d7
--- /dev/null
+++ b/src/core/hid/input_converter.h
@@ -0,0 +1,95 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included
4
5#pragma once
6
7namespace Common::Input {
8struct CallbackStatus;
9enum class BatteryLevel : u32;
10using BatteryStatus = BatteryLevel;
11struct AnalogStatus;
12struct ButtonStatus;
13struct MotionStatus;
14struct StickStatus;
15struct TouchStatus;
16struct TriggerStatus;
17}; // namespace Common::Input
18
19namespace Core::HID {
20
21/**
22 * Converts raw input data into a valid battery status.
23 *
24 * @param Supported callbacks: Analog, Battery, Trigger.
25 * @return A valid BatteryStatus object.
26 */
27Common::Input::BatteryStatus TransformToBattery(const Common::Input::CallbackStatus& callback);
28
29/**
30 * Converts raw input data into a valid button status. Applies invert properties to the output.
31 *
32 * @param Supported callbacks: Analog, Button, Trigger.
33 * @return A valid TouchStatus object.
34 */
35Common::Input::ButtonStatus TransformToButton(const Common::Input::CallbackStatus& callback);
36
37/**
38 * Converts raw input data into a valid motion status.
39 *
40 * @param Supported callbacks: Motion.
41 * @return A valid TouchStatus object.
42 */
43Common::Input::MotionStatus TransformToMotion(const Common::Input::CallbackStatus& callback);
44
45/**
46 * Converts raw input data into a valid stick status. Applies offset, deadzone, range and invert
47 * properties to the output.
48 *
49 * @param Supported callbacks: Stick.
50 * @return A valid StickStatus object.
51 */
52Common::Input::StickStatus TransformToStick(const Common::Input::CallbackStatus& callback);
53
54/**
55 * Converts raw input data into a valid touch status.
56 *
57 * @param Supported callbacks: Touch.
58 * @return A valid TouchStatus object.
59 */
60Common::Input::TouchStatus TransformToTouch(const Common::Input::CallbackStatus& callback);
61
62/**
63 * Converts raw input data into a valid trigger status. Applies offset, deadzone, range and
64 * invert properties to the output. Button status uses the threshold property if necessary.
65 *
66 * @param Supported callbacks: Analog, Button, Trigger.
67 * @return A valid TriggerStatus object.
68 */
69Common::Input::TriggerStatus TransformToTrigger(const Common::Input::CallbackStatus& callback);
70
71/**
72 * Converts raw input data into a valid analog status. Applies offset, deadzone, range and
73 * invert properties to the output.
74 *
75 * @param Supported callbacks: Analog.
76 * @return A valid AnalogStatus object.
77 */
78Common::Input::AnalogStatus TransformToAnalog(const Common::Input::CallbackStatus& callback);
79
80/**
81 * Converts raw analog data into a valid analog value
82 * @param An analog object containing raw data and properties, bool that determines if the value
83 * needs to be clamped between -1.0f and 1.0f.
84 */
85void SanitizeAnalog(Common::Input::AnalogStatus& analog, bool clamp_value);
86
87/**
88 * Converts raw stick data into a valid stick value
89 * @param Two analog objects containing raw data and properties, bool that determines if the value
90 * needs to be clamped into the unit circle.
91 */
92void SanitizeStick(Common::Input::AnalogStatus& analog_x, Common::Input::AnalogStatus& analog_y,
93 bool clamp_value);
94
95} // namespace Core::HID
diff --git a/src/core/frontend/input_interpreter.cpp b/src/core/hid/input_interpreter.cpp
index 9f6a90e8f..870422d82 100644
--- a/src/core/frontend/input_interpreter.cpp
+++ b/src/core/hid/input_interpreter.cpp
@@ -3,7 +3,8 @@
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include "core/core.h" 5#include "core/core.h"
6#include "core/frontend/input_interpreter.h" 6#include "core/hid/hid_types.h"
7#include "core/hid/input_interpreter.h"
7#include "core/hle/service/hid/controllers/npad.h" 8#include "core/hle/service/hid/controllers/npad.h"
8#include "core/hle/service/hid/hid.h" 9#include "core/hle/service/hid/hid.h"
9#include "core/hle/service/sm/sm.h" 10#include "core/hle/service/sm/sm.h"
@@ -19,7 +20,7 @@ InputInterpreter::InputInterpreter(Core::System& system)
19InputInterpreter::~InputInterpreter() = default; 20InputInterpreter::~InputInterpreter() = default;
20 21
21void InputInterpreter::PollInput() { 22void InputInterpreter::PollInput() {
22 const u32 button_state = npad.GetAndResetPressState(); 23 const u64 button_state = npad.GetAndResetPressState();
23 24
24 previous_index = current_index; 25 previous_index = current_index;
25 current_index = (current_index + 1) % button_states.size(); 26 current_index = (current_index + 1) % button_states.size();
@@ -31,32 +32,30 @@ void InputInterpreter::ResetButtonStates() {
31 previous_index = 0; 32 previous_index = 0;
32 current_index = 0; 33 current_index = 0;
33 34
34 button_states[0] = 0xFFFFFFFF; 35 button_states[0] = 0xFFFFFFFFFFFFFFFF;
35 36
36 for (std::size_t i = 1; i < button_states.size(); ++i) { 37 for (std::size_t i = 1; i < button_states.size(); ++i) {
37 button_states[i] = 0; 38 button_states[i] = 0;
38 } 39 }
39} 40}
40 41
41bool InputInterpreter::IsButtonPressed(HIDButton button) const { 42bool InputInterpreter::IsButtonPressed(Core::HID::NpadButton button) const {
42 return (button_states[current_index] & (1U << static_cast<u8>(button))) != 0; 43 return (button_states[current_index] & static_cast<u64>(button)) != 0;
43} 44}
44 45
45bool InputInterpreter::IsButtonPressedOnce(HIDButton button) const { 46bool InputInterpreter::IsButtonPressedOnce(Core::HID::NpadButton button) const {
46 const bool current_press = 47 const bool current_press = (button_states[current_index] & static_cast<u64>(button)) != 0;
47 (button_states[current_index] & (1U << static_cast<u8>(button))) != 0; 48 const bool previous_press = (button_states[previous_index] & static_cast<u64>(button)) != 0;
48 const bool previous_press =
49 (button_states[previous_index] & (1U << static_cast<u8>(button))) != 0;
50 49
51 return current_press && !previous_press; 50 return current_press && !previous_press;
52} 51}
53 52
54bool InputInterpreter::IsButtonHeld(HIDButton button) const { 53bool InputInterpreter::IsButtonHeld(Core::HID::NpadButton button) const {
55 u32 held_buttons{button_states[0]}; 54 u64 held_buttons{button_states[0]};
56 55
57 for (std::size_t i = 1; i < button_states.size(); ++i) { 56 for (std::size_t i = 1; i < button_states.size(); ++i) {
58 held_buttons &= button_states[i]; 57 held_buttons &= button_states[i];
59 } 58 }
60 59
61 return (held_buttons & (1U << static_cast<u8>(button))) != 0; 60 return (held_buttons & static_cast<u64>(button)) != 0;
62} 61}
diff --git a/src/core/frontend/input_interpreter.h b/src/core/hid/input_interpreter.h
index 9495e3daf..1c2e02142 100644
--- a/src/core/frontend/input_interpreter.h
+++ b/src/core/hid/input_interpreter.h
@@ -12,46 +12,14 @@ namespace Core {
12class System; 12class System;
13} 13}
14 14
15namespace Core::HID {
16enum class NpadButton : u64;
17}
18
15namespace Service::HID { 19namespace Service::HID {
16class Controller_NPad; 20class Controller_NPad;
17} 21}
18 22
19enum class HIDButton : u8 {
20 A,
21 B,
22 X,
23 Y,
24 LStick,
25 RStick,
26 L,
27 R,
28 ZL,
29 ZR,
30 Plus,
31 Minus,
32
33 DLeft,
34 DUp,
35 DRight,
36 DDown,
37
38 LStickLeft,
39 LStickUp,
40 LStickRight,
41 LStickDown,
42
43 RStickLeft,
44 RStickUp,
45 RStickRight,
46 RStickDown,
47
48 LeftSL,
49 LeftSR,
50
51 RightSL,
52 RightSR,
53};
54
55/** 23/**
56 * The InputInterpreter class interfaces with HID to retrieve button press states. 24 * The InputInterpreter class interfaces with HID to retrieve button press states.
57 * Input is intended to be polled every 50ms so that a button is considered to be 25 * Input is intended to be polled every 50ms so that a button is considered to be
@@ -76,7 +44,7 @@ public:
76 * 44 *
77 * @returns True when the button is pressed. 45 * @returns True when the button is pressed.
78 */ 46 */
79 [[nodiscard]] bool IsButtonPressed(HIDButton button) const; 47 [[nodiscard]] bool IsButtonPressed(Core::HID::NpadButton button) const;
80 48
81 /** 49 /**
82 * Checks whether any of the buttons in the parameter list is pressed. 50 * Checks whether any of the buttons in the parameter list is pressed.
@@ -85,7 +53,7 @@ public:
85 * 53 *
86 * @returns True when at least one of the buttons is pressed. 54 * @returns True when at least one of the buttons is pressed.
87 */ 55 */
88 template <HIDButton... T> 56 template <Core::HID::NpadButton... T>
89 [[nodiscard]] bool IsAnyButtonPressed() { 57 [[nodiscard]] bool IsAnyButtonPressed() {
90 return (IsButtonPressed(T) || ...); 58 return (IsButtonPressed(T) || ...);
91 } 59 }
@@ -98,7 +66,7 @@ public:
98 * 66 *
99 * @returns True when the button is pressed once. 67 * @returns True when the button is pressed once.
100 */ 68 */
101 [[nodiscard]] bool IsButtonPressedOnce(HIDButton button) const; 69 [[nodiscard]] bool IsButtonPressedOnce(Core::HID::NpadButton button) const;
102 70
103 /** 71 /**
104 * Checks whether any of the buttons in the parameter list is pressed once. 72 * Checks whether any of the buttons in the parameter list is pressed once.
@@ -107,7 +75,7 @@ public:
107 * 75 *
108 * @returns True when at least one of the buttons is pressed once. 76 * @returns True when at least one of the buttons is pressed once.
109 */ 77 */
110 template <HIDButton... T> 78 template <Core::HID::NpadButton... T>
111 [[nodiscard]] bool IsAnyButtonPressedOnce() const { 79 [[nodiscard]] bool IsAnyButtonPressedOnce() const {
112 return (IsButtonPressedOnce(T) || ...); 80 return (IsButtonPressedOnce(T) || ...);
113 } 81 }
@@ -119,7 +87,7 @@ public:
119 * 87 *
120 * @returns True when the button is held down. 88 * @returns True when the button is held down.
121 */ 89 */
122 [[nodiscard]] bool IsButtonHeld(HIDButton button) const; 90 [[nodiscard]] bool IsButtonHeld(Core::HID::NpadButton button) const;
123 91
124 /** 92 /**
125 * Checks whether any of the buttons in the parameter list is held down. 93 * Checks whether any of the buttons in the parameter list is held down.
@@ -128,7 +96,7 @@ public:
128 * 96 *
129 * @returns True when at least one of the buttons is held down. 97 * @returns True when at least one of the buttons is held down.
130 */ 98 */
131 template <HIDButton... T> 99 template <Core::HID::NpadButton... T>
132 [[nodiscard]] bool IsAnyButtonHeld() const { 100 [[nodiscard]] bool IsAnyButtonHeld() const {
133 return (IsButtonHeld(T) || ...); 101 return (IsButtonHeld(T) || ...);
134 } 102 }
@@ -137,7 +105,7 @@ private:
137 Service::HID::Controller_NPad& npad; 105 Service::HID::Controller_NPad& npad;
138 106
139 /// Stores 9 consecutive button states polled from HID. 107 /// Stores 9 consecutive button states polled from HID.
140 std::array<u32, 9> button_states{}; 108 std::array<u64, 9> button_states{};
141 109
142 std::size_t previous_index{}; 110 std::size_t previous_index{};
143 std::size_t current_index{}; 111 std::size_t current_index{};
diff --git a/src/core/hid/motion_input.cpp b/src/core/hid/motion_input.cpp
new file mode 100644
index 000000000..c25fea966
--- /dev/null
+++ b/src/core/hid/motion_input.cpp
@@ -0,0 +1,280 @@
1// Copyright 2020 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included
4
5#include "common/math_util.h"
6#include "core/hid/motion_input.h"
7
8namespace Core::HID {
9
10MotionInput::MotionInput() {
11 // Initialize PID constants with default values
12 SetPID(0.3f, 0.005f, 0.0f);
13}
14
15void MotionInput::SetPID(f32 new_kp, f32 new_ki, f32 new_kd) {
16 kp = new_kp;
17 ki = new_ki;
18 kd = new_kd;
19}
20
21void MotionInput::SetAcceleration(const Common::Vec3f& acceleration) {
22 accel = acceleration;
23}
24
25void MotionInput::SetGyroscope(const Common::Vec3f& gyroscope) {
26 gyro = gyroscope - gyro_drift;
27
28 // Auto adjust drift to minimize drift
29 if (!IsMoving(0.1f)) {
30 gyro_drift = (gyro_drift * 0.9999f) + (gyroscope * 0.0001f);
31 }
32
33 if (gyro.Length2() < gyro_threshold) {
34 gyro = {};
35 } else {
36 only_accelerometer = false;
37 }
38}
39
40void MotionInput::SetQuaternion(const Common::Quaternion<f32>& quaternion) {
41 quat = quaternion;
42}
43
44void MotionInput::SetGyroDrift(const Common::Vec3f& drift) {
45 gyro_drift = drift;
46}
47
48void MotionInput::SetGyroThreshold(f32 threshold) {
49 gyro_threshold = threshold;
50}
51
52void MotionInput::EnableReset(bool reset) {
53 reset_enabled = reset;
54}
55
56void MotionInput::ResetRotations() {
57 rotations = {};
58}
59
60bool MotionInput::IsMoving(f32 sensitivity) const {
61 return gyro.Length() >= sensitivity || accel.Length() <= 0.9f || accel.Length() >= 1.1f;
62}
63
64bool MotionInput::IsCalibrated(f32 sensitivity) const {
65 return real_error.Length() < sensitivity;
66}
67
68void MotionInput::UpdateRotation(u64 elapsed_time) {
69 const auto sample_period = static_cast<f32>(elapsed_time) / 1000000.0f;
70 if (sample_period > 0.1f) {
71 return;
72 }
73 rotations += gyro * sample_period;
74}
75
76// Based on Madgwick's implementation of Mayhony's AHRS algorithm.
77// https://github.com/xioTechnologies/Open-Source-AHRS-With-x-IMU/blob/master/x-IMU%20IMU%20and%20AHRS%20Algorithms/x-IMU%20IMU%20and%20AHRS%20Algorithms/AHRS/MahonyAHRS.cs
78void MotionInput::UpdateOrientation(u64 elapsed_time) {
79 if (!IsCalibrated(0.1f)) {
80 ResetOrientation();
81 }
82 // Short name local variable for readability
83 f32 q1 = quat.w;
84 f32 q2 = quat.xyz[0];
85 f32 q3 = quat.xyz[1];
86 f32 q4 = quat.xyz[2];
87 const auto sample_period = static_cast<f32>(elapsed_time) / 1000000.0f;
88
89 // Ignore invalid elapsed time
90 if (sample_period > 0.1f) {
91 return;
92 }
93
94 const auto normal_accel = accel.Normalized();
95 auto rad_gyro = gyro * Common::PI * 2;
96 const f32 swap = rad_gyro.x;
97 rad_gyro.x = rad_gyro.y;
98 rad_gyro.y = -swap;
99 rad_gyro.z = -rad_gyro.z;
100
101 // Clear gyro values if there is no gyro present
102 if (only_accelerometer) {
103 rad_gyro.x = 0;
104 rad_gyro.y = 0;
105 rad_gyro.z = 0;
106 }
107
108 // Ignore drift correction if acceleration is not reliable
109 if (accel.Length() >= 0.75f && accel.Length() <= 1.25f) {
110 const f32 ax = -normal_accel.x;
111 const f32 ay = normal_accel.y;
112 const f32 az = -normal_accel.z;
113
114 // Estimated direction of gravity
115 const f32 vx = 2.0f * (q2 * q4 - q1 * q3);
116 const f32 vy = 2.0f * (q1 * q2 + q3 * q4);
117 const f32 vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4;
118
119 // Error is cross product between estimated direction and measured direction of gravity
120 const Common::Vec3f new_real_error = {
121 az * vx - ax * vz,
122 ay * vz - az * vy,
123 ax * vy - ay * vx,
124 };
125
126 derivative_error = new_real_error - real_error;
127 real_error = new_real_error;
128
129 // Prevent integral windup
130 if (ki != 0.0f && !IsCalibrated(0.05f)) {
131 integral_error += real_error;
132 } else {
133 integral_error = {};
134 }
135
136 // Apply feedback terms
137 if (!only_accelerometer) {
138 rad_gyro += kp * real_error;
139 rad_gyro += ki * integral_error;
140 rad_gyro += kd * derivative_error;
141 } else {
142 // Give more weight to accelerometer values to compensate for the lack of gyro
143 rad_gyro += 35.0f * kp * real_error;
144 rad_gyro += 10.0f * ki * integral_error;
145 rad_gyro += 10.0f * kd * derivative_error;
146
147 // Emulate gyro values for games that need them
148 gyro.x = -rad_gyro.y;
149 gyro.y = rad_gyro.x;
150 gyro.z = -rad_gyro.z;
151 UpdateRotation(elapsed_time);
152 }
153 }
154
155 const f32 gx = rad_gyro.y;
156 const f32 gy = rad_gyro.x;
157 const f32 gz = rad_gyro.z;
158
159 // Integrate rate of change of quaternion
160 const f32 pa = q2;
161 const f32 pb = q3;
162 const f32 pc = q4;
163 q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * sample_period);
164 q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * sample_period);
165 q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * sample_period);
166 q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * sample_period);
167
168 quat.w = q1;
169 quat.xyz[0] = q2;
170 quat.xyz[1] = q3;
171 quat.xyz[2] = q4;
172 quat = quat.Normalized();
173}
174
175std::array<Common::Vec3f, 3> MotionInput::GetOrientation() const {
176 const Common::Quaternion<float> quad{
177 .xyz = {-quat.xyz[1], -quat.xyz[0], -quat.w},
178 .w = -quat.xyz[2],
179 };
180 const std::array<float, 16> matrix4x4 = quad.ToMatrix();
181
182 return {Common::Vec3f(matrix4x4[0], matrix4x4[1], -matrix4x4[2]),
183 Common::Vec3f(matrix4x4[4], matrix4x4[5], -matrix4x4[6]),
184 Common::Vec3f(-matrix4x4[8], -matrix4x4[9], matrix4x4[10])};
185}
186
187Common::Vec3f MotionInput::GetAcceleration() const {
188 return accel;
189}
190
191Common::Vec3f MotionInput::GetGyroscope() const {
192 return gyro;
193}
194
195Common::Quaternion<f32> MotionInput::GetQuaternion() const {
196 return quat;
197}
198
199Common::Vec3f MotionInput::GetRotations() const {
200 return rotations;
201}
202
203void MotionInput::ResetOrientation() {
204 if (!reset_enabled || only_accelerometer) {
205 return;
206 }
207 if (!IsMoving(0.5f) && accel.z <= -0.9f) {
208 ++reset_counter;
209 if (reset_counter > 900) {
210 quat.w = 0;
211 quat.xyz[0] = 0;
212 quat.xyz[1] = 0;
213 quat.xyz[2] = -1;
214 SetOrientationFromAccelerometer();
215 integral_error = {};
216 reset_counter = 0;
217 }
218 } else {
219 reset_counter = 0;
220 }
221}
222
223void MotionInput::SetOrientationFromAccelerometer() {
224 int iterations = 0;
225 const f32 sample_period = 0.015f;
226
227 const auto normal_accel = accel.Normalized();
228
229 while (!IsCalibrated(0.01f) && ++iterations < 100) {
230 // Short name local variable for readability
231 f32 q1 = quat.w;
232 f32 q2 = quat.xyz[0];
233 f32 q3 = quat.xyz[1];
234 f32 q4 = quat.xyz[2];
235
236 Common::Vec3f rad_gyro;
237 const f32 ax = -normal_accel.x;
238 const f32 ay = normal_accel.y;
239 const f32 az = -normal_accel.z;
240
241 // Estimated direction of gravity
242 const f32 vx = 2.0f * (q2 * q4 - q1 * q3);
243 const f32 vy = 2.0f * (q1 * q2 + q3 * q4);
244 const f32 vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4;
245
246 // Error is cross product between estimated direction and measured direction of gravity
247 const Common::Vec3f new_real_error = {
248 az * vx - ax * vz,
249 ay * vz - az * vy,
250 ax * vy - ay * vx,
251 };
252
253 derivative_error = new_real_error - real_error;
254 real_error = new_real_error;
255
256 rad_gyro += 10.0f * kp * real_error;
257 rad_gyro += 5.0f * ki * integral_error;
258 rad_gyro += 10.0f * kd * derivative_error;
259
260 const f32 gx = rad_gyro.y;
261 const f32 gy = rad_gyro.x;
262 const f32 gz = rad_gyro.z;
263
264 // Integrate rate of change of quaternion
265 const f32 pa = q2;
266 const f32 pb = q3;
267 const f32 pc = q4;
268 q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * sample_period);
269 q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * sample_period);
270 q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * sample_period);
271 q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * sample_period);
272
273 quat.w = q1;
274 quat.xyz[0] = q2;
275 quat.xyz[1] = q3;
276 quat.xyz[2] = q4;
277 quat = quat.Normalized();
278 }
279}
280} // namespace Core::HID
diff --git a/src/core/hid/motion_input.h b/src/core/hid/motion_input.h
new file mode 100644
index 000000000..5b5b420bb
--- /dev/null
+++ b/src/core/hid/motion_input.h
@@ -0,0 +1,87 @@
1// Copyright 2020 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included
4
5#pragma once
6
7#include "common/common_types.h"
8#include "common/quaternion.h"
9#include "common/vector_math.h"
10
11namespace Core::HID {
12
13class MotionInput {
14public:
15 explicit MotionInput();
16
17 MotionInput(const MotionInput&) = default;
18 MotionInput& operator=(const MotionInput&) = default;
19
20 MotionInput(MotionInput&&) = default;
21 MotionInput& operator=(MotionInput&&) = default;
22
23 void SetPID(f32 new_kp, f32 new_ki, f32 new_kd);
24 void SetAcceleration(const Common::Vec3f& acceleration);
25 void SetGyroscope(const Common::Vec3f& gyroscope);
26 void SetQuaternion(const Common::Quaternion<f32>& quaternion);
27 void SetGyroDrift(const Common::Vec3f& drift);
28 void SetGyroThreshold(f32 threshold);
29
30 void EnableReset(bool reset);
31 void ResetRotations();
32
33 void UpdateRotation(u64 elapsed_time);
34 void UpdateOrientation(u64 elapsed_time);
35
36 [[nodiscard]] std::array<Common::Vec3f, 3> GetOrientation() const;
37 [[nodiscard]] Common::Vec3f GetAcceleration() const;
38 [[nodiscard]] Common::Vec3f GetGyroscope() const;
39 [[nodiscard]] Common::Vec3f GetRotations() const;
40 [[nodiscard]] Common::Quaternion<f32> GetQuaternion() const;
41
42 [[nodiscard]] bool IsMoving(f32 sensitivity) const;
43 [[nodiscard]] bool IsCalibrated(f32 sensitivity) const;
44
45private:
46 void ResetOrientation();
47 void SetOrientationFromAccelerometer();
48
49 // PID constants
50 f32 kp;
51 f32 ki;
52 f32 kd;
53
54 // PID errors
55 Common::Vec3f real_error;
56 Common::Vec3f integral_error;
57 Common::Vec3f derivative_error;
58
59 // Quaternion containing the device orientation
60 Common::Quaternion<f32> quat{{0.0f, 0.0f, -1.0f}, 0.0f};
61
62 // Number of full rotations in each axis
63 Common::Vec3f rotations;
64
65 // Acceleration vector measurement in G force
66 Common::Vec3f accel;
67
68 // Gyroscope vector measurement in radians/s.
69 Common::Vec3f gyro;
70
71 // Vector to be substracted from gyro measurements
72 Common::Vec3f gyro_drift;
73
74 // Minimum gyro amplitude to detect if the device is moving
75 f32 gyro_threshold = 0.0f;
76
77 // Number of invalid sequential data
78 u32 reset_counter = 0;
79
80 // If the provided data is invalid the device will be autocalibrated
81 bool reset_enabled = true;
82
83 // Use accelerometer values to calculate position
84 bool only_accelerometer = true;
85};
86
87} // namespace Core::HID
diff --git a/src/core/hle/service/am/applets/applet_controller.cpp b/src/core/hle/service/am/applets/applet_controller.cpp
index 2721679c1..d073f2210 100644
--- a/src/core/hle/service/am/applets/applet_controller.cpp
+++ b/src/core/hle/service/am/applets/applet_controller.cpp
@@ -10,6 +10,9 @@
10#include "common/string_util.h" 10#include "common/string_util.h"
11#include "core/core.h" 11#include "core/core.h"
12#include "core/frontend/applets/controller.h" 12#include "core/frontend/applets/controller.h"
13#include "core/hid/emulated_controller.h"
14#include "core/hid/hid_core.h"
15#include "core/hid/hid_types.h"
13#include "core/hle/result.h" 16#include "core/hle/result.h"
14#include "core/hle/service/am/am.h" 17#include "core/hle/service/am/am.h"
15#include "core/hle/service/am/applets/applet_controller.h" 18#include "core/hle/service/am/applets/applet_controller.h"
@@ -25,7 +28,7 @@ namespace Service::AM::Applets {
25static Core::Frontend::ControllerParameters ConvertToFrontendParameters( 28static Core::Frontend::ControllerParameters ConvertToFrontendParameters(
26 ControllerSupportArgPrivate private_arg, ControllerSupportArgHeader header, bool enable_text, 29 ControllerSupportArgPrivate private_arg, ControllerSupportArgHeader header, bool enable_text,
27 std::vector<IdentificationColor> identification_colors, std::vector<ExplainText> text) { 30 std::vector<IdentificationColor> identification_colors, std::vector<ExplainText> text) {
28 HID::Controller_NPad::NpadStyleSet npad_style_set; 31 Core::HID::NpadStyleTag npad_style_set;
29 npad_style_set.raw = private_arg.style_set; 32 npad_style_set.raw = private_arg.style_set;
30 33
31 return { 34 return {
@@ -243,19 +246,11 @@ void Controller::Execute() {
243void Controller::ConfigurationComplete() { 246void Controller::ConfigurationComplete() {
244 ControllerSupportResultInfo result_info{}; 247 ControllerSupportResultInfo result_info{};
245 248
246 const auto& players = Settings::values.players.GetValue();
247
248 // If enable_single_mode is enabled, player_count is 1 regardless of any other parameters. 249 // If enable_single_mode is enabled, player_count is 1 regardless of any other parameters.
249 // Otherwise, only count connected players from P1-P8. 250 // Otherwise, only count connected players from P1-P8.
250 result_info.player_count = 251 result_info.player_count = is_single_mode ? 1 : system.HIDCore().GetPlayerCount();
251 is_single_mode 252
252 ? 1 253 result_info.selected_id = static_cast<u32>(system.HIDCore().GetFirstNpadId());
253 : static_cast<s8>(std::count_if(players.begin(), players.end() - 2,
254 [](const auto& player) { return player.connected; }));
255
256 result_info.selected_id = HID::Controller_NPad::IndexToNPad(std::distance(
257 players.begin(), std::find_if(players.begin(), players.end(),
258 [](const auto& player) { return player.connected; })));
259 254
260 result_info.result = 0; 255 result_info.result = 0;
261 256
diff --git a/src/core/hle/service/am/applets/applet_controller.h b/src/core/hle/service/am/applets/applet_controller.h
index 0a34c4fc0..1a832505e 100644
--- a/src/core/hle/service/am/applets/applet_controller.h
+++ b/src/core/hle/service/am/applets/applet_controller.h
@@ -16,6 +16,10 @@ namespace Core {
16class System; 16class System;
17} 17}
18 18
19namespace Core::HID {
20enum class NpadStyleSet : u32;
21}
22
19namespace Service::AM::Applets { 23namespace Service::AM::Applets {
20 24
21using IdentificationColor = std::array<u8, 4>; 25using IdentificationColor = std::array<u8, 4>;
@@ -52,7 +56,7 @@ struct ControllerSupportArgPrivate {
52 bool flag_1{}; 56 bool flag_1{};
53 ControllerSupportMode mode{}; 57 ControllerSupportMode mode{};
54 ControllerSupportCaller caller{}; 58 ControllerSupportCaller caller{};
55 u32 style_set{}; 59 Core::HID::NpadStyleSet style_set{};
56 u32 joy_hold_type{}; 60 u32 joy_hold_type{};
57}; 61};
58static_assert(sizeof(ControllerSupportArgPrivate) == 0x14, 62static_assert(sizeof(ControllerSupportArgPrivate) == 0x14,
diff --git a/src/core/hle/service/am/applets/applets.cpp b/src/core/hle/service/am/applets/applets.cpp
index 7320b1c0f..134ac1ee2 100644
--- a/src/core/hle/service/am/applets/applets.cpp
+++ b/src/core/hle/service/am/applets/applets.cpp
@@ -231,7 +231,7 @@ void AppletManager::SetDefaultAppletFrontendSet() {
231void AppletManager::SetDefaultAppletsIfMissing() { 231void AppletManager::SetDefaultAppletsIfMissing() {
232 if (frontend.controller == nullptr) { 232 if (frontend.controller == nullptr) {
233 frontend.controller = 233 frontend.controller =
234 std::make_unique<Core::Frontend::DefaultControllerApplet>(system.ServiceManager()); 234 std::make_unique<Core::Frontend::DefaultControllerApplet>(system.HIDCore());
235 } 235 }
236 236
237 if (frontend.error == nullptr) { 237 if (frontend.error == nullptr) {
diff --git a/src/core/hle/service/hid/controllers/console_sixaxis.cpp b/src/core/hle/service/hid/controllers/console_sixaxis.cpp
index bda6e2557..f0f3105dc 100644
--- a/src/core/hle/service/hid/controllers/console_sixaxis.cpp
+++ b/src/core/hle/service/hid/controllers/console_sixaxis.cpp
@@ -4,13 +4,18 @@
4 4
5#include "common/settings.h" 5#include "common/settings.h"
6#include "core/core_timing.h" 6#include "core/core_timing.h"
7#include "core/hid/emulated_console.h"
8#include "core/hid/hid_core.h"
7#include "core/hle/service/hid/controllers/console_sixaxis.h" 9#include "core/hle/service/hid/controllers/console_sixaxis.h"
8 10
9namespace Service::HID { 11namespace Service::HID {
10constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3C200; 12constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3C200;
11 13
12Controller_ConsoleSixAxis::Controller_ConsoleSixAxis(Core::System& system_) 14Controller_ConsoleSixAxis::Controller_ConsoleSixAxis(Core::HID::HIDCore& hid_core_)
13 : ControllerBase{system_} {} 15 : ControllerBase{hid_core_} {
16 console = hid_core.GetEmulatedConsole();
17}
18
14Controller_ConsoleSixAxis::~Controller_ConsoleSixAxis() = default; 19Controller_ConsoleSixAxis::~Controller_ConsoleSixAxis() = default;
15 20
16void Controller_ConsoleSixAxis::OnInit() {} 21void Controller_ConsoleSixAxis::OnInit() {}
@@ -19,44 +24,31 @@ void Controller_ConsoleSixAxis::OnRelease() {}
19 24
20void Controller_ConsoleSixAxis::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 25void Controller_ConsoleSixAxis::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
21 std::size_t size) { 26 std::size_t size) {
22 seven_six_axis.header.timestamp = core_timing.GetCPUTicks();
23 seven_six_axis.header.total_entry_count = 17;
24
25 if (!IsControllerActivated() || !is_transfer_memory_set) { 27 if (!IsControllerActivated() || !is_transfer_memory_set) {
26 seven_six_axis.header.entry_count = 0; 28 seven_sixaxis_lifo.buffer_count = 0;
27 seven_six_axis.header.last_entry_index = 0; 29 seven_sixaxis_lifo.buffer_tail = 0;
28 return; 30 return;
29 } 31 }
30 seven_six_axis.header.entry_count = 16;
31
32 const auto& last_entry =
33 seven_six_axis.sevensixaxis_states[seven_six_axis.header.last_entry_index];
34 seven_six_axis.header.last_entry_index = (seven_six_axis.header.last_entry_index + 1) % 17;
35 auto& cur_entry = seven_six_axis.sevensixaxis_states[seven_six_axis.header.last_entry_index];
36 32
37 cur_entry.sampling_number = last_entry.sampling_number + 1; 33 const auto& last_entry = seven_sixaxis_lifo.ReadCurrentEntry().state;
38 cur_entry.sampling_number2 = cur_entry.sampling_number; 34 next_seven_sixaxis_state.sampling_number = last_entry.sampling_number + 1;
39 35
40 // Try to read sixaxis sensor states 36 // Try to read sixaxis sensor states
41 MotionDevice motion_device{}; 37 const auto motion_status = console->GetMotion();
42 const auto& device = motions[0]; 38
43 if (device) { 39 console_six_axis.is_seven_six_axis_sensor_at_rest = motion_status.is_at_rest;
44 std::tie(motion_device.accel, motion_device.gyro, motion_device.rotation,
45 motion_device.orientation, motion_device.quaternion) = device->GetStatus();
46 console_six_axis.is_seven_six_axis_sensor_at_rest = motion_device.gyro.Length2() < 0.0001f;
47 }
48 40
49 cur_entry.accel = motion_device.accel; 41 next_seven_sixaxis_state.accel = motion_status.accel;
50 // Zero gyro values as they just mess up with the camera 42 // Zero gyro values as they just mess up with the camera
51 // Note: Probably a correct sensivity setting must be set 43 // Note: Probably a correct sensivity setting must be set
52 cur_entry.gyro = {}; 44 next_seven_sixaxis_state.gyro = {};
53 cur_entry.quaternion = { 45 next_seven_sixaxis_state.quaternion = {
54 { 46 {
55 motion_device.quaternion.xyz.y, 47 motion_status.quaternion.xyz.y,
56 motion_device.quaternion.xyz.x, 48 motion_status.quaternion.xyz.x,
57 -motion_device.quaternion.w, 49 -motion_status.quaternion.w,
58 }, 50 },
59 -motion_device.quaternion.xyz.z, 51 -motion_status.quaternion.xyz.z,
60 }; 52 };
61 53
62 console_six_axis.sampling_number++; 54 console_six_axis.sampling_number++;
@@ -67,14 +59,8 @@ void Controller_ConsoleSixAxis::OnUpdate(const Core::Timing::CoreTiming& core_ti
67 // Update console six axis shared memory 59 // Update console six axis shared memory
68 std::memcpy(data + SHARED_MEMORY_OFFSET, &console_six_axis, sizeof(console_six_axis)); 60 std::memcpy(data + SHARED_MEMORY_OFFSET, &console_six_axis, sizeof(console_six_axis));
69 // Update seven six axis transfer memory 61 // Update seven six axis transfer memory
70 std::memcpy(transfer_memory, &seven_six_axis, sizeof(seven_six_axis)); 62 seven_sixaxis_lifo.WriteNextEntry(next_seven_sixaxis_state);
71} 63 std::memcpy(transfer_memory, &seven_sixaxis_lifo, sizeof(seven_sixaxis_lifo));
72
73void Controller_ConsoleSixAxis::OnLoadInputDevices() {
74 const auto player = Settings::values.players.GetValue()[0];
75 std::transform(player.motions.begin() + Settings::NativeMotion::MOTION_HID_BEGIN,
76 player.motions.begin() + Settings::NativeMotion::MOTION_HID_END, motions.begin(),
77 Input::CreateDevice<Input::MotionDevice>);
78} 64}
79 65
80void Controller_ConsoleSixAxis::SetTransferMemoryPointer(u8* t_mem) { 66void Controller_ConsoleSixAxis::SetTransferMemoryPointer(u8* t_mem) {
@@ -83,8 +69,7 @@ void Controller_ConsoleSixAxis::SetTransferMemoryPointer(u8* t_mem) {
83} 69}
84 70
85void Controller_ConsoleSixAxis::ResetTimestamp() { 71void Controller_ConsoleSixAxis::ResetTimestamp() {
86 auto& cur_entry = seven_six_axis.sevensixaxis_states[seven_six_axis.header.last_entry_index]; 72 seven_sixaxis_lifo.buffer_count = 0;
87 cur_entry.sampling_number = 0; 73 seven_sixaxis_lifo.buffer_tail = 0;
88 cur_entry.sampling_number2 = 0;
89} 74}
90} // namespace Service::HID 75} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/console_sixaxis.h b/src/core/hle/service/hid/controllers/console_sixaxis.h
index fd8a427af..279241858 100644
--- a/src/core/hle/service/hid/controllers/console_sixaxis.h
+++ b/src/core/hle/service/hid/controllers/console_sixaxis.h
@@ -5,16 +5,21 @@
5#pragma once 5#pragma once
6 6
7#include <array> 7#include <array>
8#include "common/bit_field.h" 8
9#include "common/common_types.h" 9#include "common/common_types.h"
10#include "common/quaternion.h" 10#include "common/quaternion.h"
11#include "core/frontend/input.h" 11#include "core/hid/hid_types.h"
12#include "core/hle/service/hid/controllers/controller_base.h" 12#include "core/hle/service/hid/controllers/controller_base.h"
13#include "core/hle/service/hid/ring_lifo.h"
14
15namespace Core::HID {
16class EmulatedConsole;
17} // namespace Core::HID
13 18
14namespace Service::HID { 19namespace Service::HID {
15class Controller_ConsoleSixAxis final : public ControllerBase { 20class Controller_ConsoleSixAxis final : public ControllerBase {
16public: 21public:
17 explicit Controller_ConsoleSixAxis(Core::System& system_); 22 explicit Controller_ConsoleSixAxis(Core::HID::HIDCore& hid_core_);
18 ~Controller_ConsoleSixAxis() override; 23 ~Controller_ConsoleSixAxis() override;
19 24
20 // Called when the controller is initialized 25 // Called when the controller is initialized
@@ -26,9 +31,6 @@ public:
26 // When the controller is requesting an update for the shared memory 31 // When the controller is requesting an update for the shared memory
27 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, size_t size) override; 32 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, size_t size) override;
28 33
29 // Called when input devices should be loaded
30 void OnLoadInputDevices() override;
31
32 // Called on InitializeSevenSixAxisSensor 34 // Called on InitializeSevenSixAxisSensor
33 void SetTransferMemoryPointer(u8* t_mem); 35 void SetTransferMemoryPointer(u8* t_mem);
34 36
@@ -38,43 +40,31 @@ public:
38private: 40private:
39 struct SevenSixAxisState { 41 struct SevenSixAxisState {
40 INSERT_PADDING_WORDS(4); // unused 42 INSERT_PADDING_WORDS(4); // unused
41 s64_le sampling_number{}; 43 s64 sampling_number{};
42 s64_le sampling_number2{};
43 u64 unknown{}; 44 u64 unknown{};
44 Common::Vec3f accel{}; 45 Common::Vec3f accel{};
45 Common::Vec3f gyro{}; 46 Common::Vec3f gyro{};
46 Common::Quaternion<f32> quaternion{}; 47 Common::Quaternion<f32> quaternion{};
47 }; 48 };
48 static_assert(sizeof(SevenSixAxisState) == 0x50, "SevenSixAxisState is an invalid size"); 49 static_assert(sizeof(SevenSixAxisState) == 0x48, "SevenSixAxisState is an invalid size");
49
50 struct SevenSixAxisMemory {
51 CommonHeader header{};
52 std::array<SevenSixAxisState, 0x21> sevensixaxis_states{};
53 };
54 static_assert(sizeof(SevenSixAxisMemory) == 0xA70, "SevenSixAxisMemory is an invalid size");
55 50
51 // This is nn::hid::detail::ConsoleSixAxisSensorSharedMemoryFormat
56 struct ConsoleSharedMemory { 52 struct ConsoleSharedMemory {
57 u64_le sampling_number{}; 53 u64 sampling_number{};
58 bool is_seven_six_axis_sensor_at_rest{}; 54 bool is_seven_six_axis_sensor_at_rest{};
55 INSERT_PADDING_BYTES(4); // padding
59 f32 verticalization_error{}; 56 f32 verticalization_error{};
60 Common::Vec3f gyro_bias{}; 57 Common::Vec3f gyro_bias{};
61 }; 58 };
62 static_assert(sizeof(ConsoleSharedMemory) == 0x20, "ConsoleSharedMemory is an invalid size"); 59 static_assert(sizeof(ConsoleSharedMemory) == 0x20, "ConsoleSharedMemory is an invalid size");
63 60
64 struct MotionDevice { 61 Lifo<SevenSixAxisState, 0x21> seven_sixaxis_lifo{};
65 Common::Vec3f accel; 62 static_assert(sizeof(seven_sixaxis_lifo) == 0xA70, "SevenSixAxisState is an invalid size");
66 Common::Vec3f gyro;
67 Common::Vec3f rotation;
68 std::array<Common::Vec3f, 3> orientation;
69 Common::Quaternion<f32> quaternion;
70 };
71 63
72 using MotionArray = 64 Core::HID::EmulatedConsole* console;
73 std::array<std::unique_ptr<Input::MotionDevice>, Settings::NativeMotion::NUM_MOTIONS_HID>;
74 MotionArray motions;
75 u8* transfer_memory = nullptr; 65 u8* transfer_memory = nullptr;
76 bool is_transfer_memory_set = false; 66 bool is_transfer_memory_set = false;
77 ConsoleSharedMemory console_six_axis{}; 67 ConsoleSharedMemory console_six_axis{};
78 SevenSixAxisMemory seven_six_axis{}; 68 SevenSixAxisState next_seven_sixaxis_state{};
79}; 69};
80} // namespace Service::HID 70} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/controller_base.cpp b/src/core/hle/service/hid/controllers/controller_base.cpp
index 9d1e6db6a..788ae9ae7 100644
--- a/src/core/hle/service/hid/controllers/controller_base.cpp
+++ b/src/core/hle/service/hid/controllers/controller_base.cpp
@@ -6,12 +6,12 @@
6 6
7namespace Service::HID { 7namespace Service::HID {
8 8
9ControllerBase::ControllerBase(Core::System& system_) : system(system_) {} 9ControllerBase::ControllerBase(Core::HID::HIDCore& hid_core_) : hid_core(hid_core_) {}
10ControllerBase::~ControllerBase() = default; 10ControllerBase::~ControllerBase() = default;
11 11
12void ControllerBase::ActivateController() { 12void ControllerBase::ActivateController() {
13 if (is_activated) { 13 if (is_activated) {
14 OnRelease(); 14 return;
15 } 15 }
16 is_activated = true; 16 is_activated = true;
17 OnInit(); 17 OnInit();
diff --git a/src/core/hle/service/hid/controllers/controller_base.h b/src/core/hle/service/hid/controllers/controller_base.h
index 1556fb08e..7450eb20a 100644
--- a/src/core/hle/service/hid/controllers/controller_base.h
+++ b/src/core/hle/service/hid/controllers/controller_base.h
@@ -11,14 +11,14 @@ namespace Core::Timing {
11class CoreTiming; 11class CoreTiming;
12} 12}
13 13
14namespace Core { 14namespace Core::HID {
15class System; 15class HIDCore;
16} 16}
17 17
18namespace Service::HID { 18namespace Service::HID {
19class ControllerBase { 19class ControllerBase {
20public: 20public:
21 explicit ControllerBase(Core::System& system_); 21 explicit ControllerBase(Core::HID::HIDCore& hid_core_);
22 virtual ~ControllerBase(); 22 virtual ~ControllerBase();
23 23
24 // Called when the controller is initialized 24 // Called when the controller is initialized
@@ -35,26 +35,17 @@ public:
35 virtual void OnMotionUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 35 virtual void OnMotionUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
36 std::size_t size) {} 36 std::size_t size) {}
37 37
38 // Called when input devices should be loaded
39 virtual void OnLoadInputDevices() = 0;
40
41 void ActivateController(); 38 void ActivateController();
42 39
43 void DeactivateController(); 40 void DeactivateController();
44 41
45 bool IsControllerActivated() const; 42 bool IsControllerActivated() const;
46 43
44 static const std::size_t hid_entry_count = 17;
45
47protected: 46protected:
48 bool is_activated{false}; 47 bool is_activated{false};
49 48
50 struct CommonHeader { 49 Core::HID::HIDCore& hid_core;
51 s64_le timestamp;
52 s64_le total_entry_count;
53 s64_le last_entry_index;
54 s64_le entry_count;
55 };
56 static_assert(sizeof(CommonHeader) == 0x20, "CommonHeader is an invalid size");
57
58 Core::System& system;
59}; 50};
60} // namespace Service::HID 51} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/debug_pad.cpp b/src/core/hle/service/hid/controllers/debug_pad.cpp
index d439b8fb0..6a6fb9cab 100644
--- a/src/core/hle/service/hid/controllers/debug_pad.cpp
+++ b/src/core/hle/service/hid/controllers/debug_pad.cpp
@@ -6,15 +6,19 @@
6#include "common/common_types.h" 6#include "common/common_types.h"
7#include "common/settings.h" 7#include "common/settings.h"
8#include "core/core_timing.h" 8#include "core/core_timing.h"
9#include "core/hid/emulated_controller.h"
10#include "core/hid/hid_core.h"
11#include "core/hid/hid_types.h"
9#include "core/hle/service/hid/controllers/debug_pad.h" 12#include "core/hle/service/hid/controllers/debug_pad.h"
10 13
11namespace Service::HID { 14namespace Service::HID {
15constexpr std::size_t SHARED_MEMORY_OFFSET = 0x00000;
12 16
13constexpr s32 HID_JOYSTICK_MAX = 0x7fff; 17Controller_DebugPad::Controller_DebugPad(Core::HID::HIDCore& hid_core_)
14[[maybe_unused]] constexpr s32 HID_JOYSTICK_MIN = -0x7fff; 18 : ControllerBase{hid_core_} {
15enum class JoystickId : std::size_t { Joystick_Left, Joystick_Right }; 19 controller = hid_core.GetEmulatedController(Core::HID::NpadIdType::Other);
20}
16 21
17Controller_DebugPad::Controller_DebugPad(Core::System& system_) : ControllerBase{system_} {}
18Controller_DebugPad::~Controller_DebugPad() = default; 22Controller_DebugPad::~Controller_DebugPad() = default;
19 23
20void Controller_DebugPad::OnInit() {} 24void Controller_DebugPad::OnInit() {}
@@ -23,63 +27,29 @@ void Controller_DebugPad::OnRelease() {}
23 27
24void Controller_DebugPad::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 28void Controller_DebugPad::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
25 std::size_t size) { 29 std::size_t size) {
26 shared_memory.header.timestamp = core_timing.GetCPUTicks();
27 shared_memory.header.total_entry_count = 17;
28
29 if (!IsControllerActivated()) { 30 if (!IsControllerActivated()) {
30 shared_memory.header.entry_count = 0; 31 debug_pad_lifo.buffer_count = 0;
31 shared_memory.header.last_entry_index = 0; 32 debug_pad_lifo.buffer_tail = 0;
33 std::memcpy(data + SHARED_MEMORY_OFFSET, &debug_pad_lifo, sizeof(debug_pad_lifo));
32 return; 34 return;
33 } 35 }
34 shared_memory.header.entry_count = 16;
35 36
36 const auto& last_entry = shared_memory.pad_states[shared_memory.header.last_entry_index]; 37 const auto& last_entry = debug_pad_lifo.ReadCurrentEntry().state;
37 shared_memory.header.last_entry_index = (shared_memory.header.last_entry_index + 1) % 17; 38 next_state.sampling_number = last_entry.sampling_number + 1;
38 auto& cur_entry = shared_memory.pad_states[shared_memory.header.last_entry_index];
39
40 cur_entry.sampling_number = last_entry.sampling_number + 1;
41 cur_entry.sampling_number2 = cur_entry.sampling_number;
42 39
43 if (Settings::values.debug_pad_enabled) { 40 if (Settings::values.debug_pad_enabled) {
44 cur_entry.attribute.connected.Assign(1); 41 next_state.attribute.connected.Assign(1);
45 auto& pad = cur_entry.pad_state;
46 42
47 using namespace Settings::NativeButton; 43 const auto& button_state = controller->GetDebugPadButtons();
48 pad.a.Assign(buttons[A - BUTTON_HID_BEGIN]->GetStatus()); 44 const auto& stick_state = controller->GetSticks();
49 pad.b.Assign(buttons[B - BUTTON_HID_BEGIN]->GetStatus());
50 pad.x.Assign(buttons[X - BUTTON_HID_BEGIN]->GetStatus());
51 pad.y.Assign(buttons[Y - BUTTON_HID_BEGIN]->GetStatus());
52 pad.l.Assign(buttons[L - BUTTON_HID_BEGIN]->GetStatus());
53 pad.r.Assign(buttons[R - BUTTON_HID_BEGIN]->GetStatus());
54 pad.zl.Assign(buttons[ZL - BUTTON_HID_BEGIN]->GetStatus());
55 pad.zr.Assign(buttons[ZR - BUTTON_HID_BEGIN]->GetStatus());
56 pad.plus.Assign(buttons[Plus - BUTTON_HID_BEGIN]->GetStatus());
57 pad.minus.Assign(buttons[Minus - BUTTON_HID_BEGIN]->GetStatus());
58 pad.d_left.Assign(buttons[DLeft - BUTTON_HID_BEGIN]->GetStatus());
59 pad.d_up.Assign(buttons[DUp - BUTTON_HID_BEGIN]->GetStatus());
60 pad.d_right.Assign(buttons[DRight - BUTTON_HID_BEGIN]->GetStatus());
61 pad.d_down.Assign(buttons[DDown - BUTTON_HID_BEGIN]->GetStatus());
62 45
63 const auto [stick_l_x_f, stick_l_y_f] = 46 next_state.pad_state = button_state;
64 analogs[static_cast<std::size_t>(JoystickId::Joystick_Left)]->GetStatus(); 47 next_state.l_stick = stick_state.left;
65 const auto [stick_r_x_f, stick_r_y_f] = 48 next_state.r_stick = stick_state.right;
66 analogs[static_cast<std::size_t>(JoystickId::Joystick_Right)]->GetStatus();
67 cur_entry.l_stick.x = static_cast<s32>(stick_l_x_f * HID_JOYSTICK_MAX);
68 cur_entry.l_stick.y = static_cast<s32>(stick_l_y_f * HID_JOYSTICK_MAX);
69 cur_entry.r_stick.x = static_cast<s32>(stick_r_x_f * HID_JOYSTICK_MAX);
70 cur_entry.r_stick.y = static_cast<s32>(stick_r_y_f * HID_JOYSTICK_MAX);
71 } 49 }
72 50
73 std::memcpy(data, &shared_memory, sizeof(SharedMemory)); 51 debug_pad_lifo.WriteNextEntry(next_state);
52 std::memcpy(data + SHARED_MEMORY_OFFSET, &debug_pad_lifo, sizeof(debug_pad_lifo));
74} 53}
75 54
76void Controller_DebugPad::OnLoadInputDevices() {
77 std::transform(Settings::values.debug_pad_buttons.begin(),
78 Settings::values.debug_pad_buttons.begin() +
79 Settings::NativeButton::NUM_BUTTONS_HID,
80 buttons.begin(), Input::CreateDevice<Input::ButtonDevice>);
81 std::transform(Settings::values.debug_pad_analogs.begin(),
82 Settings::values.debug_pad_analogs.end(), analogs.begin(),
83 Input::CreateDevice<Input::AnalogDevice>);
84}
85} // namespace Service::HID 55} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/debug_pad.h b/src/core/hle/service/hid/controllers/debug_pad.h
index 1b1645184..afe374fc2 100644
--- a/src/core/hle/service/hid/controllers/debug_pad.h
+++ b/src/core/hle/service/hid/controllers/debug_pad.h
@@ -8,15 +8,20 @@
8#include "common/bit_field.h" 8#include "common/bit_field.h"
9#include "common/common_funcs.h" 9#include "common/common_funcs.h"
10#include "common/common_types.h" 10#include "common/common_types.h"
11#include "common/settings.h"
12#include "common/swap.h" 11#include "common/swap.h"
13#include "core/frontend/input.h"
14#include "core/hle/service/hid/controllers/controller_base.h" 12#include "core/hle/service/hid/controllers/controller_base.h"
13#include "core/hle/service/hid/ring_lifo.h"
14
15namespace Core::HID {
16class EmulatedController;
17struct DebugPadButton;
18struct AnalogStickState;
19} // namespace Core::HID
15 20
16namespace Service::HID { 21namespace Service::HID {
17class Controller_DebugPad final : public ControllerBase { 22class Controller_DebugPad final : public ControllerBase {
18public: 23public:
19 explicit Controller_DebugPad(Core::System& system_); 24 explicit Controller_DebugPad(Core::HID::HIDCore& hid_core_);
20 ~Controller_DebugPad() override; 25 ~Controller_DebugPad() override;
21 26
22 // Called when the controller is initialized 27 // Called when the controller is initialized
@@ -28,66 +33,31 @@ public:
28 // When the controller is requesting an update for the shared memory 33 // When the controller is requesting an update for the shared memory
29 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override; 34 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override;
30 35
31 // Called when input devices should be loaded
32 void OnLoadInputDevices() override;
33
34private: 36private:
35 struct AnalogStick { 37 // This is nn::hid::DebugPadAttribute
36 s32_le x; 38 struct DebugPadAttribute {
37 s32_le y;
38 };
39 static_assert(sizeof(AnalogStick) == 0x8);
40
41 struct PadState {
42 union {
43 u32_le raw{};
44 BitField<0, 1, u32> a;
45 BitField<1, 1, u32> b;
46 BitField<2, 1, u32> x;
47 BitField<3, 1, u32> y;
48 BitField<4, 1, u32> l;
49 BitField<5, 1, u32> r;
50 BitField<6, 1, u32> zl;
51 BitField<7, 1, u32> zr;
52 BitField<8, 1, u32> plus;
53 BitField<9, 1, u32> minus;
54 BitField<10, 1, u32> d_left;
55 BitField<11, 1, u32> d_up;
56 BitField<12, 1, u32> d_right;
57 BitField<13, 1, u32> d_down;
58 };
59 };
60 static_assert(sizeof(PadState) == 0x4, "PadState is an invalid size");
61
62 struct Attributes {
63 union { 39 union {
64 u32_le raw{}; 40 u32 raw{};
65 BitField<0, 1, u32> connected; 41 BitField<0, 1, u32> connected;
66 }; 42 };
67 }; 43 };
68 static_assert(sizeof(Attributes) == 0x4, "Attributes is an invalid size"); 44 static_assert(sizeof(DebugPadAttribute) == 0x4, "DebugPadAttribute is an invalid size");
69 45
70 struct PadStates { 46 // This is nn::hid::DebugPadState
71 s64_le sampling_number; 47 struct DebugPadState {
72 s64_le sampling_number2; 48 s64 sampling_number;
73 Attributes attribute; 49 DebugPadAttribute attribute;
74 PadState pad_state; 50 Core::HID::DebugPadButton pad_state;
75 AnalogStick r_stick; 51 Core::HID::AnalogStickState r_stick;
76 AnalogStick l_stick; 52 Core::HID::AnalogStickState l_stick;
77 }; 53 };
78 static_assert(sizeof(PadStates) == 0x28, "PadStates is an invalid state"); 54 static_assert(sizeof(DebugPadState) == 0x20, "DebugPadState is an invalid state");
79 55
80 struct SharedMemory { 56 // This is nn::hid::detail::DebugPadLifo
81 CommonHeader header; 57 Lifo<DebugPadState, hid_entry_count> debug_pad_lifo{};
82 std::array<PadStates, 17> pad_states; 58 static_assert(sizeof(debug_pad_lifo) == 0x2C8, "debug_pad_lifo is an invalid size");
83 INSERT_PADDING_BYTES(0x138); 59 DebugPadState next_state{};
84 };
85 static_assert(sizeof(SharedMemory) == 0x400, "SharedMemory is an invalid size");
86 SharedMemory shared_memory{};
87 60
88 std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeButton::NUM_BUTTONS_HID> 61 Core::HID::EmulatedController* controller;
89 buttons;
90 std::array<std::unique_ptr<Input::AnalogDevice>, Settings::NativeAnalog::NUM_STICKS_HID>
91 analogs;
92}; 62};
93} // namespace Service::HID 63} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/gesture.cpp b/src/core/hle/service/hid/controllers/gesture.cpp
index 764abb5b6..fe895c4f6 100644
--- a/src/core/hle/service/hid/controllers/gesture.cpp
+++ b/src/core/hle/service/hid/controllers/gesture.cpp
@@ -7,6 +7,7 @@
7#include "common/settings.h" 7#include "common/settings.h"
8#include "core/core_timing.h" 8#include "core/core_timing.h"
9#include "core/frontend/emu_window.h" 9#include "core/frontend/emu_window.h"
10#include "core/hid/hid_core.h"
10#include "core/hle/service/hid/controllers/gesture.h" 11#include "core/hle/service/hid/controllers/gesture.h"
11 12
12namespace Service::HID { 13namespace Service::HID {
@@ -23,16 +24,14 @@ constexpr f32 Square(s32 num) {
23 return static_cast<f32>(num * num); 24 return static_cast<f32>(num * num);
24} 25}
25 26
26Controller_Gesture::Controller_Gesture(Core::System& system_) : ControllerBase(system_) {} 27Controller_Gesture::Controller_Gesture(Core::HID::HIDCore& hid_core_) : ControllerBase(hid_core_) {
28 console = hid_core.GetEmulatedConsole();
29}
27Controller_Gesture::~Controller_Gesture() = default; 30Controller_Gesture::~Controller_Gesture() = default;
28 31
29void Controller_Gesture::OnInit() { 32void Controller_Gesture::OnInit() {
30 for (std::size_t id = 0; id < MAX_FINGERS; ++id) { 33 gesture_lifo.buffer_count = 0;
31 mouse_finger_id[id] = MAX_POINTS; 34 gesture_lifo.buffer_tail = 0;
32 keyboard_finger_id[id] = MAX_POINTS;
33 udp_finger_id[id] = MAX_POINTS;
34 }
35 shared_memory.header.entry_count = 0;
36 force_update = true; 35 force_update = true;
37} 36}
38 37
@@ -40,50 +39,38 @@ void Controller_Gesture::OnRelease() {}
40 39
41void Controller_Gesture::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 40void Controller_Gesture::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
42 std::size_t size) { 41 std::size_t size) {
43 shared_memory.header.timestamp = core_timing.GetCPUTicks();
44 shared_memory.header.total_entry_count = 17;
45
46 if (!IsControllerActivated()) { 42 if (!IsControllerActivated()) {
47 shared_memory.header.entry_count = 0; 43 gesture_lifo.buffer_count = 0;
48 shared_memory.header.last_entry_index = 0; 44 gesture_lifo.buffer_tail = 0;
45 std::memcpy(data + SHARED_MEMORY_OFFSET, &gesture_lifo, sizeof(gesture_lifo));
49 return; 46 return;
50 } 47 }
51 48
52 ReadTouchInput(); 49 ReadTouchInput();
53 50
54 GestureProperties gesture = GetGestureProperties(); 51 GestureProperties gesture = GetGestureProperties();
55 f32 time_difference = static_cast<f32>(shared_memory.header.timestamp - last_update_timestamp) / 52 f32 time_difference =
56 (1000 * 1000 * 1000); 53 static_cast<f32>(gesture_lifo.timestamp - last_update_timestamp) / (1000 * 1000 * 1000);
57 54
58 // Only update if necesary 55 // Only update if necesary
59 if (!ShouldUpdateGesture(gesture, time_difference)) { 56 if (!ShouldUpdateGesture(gesture, time_difference)) {
60 return; 57 return;
61 } 58 }
62 59
63 last_update_timestamp = shared_memory.header.timestamp; 60 last_update_timestamp = gesture_lifo.timestamp;
64 UpdateGestureSharedMemory(data, size, gesture, time_difference); 61 UpdateGestureSharedMemory(data, size, gesture, time_difference);
65} 62}
66 63
67void Controller_Gesture::ReadTouchInput() { 64void Controller_Gesture::ReadTouchInput() {
68 const Input::TouchStatus& mouse_status = touch_mouse_device->GetStatus(); 65 const auto touch_status = console->GetTouch();
69 const Input::TouchStatus& udp_status = touch_udp_device->GetStatus(); 66 for (std::size_t id = 0; id < fingers.size(); ++id) {
70 for (std::size_t id = 0; id < mouse_status.size(); ++id) { 67 fingers[id] = touch_status[id];
71 mouse_finger_id[id] = UpdateTouchInputEvent(mouse_status[id], mouse_finger_id[id]);
72 udp_finger_id[id] = UpdateTouchInputEvent(udp_status[id], udp_finger_id[id]);
73 }
74
75 if (Settings::values.use_touch_from_button) {
76 const Input::TouchStatus& keyboard_status = touch_btn_device->GetStatus();
77 for (std::size_t id = 0; id < mouse_status.size(); ++id) {
78 keyboard_finger_id[id] =
79 UpdateTouchInputEvent(keyboard_status[id], keyboard_finger_id[id]);
80 }
81 } 68 }
82} 69}
83 70
84bool Controller_Gesture::ShouldUpdateGesture(const GestureProperties& gesture, 71bool Controller_Gesture::ShouldUpdateGesture(const GestureProperties& gesture,
85 f32 time_difference) { 72 f32 time_difference) {
86 const auto& last_entry = shared_memory.gesture_states[shared_memory.header.last_entry_index]; 73 const auto& last_entry = GetLastGestureEntry();
87 if (force_update) { 74 if (force_update) {
88 force_update = false; 75 force_update = false;
89 return true; 76 return true;
@@ -97,7 +84,7 @@ bool Controller_Gesture::ShouldUpdateGesture(const GestureProperties& gesture,
97 } 84 }
98 85
99 // Update on press and hold event after 0.5 seconds 86 // Update on press and hold event after 0.5 seconds
100 if (last_entry.type == TouchType::Touch && last_entry.point_count == 1 && 87 if (last_entry.type == GestureType::Touch && last_entry.point_count == 1 &&
101 time_difference > press_delay) { 88 time_difference > press_delay) {
102 return enable_press_and_tap; 89 return enable_press_and_tap;
103 } 90 }
@@ -108,27 +95,19 @@ bool Controller_Gesture::ShouldUpdateGesture(const GestureProperties& gesture,
108void Controller_Gesture::UpdateGestureSharedMemory(u8* data, std::size_t size, 95void Controller_Gesture::UpdateGestureSharedMemory(u8* data, std::size_t size,
109 GestureProperties& gesture, 96 GestureProperties& gesture,
110 f32 time_difference) { 97 f32 time_difference) {
111 TouchType type = TouchType::Idle; 98 GestureType type = GestureType::Idle;
112 Attribute attributes{}; 99 GestureAttribute attributes{};
113 100
114 const auto& last_entry = shared_memory.gesture_states[shared_memory.header.last_entry_index]; 101 const auto& last_entry = gesture_lifo.ReadCurrentEntry().state;
115 shared_memory.header.last_entry_index = (shared_memory.header.last_entry_index + 1) % 17;
116 auto& cur_entry = shared_memory.gesture_states[shared_memory.header.last_entry_index];
117 102
118 if (shared_memory.header.entry_count < 16) { 103 // Reset next state to default
119 shared_memory.header.entry_count++; 104 next_state.sampling_number = last_entry.sampling_number + 1;
120 } 105 next_state.delta = {};
121 106 next_state.vel_x = 0;
122 cur_entry.sampling_number = last_entry.sampling_number + 1; 107 next_state.vel_y = 0;
123 cur_entry.sampling_number2 = cur_entry.sampling_number; 108 next_state.direction = GestureDirection::None;
124 109 next_state.rotation_angle = 0;
125 // Reset values to default 110 next_state.scale = 0;
126 cur_entry.delta = {};
127 cur_entry.vel_x = 0;
128 cur_entry.vel_y = 0;
129 cur_entry.direction = Direction::None;
130 cur_entry.rotation_angle = 0;
131 cur_entry.scale = 0;
132 111
133 if (gesture.active_points > 0) { 112 if (gesture.active_points > 0) {
134 if (last_gesture.active_points == 0) { 113 if (last_gesture.active_points == 0) {
@@ -141,46 +120,47 @@ void Controller_Gesture::UpdateGestureSharedMemory(u8* data, std::size_t size,
141 } 120 }
142 121
143 // Apply attributes 122 // Apply attributes
144 cur_entry.detection_count = gesture.detection_count; 123 next_state.detection_count = gesture.detection_count;
145 cur_entry.type = type; 124 next_state.type = type;
146 cur_entry.attributes = attributes; 125 next_state.attributes = attributes;
147 cur_entry.pos = gesture.mid_point; 126 next_state.pos = gesture.mid_point;
148 cur_entry.point_count = static_cast<s32>(gesture.active_points); 127 next_state.point_count = static_cast<s32>(gesture.active_points);
149 cur_entry.points = gesture.points; 128 next_state.points = gesture.points;
150 last_gesture = gesture; 129 last_gesture = gesture;
151 130
152 std::memcpy(data + SHARED_MEMORY_OFFSET, &shared_memory, sizeof(SharedMemory)); 131 gesture_lifo.WriteNextEntry(next_state);
132 std::memcpy(data + SHARED_MEMORY_OFFSET, &gesture_lifo, sizeof(gesture_lifo));
153} 133}
154 134
155void Controller_Gesture::NewGesture(GestureProperties& gesture, TouchType& type, 135void Controller_Gesture::NewGesture(GestureProperties& gesture, GestureType& type,
156 Attribute& attributes) { 136 GestureAttribute& attributes) {
157 const auto& last_entry = GetLastGestureEntry(); 137 const auto& last_entry = GetLastGestureEntry();
158 138
159 gesture.detection_count++; 139 gesture.detection_count++;
160 type = TouchType::Touch; 140 type = GestureType::Touch;
161 141
162 // New touch after cancel is not considered new 142 // New touch after cancel is not considered new
163 if (last_entry.type != TouchType::Cancel) { 143 if (last_entry.type != GestureType::Cancel) {
164 attributes.is_new_touch.Assign(1); 144 attributes.is_new_touch.Assign(1);
165 enable_press_and_tap = true; 145 enable_press_and_tap = true;
166 } 146 }
167} 147}
168 148
169void Controller_Gesture::UpdateExistingGesture(GestureProperties& gesture, TouchType& type, 149void Controller_Gesture::UpdateExistingGesture(GestureProperties& gesture, GestureType& type,
170 f32 time_difference) { 150 f32 time_difference) {
171 const auto& last_entry = GetLastGestureEntry(); 151 const auto& last_entry = GetLastGestureEntry();
172 152
173 // Promote to pan type if touch moved 153 // Promote to pan type if touch moved
174 for (size_t id = 0; id < MAX_POINTS; id++) { 154 for (size_t id = 0; id < MAX_POINTS; id++) {
175 if (gesture.points[id] != last_gesture.points[id]) { 155 if (gesture.points[id] != last_gesture.points[id]) {
176 type = TouchType::Pan; 156 type = GestureType::Pan;
177 break; 157 break;
178 } 158 }
179 } 159 }
180 160
181 // Number of fingers changed cancel the last event and clear data 161 // Number of fingers changed cancel the last event and clear data
182 if (gesture.active_points != last_gesture.active_points) { 162 if (gesture.active_points != last_gesture.active_points) {
183 type = TouchType::Cancel; 163 type = GestureType::Cancel;
184 enable_press_and_tap = false; 164 enable_press_and_tap = false;
185 gesture.active_points = 0; 165 gesture.active_points = 0;
186 gesture.mid_point = {}; 166 gesture.mid_point = {};
@@ -189,41 +169,41 @@ void Controller_Gesture::UpdateExistingGesture(GestureProperties& gesture, Touch
189 } 169 }
190 170
191 // Calculate extra parameters of panning 171 // Calculate extra parameters of panning
192 if (type == TouchType::Pan) { 172 if (type == GestureType::Pan) {
193 UpdatePanEvent(gesture, last_gesture, type, time_difference); 173 UpdatePanEvent(gesture, last_gesture, type, time_difference);
194 return; 174 return;
195 } 175 }
196 176
197 // Promote to press type 177 // Promote to press type
198 if (last_entry.type == TouchType::Touch) { 178 if (last_entry.type == GestureType::Touch) {
199 type = TouchType::Press; 179 type = GestureType::Press;
200 } 180 }
201} 181}
202 182
203void Controller_Gesture::EndGesture(GestureProperties& gesture, 183void Controller_Gesture::EndGesture(GestureProperties& gesture,
204 GestureProperties& last_gesture_props, TouchType& type, 184 GestureProperties& last_gesture_props, GestureType& type,
205 Attribute& attributes, f32 time_difference) { 185 GestureAttribute& attributes, f32 time_difference) {
206 const auto& last_entry = GetLastGestureEntry(); 186 const auto& last_entry = GetLastGestureEntry();
207 187
208 if (last_gesture_props.active_points != 0) { 188 if (last_gesture_props.active_points != 0) {
209 switch (last_entry.type) { 189 switch (last_entry.type) {
210 case TouchType::Touch: 190 case GestureType::Touch:
211 if (enable_press_and_tap) { 191 if (enable_press_and_tap) {
212 SetTapEvent(gesture, last_gesture_props, type, attributes); 192 SetTapEvent(gesture, last_gesture_props, type, attributes);
213 return; 193 return;
214 } 194 }
215 type = TouchType::Cancel; 195 type = GestureType::Cancel;
216 force_update = true; 196 force_update = true;
217 break; 197 break;
218 case TouchType::Press: 198 case GestureType::Press:
219 case TouchType::Tap: 199 case GestureType::Tap:
220 case TouchType::Swipe: 200 case GestureType::Swipe:
221 case TouchType::Pinch: 201 case GestureType::Pinch:
222 case TouchType::Rotate: 202 case GestureType::Rotate:
223 type = TouchType::Complete; 203 type = GestureType::Complete;
224 force_update = true; 204 force_update = true;
225 break; 205 break;
226 case TouchType::Pan: 206 case GestureType::Pan:
227 EndPanEvent(gesture, last_gesture_props, type, time_difference); 207 EndPanEvent(gesture, last_gesture_props, type, time_difference);
228 break; 208 break;
229 default: 209 default:
@@ -231,15 +211,15 @@ void Controller_Gesture::EndGesture(GestureProperties& gesture,
231 } 211 }
232 return; 212 return;
233 } 213 }
234 if (last_entry.type == TouchType::Complete || last_entry.type == TouchType::Cancel) { 214 if (last_entry.type == GestureType::Complete || last_entry.type == GestureType::Cancel) {
235 gesture.detection_count++; 215 gesture.detection_count++;
236 } 216 }
237} 217}
238 218
239void Controller_Gesture::SetTapEvent(GestureProperties& gesture, 219void Controller_Gesture::SetTapEvent(GestureProperties& gesture,
240 GestureProperties& last_gesture_props, TouchType& type, 220 GestureProperties& last_gesture_props, GestureType& type,
241 Attribute& attributes) { 221 GestureAttribute& attributes) {
242 type = TouchType::Tap; 222 type = GestureType::Tap;
243 gesture = last_gesture_props; 223 gesture = last_gesture_props;
244 force_update = true; 224 force_update = true;
245 f32 tap_time_difference = 225 f32 tap_time_difference =
@@ -251,44 +231,42 @@ void Controller_Gesture::SetTapEvent(GestureProperties& gesture,
251} 231}
252 232
253void Controller_Gesture::UpdatePanEvent(GestureProperties& gesture, 233void Controller_Gesture::UpdatePanEvent(GestureProperties& gesture,
254 GestureProperties& last_gesture_props, TouchType& type, 234 GestureProperties& last_gesture_props, GestureType& type,
255 f32 time_difference) { 235 f32 time_difference) {
256 auto& cur_entry = shared_memory.gesture_states[shared_memory.header.last_entry_index];
257 const auto& last_entry = GetLastGestureEntry(); 236 const auto& last_entry = GetLastGestureEntry();
258 237
259 cur_entry.delta = gesture.mid_point - last_entry.pos; 238 next_state.delta = gesture.mid_point - last_entry.pos;
260 cur_entry.vel_x = static_cast<f32>(cur_entry.delta.x) / time_difference; 239 next_state.vel_x = static_cast<f32>(next_state.delta.x) / time_difference;
261 cur_entry.vel_y = static_cast<f32>(cur_entry.delta.y) / time_difference; 240 next_state.vel_y = static_cast<f32>(next_state.delta.y) / time_difference;
262 last_pan_time_difference = time_difference; 241 last_pan_time_difference = time_difference;
263 242
264 // Promote to pinch type 243 // Promote to pinch type
265 if (std::abs(gesture.average_distance - last_gesture_props.average_distance) > 244 if (std::abs(gesture.average_distance - last_gesture_props.average_distance) >
266 pinch_threshold) { 245 pinch_threshold) {
267 type = TouchType::Pinch; 246 type = GestureType::Pinch;
268 cur_entry.scale = gesture.average_distance / last_gesture_props.average_distance; 247 next_state.scale = gesture.average_distance / last_gesture_props.average_distance;
269 } 248 }
270 249
271 const f32 angle_between_two_lines = std::atan((gesture.angle - last_gesture_props.angle) / 250 const f32 angle_between_two_lines = std::atan((gesture.angle - last_gesture_props.angle) /
272 (1 + (gesture.angle * last_gesture_props.angle))); 251 (1 + (gesture.angle * last_gesture_props.angle)));
273 // Promote to rotate type 252 // Promote to rotate type
274 if (std::abs(angle_between_two_lines) > angle_threshold) { 253 if (std::abs(angle_between_two_lines) > angle_threshold) {
275 type = TouchType::Rotate; 254 type = GestureType::Rotate;
276 cur_entry.scale = 0; 255 next_state.scale = 0;
277 cur_entry.rotation_angle = angle_between_two_lines * 180.0f / Common::PI; 256 next_state.rotation_angle = angle_between_two_lines * 180.0f / Common::PI;
278 } 257 }
279} 258}
280 259
281void Controller_Gesture::EndPanEvent(GestureProperties& gesture, 260void Controller_Gesture::EndPanEvent(GestureProperties& gesture,
282 GestureProperties& last_gesture_props, TouchType& type, 261 GestureProperties& last_gesture_props, GestureType& type,
283 f32 time_difference) { 262 f32 time_difference) {
284 auto& cur_entry = shared_memory.gesture_states[shared_memory.header.last_entry_index];
285 const auto& last_entry = GetLastGestureEntry(); 263 const auto& last_entry = GetLastGestureEntry();
286 cur_entry.vel_x = 264 next_state.vel_x =
287 static_cast<f32>(last_entry.delta.x) / (last_pan_time_difference + time_difference); 265 static_cast<f32>(last_entry.delta.x) / (last_pan_time_difference + time_difference);
288 cur_entry.vel_y = 266 next_state.vel_y =
289 static_cast<f32>(last_entry.delta.y) / (last_pan_time_difference + time_difference); 267 static_cast<f32>(last_entry.delta.y) / (last_pan_time_difference + time_difference);
290 const f32 curr_vel = 268 const f32 curr_vel =
291 std::sqrt((cur_entry.vel_x * cur_entry.vel_x) + (cur_entry.vel_y * cur_entry.vel_y)); 269 std::sqrt((next_state.vel_x * next_state.vel_x) + (next_state.vel_y * next_state.vel_y));
292 270
293 // Set swipe event with parameters 271 // Set swipe event with parameters
294 if (curr_vel > swipe_threshold) { 272 if (curr_vel > swipe_threshold) {
@@ -297,105 +275,50 @@ void Controller_Gesture::EndPanEvent(GestureProperties& gesture,
297 } 275 }
298 276
299 // End panning without swipe 277 // End panning without swipe
300 type = TouchType::Complete; 278 type = GestureType::Complete;
301 cur_entry.vel_x = 0; 279 next_state.vel_x = 0;
302 cur_entry.vel_y = 0; 280 next_state.vel_y = 0;
303 force_update = true; 281 force_update = true;
304} 282}
305 283
306void Controller_Gesture::SetSwipeEvent(GestureProperties& gesture, 284void Controller_Gesture::SetSwipeEvent(GestureProperties& gesture,
307 GestureProperties& last_gesture_props, TouchType& type) { 285 GestureProperties& last_gesture_props, GestureType& type) {
308 auto& cur_entry = shared_memory.gesture_states[shared_memory.header.last_entry_index];
309 const auto& last_entry = GetLastGestureEntry(); 286 const auto& last_entry = GetLastGestureEntry();
310 287
311 type = TouchType::Swipe; 288 type = GestureType::Swipe;
312 gesture = last_gesture_props; 289 gesture = last_gesture_props;
313 force_update = true; 290 force_update = true;
314 cur_entry.delta = last_entry.delta; 291 next_state.delta = last_entry.delta;
315 292
316 if (std::abs(cur_entry.delta.x) > std::abs(cur_entry.delta.y)) { 293 if (std::abs(next_state.delta.x) > std::abs(next_state.delta.y)) {
317 if (cur_entry.delta.x > 0) { 294 if (next_state.delta.x > 0) {
318 cur_entry.direction = Direction::Right; 295 next_state.direction = GestureDirection::Right;
319 return; 296 return;
320 } 297 }
321 cur_entry.direction = Direction::Left; 298 next_state.direction = GestureDirection::Left;
322 return; 299 return;
323 } 300 }
324 if (cur_entry.delta.y > 0) { 301 if (next_state.delta.y > 0) {
325 cur_entry.direction = Direction::Down; 302 next_state.direction = GestureDirection::Down;
326 return; 303 return;
327 } 304 }
328 cur_entry.direction = Direction::Up; 305 next_state.direction = GestureDirection::Up;
329}
330
331void Controller_Gesture::OnLoadInputDevices() {
332 touch_mouse_device = Input::CreateDevice<Input::TouchDevice>("engine:emu_window");
333 touch_udp_device = Input::CreateDevice<Input::TouchDevice>("engine:cemuhookudp");
334 touch_btn_device = Input::CreateDevice<Input::TouchDevice>("engine:touch_from_button");
335}
336
337std::optional<std::size_t> Controller_Gesture::GetUnusedFingerID() const {
338 // Dont assign any touch input to a point if disabled
339 if (!Settings::values.touchscreen.enabled) {
340 return std::nullopt;
341 }
342 std::size_t first_free_id = 0;
343 while (first_free_id < MAX_POINTS) {
344 if (!fingers[first_free_id].pressed) {
345 return first_free_id;
346 } else {
347 first_free_id++;
348 }
349 }
350 return std::nullopt;
351}
352
353Controller_Gesture::GestureState& Controller_Gesture::GetLastGestureEntry() {
354 return shared_memory.gesture_states[(shared_memory.header.last_entry_index + 16) % 17];
355} 306}
356 307
357const Controller_Gesture::GestureState& Controller_Gesture::GetLastGestureEntry() const { 308const Controller_Gesture::GestureState& Controller_Gesture::GetLastGestureEntry() const {
358 return shared_memory.gesture_states[(shared_memory.header.last_entry_index + 16) % 17]; 309 return gesture_lifo.ReadCurrentEntry().state;
359}
360
361std::size_t Controller_Gesture::UpdateTouchInputEvent(
362 const std::tuple<float, float, bool>& touch_input, std::size_t finger_id) {
363 const auto& [x, y, pressed] = touch_input;
364 if (finger_id > MAX_POINTS) {
365 LOG_ERROR(Service_HID, "Invalid finger id {}", finger_id);
366 return MAX_POINTS;
367 }
368 if (pressed) {
369 if (finger_id == MAX_POINTS) {
370 const auto first_free_id = GetUnusedFingerID();
371 if (!first_free_id) {
372 // Invalid finger id do nothing
373 return MAX_POINTS;
374 }
375 finger_id = first_free_id.value();
376 fingers[finger_id].pressed = true;
377 }
378 fingers[finger_id].pos = {x, y};
379 return finger_id;
380 }
381
382 if (finger_id != MAX_POINTS) {
383 fingers[finger_id].pressed = false;
384 }
385
386 return MAX_POINTS;
387} 310}
388 311
389Controller_Gesture::GestureProperties Controller_Gesture::GetGestureProperties() { 312Controller_Gesture::GestureProperties Controller_Gesture::GetGestureProperties() {
390 GestureProperties gesture; 313 GestureProperties gesture;
391 std::array<Finger, MAX_POINTS> active_fingers; 314 std::array<Core::HID::TouchFinger, MAX_POINTS> active_fingers;
392 const auto end_iter = std::copy_if(fingers.begin(), fingers.end(), active_fingers.begin(), 315 const auto end_iter = std::copy_if(fingers.begin(), fingers.end(), active_fingers.begin(),
393 [](const auto& finger) { return finger.pressed; }); 316 [](const auto& finger) { return finger.pressed; });
394 gesture.active_points = 317 gesture.active_points =
395 static_cast<std::size_t>(std::distance(active_fingers.begin(), end_iter)); 318 static_cast<std::size_t>(std::distance(active_fingers.begin(), end_iter));
396 319
397 for (size_t id = 0; id < gesture.active_points; ++id) { 320 for (size_t id = 0; id < gesture.active_points; ++id) {
398 const auto& [active_x, active_y] = active_fingers[id].pos; 321 const auto& [active_x, active_y] = active_fingers[id].position;
399 gesture.points[id] = { 322 gesture.points[id] = {
400 .x = static_cast<s32>(active_x * Layout::ScreenUndocked::Width), 323 .x = static_cast<s32>(active_x * Layout::ScreenUndocked::Width),
401 .y = static_cast<s32>(active_y * Layout::ScreenUndocked::Height), 324 .y = static_cast<s32>(active_y * Layout::ScreenUndocked::Height),
diff --git a/src/core/hle/service/hid/controllers/gesture.h b/src/core/hle/service/hid/controllers/gesture.h
index 7e7ae6625..0936a3fa3 100644
--- a/src/core/hle/service/hid/controllers/gesture.h
+++ b/src/core/hle/service/hid/controllers/gesture.h
@@ -8,13 +8,14 @@
8#include "common/bit_field.h" 8#include "common/bit_field.h"
9#include "common/common_types.h" 9#include "common/common_types.h"
10#include "common/point.h" 10#include "common/point.h"
11#include "core/frontend/input.h" 11#include "core/hid/emulated_console.h"
12#include "core/hle/service/hid/controllers/controller_base.h" 12#include "core/hle/service/hid/controllers/controller_base.h"
13#include "core/hle/service/hid/ring_lifo.h"
13 14
14namespace Service::HID { 15namespace Service::HID {
15class Controller_Gesture final : public ControllerBase { 16class Controller_Gesture final : public ControllerBase {
16public: 17public:
17 explicit Controller_Gesture(Core::System& system_); 18 explicit Controller_Gesture(Core::HID::HIDCore& hid_core_);
18 ~Controller_Gesture() override; 19 ~Controller_Gesture() override;
19 20
20 // Called when the controller is initialized 21 // Called when the controller is initialized
@@ -26,14 +27,12 @@ public:
26 // When the controller is requesting an update for the shared memory 27 // When the controller is requesting an update for the shared memory
27 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, size_t size) override; 28 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, size_t size) override;
28 29
29 // Called when input devices should be loaded
30 void OnLoadInputDevices() override;
31
32private: 30private:
33 static constexpr size_t MAX_FINGERS = 16; 31 static constexpr size_t MAX_FINGERS = 16;
34 static constexpr size_t MAX_POINTS = 4; 32 static constexpr size_t MAX_POINTS = 4;
35 33
36 enum class TouchType : u32 { 34 // This is nn::hid::GestureType
35 enum class GestureType : u32 {
37 Idle, // Nothing touching the screen 36 Idle, // Nothing touching the screen
38 Complete, // Set at the end of a touch event 37 Complete, // Set at the end of a touch event
39 Cancel, // Set when the number of fingers change 38 Cancel, // Set when the number of fingers change
@@ -46,7 +45,8 @@ private:
46 Rotate, // All points rotating from the midpoint 45 Rotate, // All points rotating from the midpoint
47 }; 46 };
48 47
49 enum class Direction : u32 { 48 // This is nn::hid::GestureDirection
49 enum class GestureDirection : u32 {
50 None, 50 None,
51 Left, 51 Left,
52 Up, 52 Up,
@@ -54,51 +54,41 @@ private:
54 Down, 54 Down,
55 }; 55 };
56 56
57 struct Attribute { 57 // This is nn::hid::GestureAttribute
58 struct GestureAttribute {
58 union { 59 union {
59 u32_le raw{}; 60 u32 raw{};
60 61
61 BitField<4, 1, u32> is_new_touch; 62 BitField<4, 1, u32> is_new_touch;
62 BitField<8, 1, u32> is_double_tap; 63 BitField<8, 1, u32> is_double_tap;
63 }; 64 };
64 }; 65 };
65 static_assert(sizeof(Attribute) == 4, "Attribute is an invalid size"); 66 static_assert(sizeof(GestureAttribute) == 4, "GestureAttribute is an invalid size");
66 67
68 // This is nn::hid::GestureState
67 struct GestureState { 69 struct GestureState {
68 s64_le sampling_number; 70 s64 sampling_number;
69 s64_le sampling_number2; 71 s64 detection_count;
70 s64_le detection_count; 72 GestureType type;
71 TouchType type; 73 GestureDirection direction;
72 Direction direction; 74 Common::Point<s32> pos;
73 Common::Point<s32_le> pos; 75 Common::Point<s32> delta;
74 Common::Point<s32_le> delta;
75 f32 vel_x; 76 f32 vel_x;
76 f32 vel_y; 77 f32 vel_y;
77 Attribute attributes; 78 GestureAttribute attributes;
78 f32 scale; 79 f32 scale;
79 f32 rotation_angle; 80 f32 rotation_angle;
80 s32_le point_count; 81 s32 point_count;
81 std::array<Common::Point<s32_le>, 4> points; 82 std::array<Common::Point<s32>, 4> points;
82 };
83 static_assert(sizeof(GestureState) == 0x68, "GestureState is an invalid size");
84
85 struct SharedMemory {
86 CommonHeader header;
87 std::array<GestureState, 17> gesture_states;
88 };
89 static_assert(sizeof(SharedMemory) == 0x708, "SharedMemory is an invalid size");
90
91 struct Finger {
92 Common::Point<f32> pos{};
93 bool pressed{};
94 }; 83 };
84 static_assert(sizeof(GestureState) == 0x60, "GestureState is an invalid size");
95 85
96 struct GestureProperties { 86 struct GestureProperties {
97 std::array<Common::Point<s32_le>, MAX_POINTS> points{}; 87 std::array<Common::Point<s32>, MAX_POINTS> points{};
98 std::size_t active_points{}; 88 std::size_t active_points{};
99 Common::Point<s32_le> mid_point{}; 89 Common::Point<s32> mid_point{};
100 s64_le detection_count{}; 90 s64 detection_count{};
101 u64_le delta_time{}; 91 u64 delta_time{};
102 f32 average_distance{}; 92 f32 average_distance{};
103 f32 angle{}; 93 f32 angle{};
104 }; 94 };
@@ -114,61 +104,48 @@ private:
114 f32 time_difference); 104 f32 time_difference);
115 105
116 // Initializes new gesture 106 // Initializes new gesture
117 void NewGesture(GestureProperties& gesture, TouchType& type, Attribute& attributes); 107 void NewGesture(GestureProperties& gesture, GestureType& type, GestureAttribute& attributes);
118 108
119 // Updates existing gesture state 109 // Updates existing gesture state
120 void UpdateExistingGesture(GestureProperties& gesture, TouchType& type, f32 time_difference); 110 void UpdateExistingGesture(GestureProperties& gesture, GestureType& type, f32 time_difference);
121 111
122 // Terminates exiting gesture 112 // Terminates exiting gesture
123 void EndGesture(GestureProperties& gesture, GestureProperties& last_gesture_props, 113 void EndGesture(GestureProperties& gesture, GestureProperties& last_gesture_props,
124 TouchType& type, Attribute& attributes, f32 time_difference); 114 GestureType& type, GestureAttribute& attributes, f32 time_difference);
125 115
126 // Set current event to a tap event 116 // Set current event to a tap event
127 void SetTapEvent(GestureProperties& gesture, GestureProperties& last_gesture_props, 117 void SetTapEvent(GestureProperties& gesture, GestureProperties& last_gesture_props,
128 TouchType& type, Attribute& attributes); 118 GestureType& type, GestureAttribute& attributes);
129 119
130 // Calculates and set the extra parameters related to a pan event 120 // Calculates and set the extra parameters related to a pan event
131 void UpdatePanEvent(GestureProperties& gesture, GestureProperties& last_gesture_props, 121 void UpdatePanEvent(GestureProperties& gesture, GestureProperties& last_gesture_props,
132 TouchType& type, f32 time_difference); 122 GestureType& type, f32 time_difference);
133 123
134 // Terminates the pan event 124 // Terminates the pan event
135 void EndPanEvent(GestureProperties& gesture, GestureProperties& last_gesture_props, 125 void EndPanEvent(GestureProperties& gesture, GestureProperties& last_gesture_props,
136 TouchType& type, f32 time_difference); 126 GestureType& type, f32 time_difference);
137 127
138 // Set current event to a swipe event 128 // Set current event to a swipe event
139 void SetSwipeEvent(GestureProperties& gesture, GestureProperties& last_gesture_props, 129 void SetSwipeEvent(GestureProperties& gesture, GestureProperties& last_gesture_props,
140 TouchType& type); 130 GestureType& type);
141
142 // Returns an unused finger id, if there is no fingers available std::nullopt is returned.
143 [[nodiscard]] std::optional<size_t> GetUnusedFingerID() const;
144 131
145 // Retrieves the last gesture entry, as indicated by shared memory indices. 132 // Retrieves the last gesture entry, as indicated by shared memory indices.
146 [[nodiscard]] GestureState& GetLastGestureEntry();
147 [[nodiscard]] const GestureState& GetLastGestureEntry() const; 133 [[nodiscard]] const GestureState& GetLastGestureEntry() const;
148 134
149 /**
150 * If the touch is new it tries to assign a new finger id, if there is no fingers available no
151 * changes will be made. Updates the coordinates if the finger id it's already set. If the touch
152 * ends delays the output by one frame to set the end_touch flag before finally freeing the
153 * finger id
154 */
155 size_t UpdateTouchInputEvent(const std::tuple<float, float, bool>& touch_input,
156 size_t finger_id);
157
158 // Returns the average distance, angle and middle point of the active fingers 135 // Returns the average distance, angle and middle point of the active fingers
159 GestureProperties GetGestureProperties(); 136 GestureProperties GetGestureProperties();
160 137
161 SharedMemory shared_memory{}; 138 // This is nn::hid::detail::GestureLifo
162 std::unique_ptr<Input::TouchDevice> touch_mouse_device; 139 Lifo<GestureState, hid_entry_count> gesture_lifo{};
163 std::unique_ptr<Input::TouchDevice> touch_udp_device; 140 static_assert(sizeof(gesture_lifo) == 0x708, "gesture_lifo is an invalid size");
164 std::unique_ptr<Input::TouchDevice> touch_btn_device; 141 GestureState next_state{};
165 std::array<size_t, MAX_FINGERS> mouse_finger_id{}; 142
166 std::array<size_t, MAX_FINGERS> keyboard_finger_id{}; 143 Core::HID::EmulatedConsole* console;
167 std::array<size_t, MAX_FINGERS> udp_finger_id{}; 144
168 std::array<Finger, MAX_POINTS> fingers{}; 145 std::array<Core::HID::TouchFinger, MAX_POINTS> fingers{};
169 GestureProperties last_gesture{}; 146 GestureProperties last_gesture{};
170 s64_le last_update_timestamp{}; 147 s64 last_update_timestamp{};
171 s64_le last_tap_timestamp{}; 148 s64 last_tap_timestamp{};
172 f32 last_pan_time_difference{}; 149 f32 last_pan_time_difference{};
173 bool force_update{false}; 150 bool force_update{false};
174 bool enable_press_and_tap{false}; 151 bool enable_press_and_tap{false};
diff --git a/src/core/hle/service/hid/controllers/keyboard.cpp b/src/core/hle/service/hid/controllers/keyboard.cpp
index c6c620008..9588a6910 100644
--- a/src/core/hle/service/hid/controllers/keyboard.cpp
+++ b/src/core/hle/service/hid/controllers/keyboard.cpp
@@ -6,13 +6,18 @@
6#include "common/common_types.h" 6#include "common/common_types.h"
7#include "common/settings.h" 7#include "common/settings.h"
8#include "core/core_timing.h" 8#include "core/core_timing.h"
9#include "core/hid/emulated_devices.h"
10#include "core/hid/hid_core.h"
9#include "core/hle/service/hid/controllers/keyboard.h" 11#include "core/hle/service/hid/controllers/keyboard.h"
10 12
11namespace Service::HID { 13namespace Service::HID {
12constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3800; 14constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3800;
13constexpr u8 KEYS_PER_BYTE = 8;
14 15
15Controller_Keyboard::Controller_Keyboard(Core::System& system_) : ControllerBase{system_} {} 16Controller_Keyboard::Controller_Keyboard(Core::HID::HIDCore& hid_core_)
17 : ControllerBase{hid_core_} {
18 emulated_devices = hid_core.GetEmulatedDevices();
19}
20
16Controller_Keyboard::~Controller_Keyboard() = default; 21Controller_Keyboard::~Controller_Keyboard() = default;
17 22
18void Controller_Keyboard::OnInit() {} 23void Controller_Keyboard::OnInit() {}
@@ -21,51 +26,27 @@ void Controller_Keyboard::OnRelease() {}
21 26
22void Controller_Keyboard::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 27void Controller_Keyboard::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
23 std::size_t size) { 28 std::size_t size) {
24 shared_memory.header.timestamp = core_timing.GetCPUTicks();
25 shared_memory.header.total_entry_count = 17;
26
27 if (!IsControllerActivated()) { 29 if (!IsControllerActivated()) {
28 shared_memory.header.entry_count = 0; 30 keyboard_lifo.buffer_count = 0;
29 shared_memory.header.last_entry_index = 0; 31 keyboard_lifo.buffer_tail = 0;
32 std::memcpy(data + SHARED_MEMORY_OFFSET, &keyboard_lifo, sizeof(keyboard_lifo));
30 return; 33 return;
31 } 34 }
32 shared_memory.header.entry_count = 16;
33
34 const auto& last_entry = shared_memory.pad_states[shared_memory.header.last_entry_index];
35 shared_memory.header.last_entry_index = (shared_memory.header.last_entry_index + 1) % 17;
36 auto& cur_entry = shared_memory.pad_states[shared_memory.header.last_entry_index];
37 35
38 cur_entry.sampling_number = last_entry.sampling_number + 1; 36 const auto& last_entry = keyboard_lifo.ReadCurrentEntry().state;
39 cur_entry.sampling_number2 = cur_entry.sampling_number; 37 next_state.sampling_number = last_entry.sampling_number + 1;
40 38
41 cur_entry.key.fill(0);
42 if (Settings::values.keyboard_enabled) { 39 if (Settings::values.keyboard_enabled) {
43 for (std::size_t i = 0; i < keyboard_keys.size(); ++i) { 40 const auto& keyboard_state = emulated_devices->GetKeyboard();
44 auto& entry = cur_entry.key[i / KEYS_PER_BYTE]; 41 const auto& keyboard_modifier_state = emulated_devices->GetKeyboardModifier();
45 entry = static_cast<u8>(entry | (keyboard_keys[i]->GetStatus() << (i % KEYS_PER_BYTE)));
46 }
47 42
48 using namespace Settings::NativeKeyboard; 43 next_state.key = keyboard_state;
49 44 next_state.modifier = keyboard_modifier_state;
50 // TODO: Assign the correct key to all modifiers 45 next_state.attribute.is_connected.Assign(1);
51 cur_entry.modifier.control.Assign(keyboard_mods[LeftControl]->GetStatus());
52 cur_entry.modifier.shift.Assign(keyboard_mods[LeftShift]->GetStatus());
53 cur_entry.modifier.left_alt.Assign(keyboard_mods[LeftAlt]->GetStatus());
54 cur_entry.modifier.right_alt.Assign(keyboard_mods[RightAlt]->GetStatus());
55 cur_entry.modifier.gui.Assign(0);
56 cur_entry.modifier.caps_lock.Assign(keyboard_mods[CapsLock]->GetStatus());
57 cur_entry.modifier.scroll_lock.Assign(keyboard_mods[ScrollLock]->GetStatus());
58 cur_entry.modifier.num_lock.Assign(keyboard_mods[NumLock]->GetStatus());
59 cur_entry.modifier.katakana.Assign(0);
60 cur_entry.modifier.hiragana.Assign(0);
61 } 46 }
62 std::memcpy(data + SHARED_MEMORY_OFFSET, &shared_memory, sizeof(SharedMemory));
63}
64 47
65void Controller_Keyboard::OnLoadInputDevices() { 48 keyboard_lifo.WriteNextEntry(next_state);
66 std::transform(Settings::values.keyboard_keys.begin(), Settings::values.keyboard_keys.end(), 49 std::memcpy(data + SHARED_MEMORY_OFFSET, &keyboard_lifo, sizeof(keyboard_lifo));
67 keyboard_keys.begin(), Input::CreateDevice<Input::ButtonDevice>);
68 std::transform(Settings::values.keyboard_mods.begin(), Settings::values.keyboard_mods.end(),
69 keyboard_mods.begin(), Input::CreateDevice<Input::ButtonDevice>);
70} 50}
51
71} // namespace Service::HID 52} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/keyboard.h b/src/core/hle/service/hid/controllers/keyboard.h
index 172a80e9c..cf62d3896 100644
--- a/src/core/hle/service/hid/controllers/keyboard.h
+++ b/src/core/hle/service/hid/controllers/keyboard.h
@@ -8,15 +8,20 @@
8#include "common/bit_field.h" 8#include "common/bit_field.h"
9#include "common/common_funcs.h" 9#include "common/common_funcs.h"
10#include "common/common_types.h" 10#include "common/common_types.h"
11#include "common/settings.h"
12#include "common/swap.h" 11#include "common/swap.h"
13#include "core/frontend/input.h"
14#include "core/hle/service/hid/controllers/controller_base.h" 12#include "core/hle/service/hid/controllers/controller_base.h"
13#include "core/hle/service/hid/ring_lifo.h"
14
15namespace Core::HID {
16class EmulatedDevices;
17struct KeyboardModifier;
18struct KeyboardKey;
19} // namespace Core::HID
15 20
16namespace Service::HID { 21namespace Service::HID {
17class Controller_Keyboard final : public ControllerBase { 22class Controller_Keyboard final : public ControllerBase {
18public: 23public:
19 explicit Controller_Keyboard(Core::System& system_); 24 explicit Controller_Keyboard(Core::HID::HIDCore& hid_core_);
20 ~Controller_Keyboard() override; 25 ~Controller_Keyboard() override;
21 26
22 // Called when the controller is initialized 27 // Called when the controller is initialized
@@ -28,47 +33,21 @@ public:
28 // When the controller is requesting an update for the shared memory 33 // When the controller is requesting an update for the shared memory
29 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override; 34 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override;
30 35
31 // Called when input devices should be loaded
32 void OnLoadInputDevices() override;
33
34private: 36private:
35 struct Modifiers { 37 // This is nn::hid::detail::KeyboardState
36 union {
37 u32_le raw{};
38 BitField<0, 1, u32> control;
39 BitField<1, 1, u32> shift;
40 BitField<2, 1, u32> left_alt;
41 BitField<3, 1, u32> right_alt;
42 BitField<4, 1, u32> gui;
43 BitField<8, 1, u32> caps_lock;
44 BitField<9, 1, u32> scroll_lock;
45 BitField<10, 1, u32> num_lock;
46 BitField<11, 1, u32> katakana;
47 BitField<12, 1, u32> hiragana;
48 };
49 };
50 static_assert(sizeof(Modifiers) == 0x4, "Modifiers is an invalid size");
51
52 struct KeyboardState { 38 struct KeyboardState {
53 s64_le sampling_number; 39 s64 sampling_number;
54 s64_le sampling_number2; 40 Core::HID::KeyboardModifier modifier;
55 41 Core::HID::KeyboardAttribute attribute;
56 Modifiers modifier; 42 Core::HID::KeyboardKey key;
57 std::array<u8, 32> key;
58 }; 43 };
59 static_assert(sizeof(KeyboardState) == 0x38, "KeyboardState is an invalid size"); 44 static_assert(sizeof(KeyboardState) == 0x30, "KeyboardState is an invalid size");
60 45
61 struct SharedMemory { 46 // This is nn::hid::detail::KeyboardLifo
62 CommonHeader header; 47 Lifo<KeyboardState, hid_entry_count> keyboard_lifo{};
63 std::array<KeyboardState, 17> pad_states; 48 static_assert(sizeof(keyboard_lifo) == 0x3D8, "keyboard_lifo is an invalid size");
64 INSERT_PADDING_BYTES(0x28); 49 KeyboardState next_state{};
65 };
66 static_assert(sizeof(SharedMemory) == 0x400, "SharedMemory is an invalid size");
67 SharedMemory shared_memory{};
68 50
69 std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeKeyboard::NumKeyboardKeys> 51 Core::HID::EmulatedDevices* emulated_devices;
70 keyboard_keys;
71 std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeKeyboard::NumKeyboardMods>
72 keyboard_mods;
73}; 52};
74} // namespace Service::HID 53} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/mouse.cpp b/src/core/hle/service/hid/controllers/mouse.cpp
index 544a71948..ba79888ae 100644
--- a/src/core/hle/service/hid/controllers/mouse.cpp
+++ b/src/core/hle/service/hid/controllers/mouse.cpp
@@ -6,12 +6,17 @@
6#include "common/common_types.h" 6#include "common/common_types.h"
7#include "core/core_timing.h" 7#include "core/core_timing.h"
8#include "core/frontend/emu_window.h" 8#include "core/frontend/emu_window.h"
9#include "core/hid/emulated_devices.h"
10#include "core/hid/hid_core.h"
9#include "core/hle/service/hid/controllers/mouse.h" 11#include "core/hle/service/hid/controllers/mouse.h"
10 12
11namespace Service::HID { 13namespace Service::HID {
12constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3400; 14constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3400;
13 15
14Controller_Mouse::Controller_Mouse(Core::System& system_) : ControllerBase{system_} {} 16Controller_Mouse::Controller_Mouse(Core::HID::HIDCore& hid_core_) : ControllerBase{hid_core_} {
17 emulated_devices = hid_core.GetEmulatedDevices();
18}
19
15Controller_Mouse::~Controller_Mouse() = default; 20Controller_Mouse::~Controller_Mouse() = default;
16 21
17void Controller_Mouse::OnInit() {} 22void Controller_Mouse::OnInit() {}
@@ -19,50 +24,35 @@ void Controller_Mouse::OnRelease() {}
19 24
20void Controller_Mouse::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 25void Controller_Mouse::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
21 std::size_t size) { 26 std::size_t size) {
22 shared_memory.header.timestamp = core_timing.GetCPUTicks();
23 shared_memory.header.total_entry_count = 17;
24
25 if (!IsControllerActivated()) { 27 if (!IsControllerActivated()) {
26 shared_memory.header.entry_count = 0; 28 mouse_lifo.buffer_count = 0;
27 shared_memory.header.last_entry_index = 0; 29 mouse_lifo.buffer_tail = 0;
30 std::memcpy(data + SHARED_MEMORY_OFFSET, &mouse_lifo, sizeof(mouse_lifo));
28 return; 31 return;
29 } 32 }
30 shared_memory.header.entry_count = 16;
31 33
32 auto& last_entry = shared_memory.mouse_states[shared_memory.header.last_entry_index]; 34 const auto& last_entry = mouse_lifo.ReadCurrentEntry().state;
33 shared_memory.header.last_entry_index = (shared_memory.header.last_entry_index + 1) % 17; 35 next_state.sampling_number = last_entry.sampling_number + 1;
34 auto& cur_entry = shared_memory.mouse_states[shared_memory.header.last_entry_index];
35 36
36 cur_entry.sampling_number = last_entry.sampling_number + 1; 37 next_state.attribute.raw = 0;
37 cur_entry.sampling_number2 = cur_entry.sampling_number;
38
39 cur_entry.attribute.raw = 0;
40 if (Settings::values.mouse_enabled) { 38 if (Settings::values.mouse_enabled) {
41 const auto [px, py, sx, sy] = mouse_device->GetStatus(); 39 const auto& mouse_button_state = emulated_devices->GetMouseButtons();
42 const auto x = static_cast<s32>(px * Layout::ScreenUndocked::Width); 40 const auto& mouse_position_state = emulated_devices->GetMousePosition();
43 const auto y = static_cast<s32>(py * Layout::ScreenUndocked::Height); 41 const auto& mouse_wheel_state = emulated_devices->GetMouseWheel();
44 cur_entry.x = x; 42 next_state.attribute.is_connected.Assign(1);
45 cur_entry.y = y; 43 next_state.x = static_cast<s32>(mouse_position_state.x * Layout::ScreenUndocked::Width);
46 cur_entry.delta_x = x - last_entry.x; 44 next_state.y = static_cast<s32>(mouse_position_state.y * Layout::ScreenUndocked::Height);
47 cur_entry.delta_y = y - last_entry.y; 45 next_state.delta_x = next_state.x - last_entry.x;
48 cur_entry.mouse_wheel_x = sx; 46 next_state.delta_y = next_state.y - last_entry.y;
49 cur_entry.mouse_wheel_y = sy; 47 next_state.delta_wheel_x = mouse_wheel_state.x - last_mouse_wheel_state.x;
50 cur_entry.attribute.is_connected.Assign(1); 48 next_state.delta_wheel_y = mouse_wheel_state.y - last_mouse_wheel_state.y;
51 49
52 using namespace Settings::NativeMouseButton; 50 last_mouse_wheel_state = mouse_wheel_state;
53 cur_entry.button.left.Assign(mouse_button_devices[Left]->GetStatus()); 51 next_state.button = mouse_button_state;
54 cur_entry.button.right.Assign(mouse_button_devices[Right]->GetStatus());
55 cur_entry.button.middle.Assign(mouse_button_devices[Middle]->GetStatus());
56 cur_entry.button.forward.Assign(mouse_button_devices[Forward]->GetStatus());
57 cur_entry.button.back.Assign(mouse_button_devices[Back]->GetStatus());
58 } 52 }
59 53
60 std::memcpy(data + SHARED_MEMORY_OFFSET, &shared_memory, sizeof(SharedMemory)); 54 mouse_lifo.WriteNextEntry(next_state);
55 std::memcpy(data + SHARED_MEMORY_OFFSET, &mouse_lifo, sizeof(mouse_lifo));
61} 56}
62 57
63void Controller_Mouse::OnLoadInputDevices() {
64 mouse_device = Input::CreateDevice<Input::MouseDevice>(Settings::values.mouse_device);
65 std::transform(Settings::values.mouse_buttons.begin(), Settings::values.mouse_buttons.end(),
66 mouse_button_devices.begin(), Input::CreateDevice<Input::ButtonDevice>);
67}
68} // namespace Service::HID 58} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/mouse.h b/src/core/hle/service/hid/controllers/mouse.h
index 3d391a798..7559fc78d 100644
--- a/src/core/hle/service/hid/controllers/mouse.h
+++ b/src/core/hle/service/hid/controllers/mouse.h
@@ -7,15 +7,20 @@
7#include <array> 7#include <array>
8#include "common/bit_field.h" 8#include "common/bit_field.h"
9#include "common/common_types.h" 9#include "common/common_types.h"
10#include "common/settings.h"
11#include "common/swap.h" 10#include "common/swap.h"
12#include "core/frontend/input.h"
13#include "core/hle/service/hid/controllers/controller_base.h" 11#include "core/hle/service/hid/controllers/controller_base.h"
12#include "core/hle/service/hid/ring_lifo.h"
13
14namespace Core::HID {
15class EmulatedDevices;
16struct MouseState;
17struct AnalogStickState;
18} // namespace Core::HID
14 19
15namespace Service::HID { 20namespace Service::HID {
16class Controller_Mouse final : public ControllerBase { 21class Controller_Mouse final : public ControllerBase {
17public: 22public:
18 explicit Controller_Mouse(Core::System& system_); 23 explicit Controller_Mouse(Core::HID::HIDCore& hid_core_);
19 ~Controller_Mouse() override; 24 ~Controller_Mouse() override;
20 25
21 // Called when the controller is initialized 26 // Called when the controller is initialized
@@ -27,53 +32,13 @@ public:
27 // When the controller is requesting an update for the shared memory 32 // When the controller is requesting an update for the shared memory
28 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override; 33 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override;
29 34
30 // Called when input devices should be loaded
31 void OnLoadInputDevices() override;
32
33private: 35private:
34 struct Buttons { 36 // This is nn::hid::detail::MouseLifo
35 union { 37 Lifo<Core::HID::MouseState, hid_entry_count> mouse_lifo{};
36 u32_le raw{}; 38 static_assert(sizeof(mouse_lifo) == 0x350, "mouse_lifo is an invalid size");
37 BitField<0, 1, u32> left; 39 Core::HID::MouseState next_state{};
38 BitField<1, 1, u32> right;
39 BitField<2, 1, u32> middle;
40 BitField<3, 1, u32> forward;
41 BitField<4, 1, u32> back;
42 };
43 };
44 static_assert(sizeof(Buttons) == 0x4, "Buttons is an invalid size");
45
46 struct Attributes {
47 union {
48 u32_le raw{};
49 BitField<0, 1, u32> transferable;
50 BitField<1, 1, u32> is_connected;
51 };
52 };
53 static_assert(sizeof(Attributes) == 0x4, "Attributes is an invalid size");
54
55 struct MouseState {
56 s64_le sampling_number;
57 s64_le sampling_number2;
58 s32_le x;
59 s32_le y;
60 s32_le delta_x;
61 s32_le delta_y;
62 s32_le mouse_wheel_x;
63 s32_le mouse_wheel_y;
64 Buttons button;
65 Attributes attribute;
66 };
67 static_assert(sizeof(MouseState) == 0x30, "MouseState is an invalid size");
68
69 struct SharedMemory {
70 CommonHeader header;
71 std::array<MouseState, 17> mouse_states;
72 };
73 SharedMemory shared_memory{};
74 40
75 std::unique_ptr<Input::MouseDevice> mouse_device; 41 Core::HID::AnalogStickState last_mouse_wheel_state;
76 std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeMouseButton::NumMouseButtons> 42 Core::HID::EmulatedDevices* emulated_devices;
77 mouse_button_devices;
78}; 43};
79} // namespace Service::HID 44} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp
index 196876810..dd4d954aa 100644
--- a/src/core/hle/service/hid/controllers/npad.cpp
+++ b/src/core/hle/service/hid/controllers/npad.cpp
@@ -10,9 +10,9 @@
10#include "common/common_types.h" 10#include "common/common_types.h"
11#include "common/logging/log.h" 11#include "common/logging/log.h"
12#include "common/settings.h" 12#include "common/settings.h"
13#include "core/core.h"
14#include "core/core_timing.h" 13#include "core/core_timing.h"
15#include "core/frontend/input.h" 14#include "core/hid/emulated_controller.h"
15#include "core/hid/hid_core.h"
16#include "core/hle/kernel/k_event.h" 16#include "core/hle/kernel/k_event.h"
17#include "core/hle/kernel/k_readable_event.h" 17#include "core/hle/kernel/k_readable_event.h"
18#include "core/hle/kernel/k_writable_event.h" 18#include "core/hle/kernel/k_writable_event.h"
@@ -20,120 +20,26 @@
20#include "core/hle/service/kernel_helpers.h" 20#include "core/hle/service/kernel_helpers.h"
21 21
22namespace Service::HID { 22namespace Service::HID {
23constexpr s32 HID_JOYSTICK_MAX = 0x7fff;
24constexpr s32 HID_TRIGGER_MAX = 0x7fff;
25[[maybe_unused]] constexpr s32 HID_JOYSTICK_MIN = -0x7fff;
26constexpr std::size_t NPAD_OFFSET = 0x9A00; 23constexpr std::size_t NPAD_OFFSET = 0x9A00;
27constexpr u32 BATTERY_FULL = 2; 24constexpr std::array<Core::HID::NpadIdType, 10> npad_id_list{
28constexpr u32 MAX_NPAD_ID = 7; 25 Core::HID::NpadIdType::Player1, Core::HID::NpadIdType::Player2, Core::HID::NpadIdType::Player3,
29constexpr std::size_t HANDHELD_INDEX = 8; 26 Core::HID::NpadIdType::Player4, Core::HID::NpadIdType::Player5, Core::HID::NpadIdType::Player6,
30constexpr std::array<u32, 10> npad_id_list{ 27 Core::HID::NpadIdType::Player7, Core::HID::NpadIdType::Player8, Core::HID::NpadIdType::Other,
31 0, 1, 2, 3, 4, 5, 6, 7, NPAD_HANDHELD, NPAD_UNKNOWN, 28 Core::HID::NpadIdType::Handheld,
32}; 29};
33 30
34enum class JoystickId : std::size_t { 31bool Controller_NPad::IsNpadIdValid(Core::HID::NpadIdType npad_id) {
35 Joystick_Left,
36 Joystick_Right,
37};
38
39Controller_NPad::NPadControllerType Controller_NPad::MapSettingsTypeToNPad(
40 Settings::ControllerType type) {
41 switch (type) {
42 case Settings::ControllerType::ProController:
43 return NPadControllerType::ProController;
44 case Settings::ControllerType::DualJoyconDetached:
45 return NPadControllerType::JoyDual;
46 case Settings::ControllerType::LeftJoycon:
47 return NPadControllerType::JoyLeft;
48 case Settings::ControllerType::RightJoycon:
49 return NPadControllerType::JoyRight;
50 case Settings::ControllerType::Handheld:
51 return NPadControllerType::Handheld;
52 case Settings::ControllerType::GameCube:
53 return NPadControllerType::GameCube;
54 default:
55 UNREACHABLE();
56 return NPadControllerType::ProController;
57 }
58}
59
60Settings::ControllerType Controller_NPad::MapNPadToSettingsType(
61 Controller_NPad::NPadControllerType type) {
62 switch (type) {
63 case NPadControllerType::ProController:
64 return Settings::ControllerType::ProController;
65 case NPadControllerType::JoyDual:
66 return Settings::ControllerType::DualJoyconDetached;
67 case NPadControllerType::JoyLeft:
68 return Settings::ControllerType::LeftJoycon;
69 case NPadControllerType::JoyRight:
70 return Settings::ControllerType::RightJoycon;
71 case NPadControllerType::Handheld:
72 return Settings::ControllerType::Handheld;
73 case NPadControllerType::GameCube:
74 return Settings::ControllerType::GameCube;
75 default:
76 UNREACHABLE();
77 return Settings::ControllerType::ProController;
78 }
79}
80
81std::size_t Controller_NPad::NPadIdToIndex(u32 npad_id) {
82 switch (npad_id) { 32 switch (npad_id) {
83 case 0: 33 case Core::HID::NpadIdType::Player1:
84 case 1: 34 case Core::HID::NpadIdType::Player2:
85 case 2: 35 case Core::HID::NpadIdType::Player3:
86 case 3: 36 case Core::HID::NpadIdType::Player4:
87 case 4: 37 case Core::HID::NpadIdType::Player5:
88 case 5: 38 case Core::HID::NpadIdType::Player6:
89 case 6: 39 case Core::HID::NpadIdType::Player7:
90 case 7: 40 case Core::HID::NpadIdType::Player8:
91 return npad_id; 41 case Core::HID::NpadIdType::Other:
92 case HANDHELD_INDEX: 42 case Core::HID::NpadIdType::Handheld:
93 case NPAD_HANDHELD:
94 return HANDHELD_INDEX;
95 case 9:
96 case NPAD_UNKNOWN:
97 return 9;
98 default:
99 UNIMPLEMENTED_MSG("Unknown npad id {}", npad_id);
100 return 0;
101 }
102}
103
104u32 Controller_NPad::IndexToNPad(std::size_t index) {
105 switch (index) {
106 case 0:
107 case 1:
108 case 2:
109 case 3:
110 case 4:
111 case 5:
112 case 6:
113 case 7:
114 return static_cast<u32>(index);
115 case HANDHELD_INDEX:
116 return NPAD_HANDHELD;
117 case 9:
118 return NPAD_UNKNOWN;
119 default:
120 UNIMPLEMENTED_MSG("Unknown npad index {}", index);
121 return 0;
122 }
123}
124
125bool Controller_NPad::IsNpadIdValid(u32 npad_id) {
126 switch (npad_id) {
127 case 0:
128 case 1:
129 case 2:
130 case 3:
131 case 4:
132 case 5:
133 case 6:
134 case 7:
135 case NPAD_UNKNOWN:
136 case NPAD_HANDHELD:
137 return true; 43 return true;
138 default: 44 default:
139 LOG_ERROR(Service_HID, "Invalid npad id {}", npad_id); 45 LOG_ERROR(Service_HID, "Invalid npad id {}", npad_id);
@@ -141,131 +47,215 @@ bool Controller_NPad::IsNpadIdValid(u32 npad_id) {
141 } 47 }
142} 48}
143 49
144bool Controller_NPad::IsDeviceHandleValid(const DeviceHandle& device_handle) { 50bool Controller_NPad::IsDeviceHandleValid(const Core::HID::VibrationDeviceHandle& device_handle) {
145 return IsNpadIdValid(device_handle.npad_id) && 51 return IsNpadIdValid(static_cast<Core::HID::NpadIdType>(device_handle.npad_id)) &&
146 device_handle.npad_type < NpadType::MaxNpadType && 52 device_handle.npad_type < Core::HID::NpadStyleIndex::MaxNpadType &&
147 device_handle.device_index < DeviceIndex::MaxDeviceIndex; 53 device_handle.device_index < Core::HID::DeviceIndex::MaxDeviceIndex;
54}
55
56bool Controller_NPad::IsDeviceHandleValid(const Core::HID::SixAxisSensorHandle& device_handle) {
57 return IsNpadIdValid(static_cast<Core::HID::NpadIdType>(device_handle.npad_id)) &&
58 device_handle.npad_type < Core::HID::NpadStyleIndex::MaxNpadType &&
59 device_handle.device_index < Core::HID::DeviceIndex::MaxDeviceIndex;
148} 60}
149 61
150Controller_NPad::Controller_NPad(Core::System& system_, 62Controller_NPad::Controller_NPad(Core::HID::HIDCore& hid_core_,
151 KernelHelpers::ServiceContext& service_context_) 63 KernelHelpers::ServiceContext& service_context_)
152 : ControllerBase{system_}, service_context{service_context_} { 64 : ControllerBase{hid_core_}, service_context{service_context_} {
153 latest_vibration_values.fill({DEFAULT_VIBRATION_VALUE, DEFAULT_VIBRATION_VALUE}); 65 for (std::size_t i = 0; i < controller_data.size(); ++i) {
66 auto& controller = controller_data[i];
67 controller.device = hid_core.GetEmulatedControllerByIndex(i);
68 controller.vibration[Core::HID::EmulatedDeviceIndex::LeftIndex].latest_vibration_value =
69 DEFAULT_VIBRATION_VALUE;
70 controller.vibration[Core::HID::EmulatedDeviceIndex::RightIndex].latest_vibration_value =
71 DEFAULT_VIBRATION_VALUE;
72 Core::HID::ControllerUpdateCallback engine_callback{
73 .on_change = [this,
74 i](Core::HID::ControllerTriggerType type) { ControllerUpdate(type, i); },
75 .is_npad_service = true,
76 };
77 controller.callback_key = controller.device->SetCallback(engine_callback);
78 }
154} 79}
155 80
156Controller_NPad::~Controller_NPad() { 81Controller_NPad::~Controller_NPad() {
82 for (std::size_t i = 0; i < controller_data.size(); ++i) {
83 auto& controller = controller_data[i];
84 controller.device->DeleteCallback(controller.callback_key);
85 }
157 OnRelease(); 86 OnRelease();
158} 87}
159 88
160void Controller_NPad::InitNewlyAddedController(std::size_t controller_idx) { 89void Controller_NPad::ControllerUpdate(Core::HID::ControllerTriggerType type,
161 const auto controller_type = connected_controllers[controller_idx].type; 90 std::size_t controller_idx) {
162 auto& controller = shared_memory_entries[controller_idx]; 91 if (type == Core::HID::ControllerTriggerType::All) {
163 if (controller_type == NPadControllerType::None) { 92 ControllerUpdate(Core::HID::ControllerTriggerType::Connected, controller_idx);
164 styleset_changed_events[controller_idx]->GetWritableEvent().Signal(); 93 ControllerUpdate(Core::HID::ControllerTriggerType::Battery, controller_idx);
165 return; 94 return;
166 } 95 }
167 controller.style_set.raw = 0; // Zero out 96 if (controller_idx >= controller_data.size()) {
168 controller.device_type.raw = 0; 97 return;
169 controller.system_properties.raw = 0; 98 }
99
100 auto& controller = controller_data[controller_idx];
101 const auto is_connected = controller.device->IsConnected();
102 const auto npad_type = controller.device->GetNpadStyleIndex();
103 const auto npad_id = controller.device->GetNpadIdType();
104 switch (type) {
105 case Core::HID::ControllerTriggerType::Connected:
106 case Core::HID::ControllerTriggerType::Disconnected:
107 if (is_connected == controller.is_connected) {
108 return;
109 }
110 UpdateControllerAt(npad_type, npad_id, is_connected);
111 break;
112 case Core::HID::ControllerTriggerType::Battery: {
113 if (!controller.is_connected) {
114 return;
115 }
116 auto& shared_memory = controller.shared_memory_entry;
117 const auto& battery_level = controller.device->GetBattery();
118 shared_memory.battery_level_dual = battery_level.dual.battery_level;
119 shared_memory.battery_level_left = battery_level.left.battery_level;
120 shared_memory.battery_level_right = battery_level.right.battery_level;
121 break;
122 }
123 default:
124 break;
125 }
126}
127
128void Controller_NPad::InitNewlyAddedController(Core::HID::NpadIdType npad_id) {
129 LOG_DEBUG(Service_HID, "Npad connected {}", npad_id);
130 auto& controller = GetControllerFromNpadIdType(npad_id);
131 const auto controller_type = controller.device->GetNpadStyleIndex();
132 auto& shared_memory = controller.shared_memory_entry;
133 if (controller_type == Core::HID::NpadStyleIndex::None) {
134 controller.styleset_changed_event->GetWritableEvent().Signal();
135 return;
136 }
137 shared_memory.style_tag.raw = Core::HID::NpadStyleSet::None;
138 shared_memory.device_type.raw = 0;
139 shared_memory.system_properties.raw = 0;
170 switch (controller_type) { 140 switch (controller_type) {
171 case NPadControllerType::None: 141 case Core::HID::NpadStyleIndex::None:
172 UNREACHABLE(); 142 UNREACHABLE();
173 break; 143 break;
174 case NPadControllerType::ProController: 144 case Core::HID::NpadStyleIndex::ProController:
175 controller.style_set.fullkey.Assign(1); 145 shared_memory.style_tag.fullkey.Assign(1);
176 controller.device_type.fullkey.Assign(1); 146 shared_memory.device_type.fullkey.Assign(1);
177 controller.system_properties.is_vertical.Assign(1); 147 shared_memory.system_properties.is_vertical.Assign(1);
178 controller.system_properties.use_plus.Assign(1); 148 shared_memory.system_properties.use_plus.Assign(1);
179 controller.system_properties.use_minus.Assign(1); 149 shared_memory.system_properties.use_minus.Assign(1);
180 controller.assignment_mode = NpadAssignments::Single; 150 shared_memory.assignment_mode = NpadJoyAssignmentMode::Single;
181 controller.footer_type = AppletFooterUiType::SwitchProController; 151 shared_memory.applet_footer.type = AppletFooterUiType::SwitchProController;
152 break;
153 case Core::HID::NpadStyleIndex::Handheld:
154 shared_memory.style_tag.handheld.Assign(1);
155 shared_memory.device_type.handheld_left.Assign(1);
156 shared_memory.device_type.handheld_right.Assign(1);
157 shared_memory.system_properties.is_vertical.Assign(1);
158 shared_memory.system_properties.use_plus.Assign(1);
159 shared_memory.system_properties.use_minus.Assign(1);
160 shared_memory.system_properties.use_directional_buttons.Assign(1);
161 shared_memory.assignment_mode = NpadJoyAssignmentMode::Dual;
162 shared_memory.applet_footer.type = AppletFooterUiType::HandheldJoyConLeftJoyConRight;
163 break;
164 case Core::HID::NpadStyleIndex::JoyconDual:
165 shared_memory.style_tag.joycon_dual.Assign(1);
166 shared_memory.device_type.joycon_left.Assign(1);
167 shared_memory.device_type.joycon_right.Assign(1);
168 shared_memory.system_properties.is_vertical.Assign(1);
169 shared_memory.system_properties.use_plus.Assign(1);
170 shared_memory.system_properties.use_minus.Assign(1);
171 shared_memory.system_properties.use_directional_buttons.Assign(1);
172 shared_memory.assignment_mode = NpadJoyAssignmentMode::Dual;
173 shared_memory.applet_footer.type = AppletFooterUiType::JoyDual;
182 break; 174 break;
183 case NPadControllerType::Handheld: 175 case Core::HID::NpadStyleIndex::JoyconLeft:
184 controller.style_set.handheld.Assign(1); 176 shared_memory.style_tag.joycon_left.Assign(1);
185 controller.device_type.handheld_left.Assign(1); 177 shared_memory.device_type.joycon_left.Assign(1);
186 controller.device_type.handheld_right.Assign(1); 178 shared_memory.system_properties.is_horizontal.Assign(1);
187 controller.system_properties.is_vertical.Assign(1); 179 shared_memory.system_properties.use_minus.Assign(1);
188 controller.system_properties.use_plus.Assign(1); 180 shared_memory.assignment_mode = NpadJoyAssignmentMode::Single;
189 controller.system_properties.use_minus.Assign(1); 181 shared_memory.applet_footer.type = AppletFooterUiType::JoyLeftHorizontal;
190 controller.assignment_mode = NpadAssignments::Dual;
191 controller.footer_type = AppletFooterUiType::HandheldJoyConLeftJoyConRight;
192 break; 182 break;
193 case NPadControllerType::JoyDual: 183 case Core::HID::NpadStyleIndex::JoyconRight:
194 controller.style_set.joycon_dual.Assign(1); 184 shared_memory.style_tag.joycon_right.Assign(1);
195 controller.device_type.joycon_left.Assign(1); 185 shared_memory.device_type.joycon_right.Assign(1);
196 controller.device_type.joycon_right.Assign(1); 186 shared_memory.system_properties.is_horizontal.Assign(1);
197 controller.system_properties.is_vertical.Assign(1); 187 shared_memory.system_properties.use_plus.Assign(1);
198 controller.system_properties.use_plus.Assign(1); 188 shared_memory.assignment_mode = NpadJoyAssignmentMode::Single;
199 controller.system_properties.use_minus.Assign(1); 189 shared_memory.applet_footer.type = AppletFooterUiType::JoyRightHorizontal;
200 controller.assignment_mode = NpadAssignments::Dual;
201 controller.footer_type = AppletFooterUiType::JoyDual;
202 break; 190 break;
203 case NPadControllerType::JoyLeft: 191 case Core::HID::NpadStyleIndex::GameCube:
204 controller.style_set.joycon_left.Assign(1); 192 shared_memory.style_tag.gamecube.Assign(1);
205 controller.device_type.joycon_left.Assign(1); 193 shared_memory.device_type.fullkey.Assign(1);
206 controller.system_properties.is_horizontal.Assign(1); 194 shared_memory.system_properties.is_vertical.Assign(1);
207 controller.system_properties.use_minus.Assign(1); 195 shared_memory.system_properties.use_plus.Assign(1);
208 controller.assignment_mode = NpadAssignments::Single;
209 controller.footer_type = AppletFooterUiType::JoyLeftHorizontal;
210 break; 196 break;
211 case NPadControllerType::JoyRight: 197 case Core::HID::NpadStyleIndex::Pokeball:
212 controller.style_set.joycon_right.Assign(1); 198 shared_memory.style_tag.palma.Assign(1);
213 controller.device_type.joycon_right.Assign(1); 199 shared_memory.device_type.palma.Assign(1);
214 controller.system_properties.is_horizontal.Assign(1); 200 shared_memory.assignment_mode = NpadJoyAssignmentMode::Single;
215 controller.system_properties.use_plus.Assign(1);
216 controller.assignment_mode = NpadAssignments::Single;
217 controller.footer_type = AppletFooterUiType::JoyRightHorizontal;
218 break; 201 break;
219 case NPadControllerType::GameCube: 202 case Core::HID::NpadStyleIndex::NES:
220 controller.style_set.gamecube.Assign(1); 203 shared_memory.style_tag.lark.Assign(1);
221 // The GC Controller behaves like a wired Pro Controller 204 shared_memory.device_type.fullkey.Assign(1);
222 controller.device_type.fullkey.Assign(1);
223 controller.system_properties.is_vertical.Assign(1);
224 controller.system_properties.use_plus.Assign(1);
225 break; 205 break;
226 case NPadControllerType::Pokeball: 206 case Core::HID::NpadStyleIndex::SNES:
227 controller.style_set.palma.Assign(1); 207 shared_memory.style_tag.lucia.Assign(1);
228 controller.device_type.palma.Assign(1); 208 shared_memory.device_type.fullkey.Assign(1);
229 controller.assignment_mode = NpadAssignments::Single; 209 shared_memory.applet_footer.type = AppletFooterUiType::Lucia;
210 break;
211 case Core::HID::NpadStyleIndex::N64:
212 shared_memory.style_tag.lagoon.Assign(1);
213 shared_memory.device_type.fullkey.Assign(1);
214 shared_memory.applet_footer.type = AppletFooterUiType::Lagon;
215 break;
216 case Core::HID::NpadStyleIndex::SegaGenesis:
217 shared_memory.style_tag.lager.Assign(1);
218 shared_memory.device_type.fullkey.Assign(1);
219 break;
220 default:
230 break; 221 break;
231 } 222 }
232 223
233 controller.fullkey_color.attribute = ColorAttributes::Ok; 224 const auto& body_colors = controller.device->GetColors();
234 controller.fullkey_color.fullkey.body = 0;
235 controller.fullkey_color.fullkey.button = 0;
236 225
237 controller.joycon_color.attribute = ColorAttributes::Ok; 226 shared_memory.fullkey_color.attribute = ColorAttribute::Ok;
238 controller.joycon_color.left.body = 227 shared_memory.fullkey_color.fullkey = body_colors.fullkey;
239 Settings::values.players.GetValue()[controller_idx].body_color_left;
240 controller.joycon_color.left.button =
241 Settings::values.players.GetValue()[controller_idx].button_color_left;
242 controller.joycon_color.right.body =
243 Settings::values.players.GetValue()[controller_idx].body_color_right;
244 controller.joycon_color.right.button =
245 Settings::values.players.GetValue()[controller_idx].button_color_right;
246 228
247 // TODO: Investigate when we should report all batery types 229 shared_memory.joycon_color.attribute = ColorAttribute::Ok;
248 controller.battery_level_dual = BATTERY_FULL; 230 shared_memory.joycon_color.left = body_colors.left;
249 controller.battery_level_left = BATTERY_FULL; 231 shared_memory.joycon_color.right = body_colors.right;
250 controller.battery_level_right = BATTERY_FULL;
251 232
252 SignalStyleSetChangedEvent(IndexToNPad(controller_idx)); 233 // TODO: Investigate when we should report all batery types
234 const auto& battery_level = controller.device->GetBattery();
235 shared_memory.battery_level_dual = battery_level.dual.battery_level;
236 shared_memory.battery_level_left = battery_level.left.battery_level;
237 shared_memory.battery_level_right = battery_level.right.battery_level;
238
239 controller.is_connected = true;
240 controller.device->Connect();
241 SignalStyleSetChangedEvent(npad_id);
242 WriteEmptyEntry(controller.shared_memory_entry);
253} 243}
254 244
255void Controller_NPad::OnInit() { 245void Controller_NPad::OnInit() {
256 for (std::size_t i = 0; i < styleset_changed_events.size(); ++i) {
257 styleset_changed_events[i] =
258 service_context.CreateEvent(fmt::format("npad:NpadStyleSetChanged_{}", i));
259 }
260
261 if (!IsControllerActivated()) { 246 if (!IsControllerActivated()) {
262 return; 247 return;
263 } 248 }
264 249
265 OnLoadInputDevices(); 250 for (std::size_t i = 0; i < controller_data.size(); ++i) {
251 auto& controller = controller_data[i];
252 controller.styleset_changed_event =
253 service_context.CreateEvent(fmt::format("npad:NpadStyleSetChanged_{}", i));
254 }
266 255
267 if (style.raw == 0) { 256 if (hid_core.GetSupportedStyleTag().raw == Core::HID::NpadStyleSet::None) {
268 // We want to support all controllers 257 // We want to support all controllers
258 Core::HID::NpadStyleTag style{};
269 style.handheld.Assign(1); 259 style.handheld.Assign(1);
270 style.joycon_left.Assign(1); 260 style.joycon_left.Assign(1);
271 style.joycon_right.Assign(1); 261 style.joycon_right.Assign(1);
@@ -273,173 +263,120 @@ void Controller_NPad::OnInit() {
273 style.fullkey.Assign(1); 263 style.fullkey.Assign(1);
274 style.gamecube.Assign(1); 264 style.gamecube.Assign(1);
275 style.palma.Assign(1); 265 style.palma.Assign(1);
266 hid_core.SetSupportedStyleTag(style);
276 } 267 }
277 268
278 std::transform(Settings::values.players.GetValue().begin(), 269 supported_npad_id_types.resize(npad_id_list.size());
279 Settings::values.players.GetValue().end(), connected_controllers.begin(), 270 std::memcpy(supported_npad_id_types.data(), npad_id_list.data(),
280 [](const Settings::PlayerInput& player) { 271 npad_id_list.size() * sizeof(Core::HID::NpadIdType));
281 return ControllerHolder{MapSettingsTypeToNPad(player.controller_type), 272
282 player.connected}; 273 // Prefill controller buffers
283 }); 274 for (auto& controller : controller_data) {
284 275 auto& npad = controller.shared_memory_entry;
285 // Connect the Player 1 or Handheld controller if none are connected. 276 npad.fullkey_color = {
286 if (std::none_of(connected_controllers.begin(), connected_controllers.end(), 277 .attribute = ColorAttribute::NoController,
287 [](const ControllerHolder& controller) { return controller.is_connected; })) { 278 .fullkey = {},
288 const auto controller = 279 };
289 MapSettingsTypeToNPad(Settings::values.players.GetValue()[0].controller_type); 280 npad.joycon_color = {
290 if (controller == NPadControllerType::Handheld) { 281 .attribute = ColorAttribute::NoController,
291 Settings::values.players.GetValue()[HANDHELD_INDEX].connected = true; 282 .left = {},
292 connected_controllers[HANDHELD_INDEX] = {controller, true}; 283 .right = {},
293 } else { 284 };
294 Settings::values.players.GetValue()[0].connected = true; 285 // HW seems to initialize the first 19 entries
295 connected_controllers[0] = {controller, true}; 286 for (std::size_t i = 0; i < 19; ++i) {
287 WriteEmptyEntry(npad);
296 } 288 }
297 } 289 }
298 290
299 // Account for handheld 291 // Connect controllers
300 if (connected_controllers[HANDHELD_INDEX].is_connected) { 292 for (auto& controller : controller_data) {
301 connected_controllers[HANDHELD_INDEX].type = NPadControllerType::Handheld; 293 const auto& device = controller.device;
294 if (device->IsConnected()) {
295 AddNewControllerAt(device->GetNpadStyleIndex(), device->GetNpadIdType());
296 }
302 } 297 }
298}
303 299
304 supported_npad_id_types.resize(npad_id_list.size()); 300void Controller_NPad::WriteEmptyEntry(NpadInternalState& npad) {
305 std::memcpy(supported_npad_id_types.data(), npad_id_list.data(), 301 NPadGenericState dummy_pad_state{};
306 npad_id_list.size() * sizeof(u32)); 302 NpadGcTriggerState dummy_gc_state{};
303 dummy_pad_state.sampling_number = npad.fullkey_lifo.ReadCurrentEntry().sampling_number + 1;
304 npad.fullkey_lifo.WriteNextEntry(dummy_pad_state);
305 dummy_pad_state.sampling_number = npad.handheld_lifo.ReadCurrentEntry().sampling_number + 1;
306 npad.handheld_lifo.WriteNextEntry(dummy_pad_state);
307 dummy_pad_state.sampling_number = npad.joy_dual_lifo.ReadCurrentEntry().sampling_number + 1;
308 npad.joy_dual_lifo.WriteNextEntry(dummy_pad_state);
309 dummy_pad_state.sampling_number = npad.joy_left_lifo.ReadCurrentEntry().sampling_number + 1;
310 npad.joy_left_lifo.WriteNextEntry(dummy_pad_state);
311 dummy_pad_state.sampling_number = npad.joy_right_lifo.ReadCurrentEntry().sampling_number + 1;
312 npad.joy_right_lifo.WriteNextEntry(dummy_pad_state);
313 dummy_pad_state.sampling_number = npad.palma_lifo.ReadCurrentEntry().sampling_number + 1;
314 npad.palma_lifo.WriteNextEntry(dummy_pad_state);
315 dummy_pad_state.sampling_number = npad.system_ext_lifo.ReadCurrentEntry().sampling_number + 1;
316 npad.system_ext_lifo.WriteNextEntry(dummy_pad_state);
317 dummy_gc_state.sampling_number = npad.gc_trigger_lifo.ReadCurrentEntry().sampling_number + 1;
318 npad.gc_trigger_lifo.WriteNextEntry(dummy_gc_state);
319}
307 320
308 for (std::size_t i = 0; i < connected_controllers.size(); ++i) { 321void Controller_NPad::OnRelease() {
309 const auto& controller = connected_controllers[i]; 322 for (std::size_t i = 0; i < controller_data.size(); ++i) {
310 if (controller.is_connected) { 323 auto& controller = controller_data[i];
311 AddNewControllerAt(controller.type, i); 324 service_context.CloseEvent(controller.styleset_changed_event);
325 for (std::size_t device_idx = 0; device_idx < controller.vibration.size(); ++device_idx) {
326 VibrateControllerAtIndex(controller.device->GetNpadIdType(), device_idx, {});
312 } 327 }
313 } 328 }
314} 329}
315 330
316void Controller_NPad::OnLoadInputDevices() { 331void Controller_NPad::RequestPadStateUpdate(Core::HID::NpadIdType npad_id) {
317 const auto& players = Settings::values.players.GetValue();
318
319 std::lock_guard lock{mutex}; 332 std::lock_guard lock{mutex};
320 for (std::size_t i = 0; i < players.size(); ++i) { 333 auto& controller = GetControllerFromNpadIdType(npad_id);
321 std::transform(players[i].buttons.begin() + Settings::NativeButton::BUTTON_HID_BEGIN, 334 const auto controller_type = controller.device->GetNpadStyleIndex();
322 players[i].buttons.begin() + Settings::NativeButton::BUTTON_HID_END, 335 if (!controller.device->IsConnected()) {
323 buttons[i].begin(), Input::CreateDevice<Input::ButtonDevice>); 336 return;
324 std::transform(players[i].analogs.begin() + Settings::NativeAnalog::STICK_HID_BEGIN,
325 players[i].analogs.begin() + Settings::NativeAnalog::STICK_HID_END,
326 sticks[i].begin(), Input::CreateDevice<Input::AnalogDevice>);
327 std::transform(players[i].vibrations.begin() +
328 Settings::NativeVibration::VIBRATION_HID_BEGIN,
329 players[i].vibrations.begin() + Settings::NativeVibration::VIBRATION_HID_END,
330 vibrations[i].begin(), Input::CreateDevice<Input::VibrationDevice>);
331 std::transform(players[i].motions.begin() + Settings::NativeMotion::MOTION_HID_BEGIN,
332 players[i].motions.begin() + Settings::NativeMotion::MOTION_HID_END,
333 motions[i].begin(), Input::CreateDevice<Input::MotionDevice>);
334 for (std::size_t device_idx = 0; device_idx < vibrations[i].size(); ++device_idx) {
335 InitializeVibrationDeviceAtIndex(i, device_idx);
336 }
337 } 337 }
338}
339 338
340void Controller_NPad::OnRelease() { 339 auto& pad_entry = controller.npad_pad_state;
341 for (std::size_t npad_idx = 0; npad_idx < vibrations.size(); ++npad_idx) { 340 auto& trigger_entry = controller.npad_trigger_state;
342 for (std::size_t device_idx = 0; device_idx < vibrations[npad_idx].size(); ++device_idx) { 341 const auto button_state = controller.device->GetNpadButtons();
343 VibrateControllerAtIndex(npad_idx, device_idx, {}); 342 const auto stick_state = controller.device->GetSticks();
344 } 343
344 using btn = Core::HID::NpadButton;
345 pad_entry.npad_buttons.raw = btn::None;
346 if (controller_type != Core::HID::NpadStyleIndex::JoyconLeft) {
347 constexpr btn right_button_mask = btn::A | btn::B | btn::X | btn::Y | btn::StickR | btn::R |
348 btn::ZR | btn::Plus | btn::StickRLeft | btn::StickRUp |
349 btn::StickRRight | btn::StickRDown;
350 pad_entry.npad_buttons.raw = button_state.raw & right_button_mask;
351 pad_entry.r_stick = stick_state.right;
345 } 352 }
346 353
347 for (std::size_t i = 0; i < styleset_changed_events.size(); ++i) { 354 if (controller_type != Core::HID::NpadStyleIndex::JoyconRight) {
348 service_context.CloseEvent(styleset_changed_events[i]); 355 constexpr btn left_button_mask =
356 btn::Left | btn::Up | btn::Right | btn::Down | btn::StickL | btn::L | btn::ZL |
357 btn::Minus | btn::StickLLeft | btn::StickLUp | btn::StickLRight | btn::StickLDown;
358 pad_entry.npad_buttons.raw |= button_state.raw & left_button_mask;
359 pad_entry.l_stick = stick_state.left;
349 } 360 }
350}
351 361
352void Controller_NPad::RequestPadStateUpdate(u32 npad_id) { 362 if (controller_type == Core::HID::NpadStyleIndex::JoyconLeft) {
353 std::lock_guard lock{mutex}; 363 pad_entry.npad_buttons.left_sl.Assign(button_state.left_sl);
364 pad_entry.npad_buttons.left_sr.Assign(button_state.left_sr);
365 }
354 366
355 const auto controller_idx = NPadIdToIndex(npad_id); 367 if (controller_type == Core::HID::NpadStyleIndex::JoyconRight) {
356 const auto controller_type = connected_controllers[controller_idx].type; 368 pad_entry.npad_buttons.right_sl.Assign(button_state.right_sl);
357 if (!connected_controllers[controller_idx].is_connected) { 369 pad_entry.npad_buttons.right_sr.Assign(button_state.right_sr);
358 return;
359 } 370 }
360 auto& pad_state = npad_pad_states[controller_idx].pad_states; 371
361 auto& lstick_entry = npad_pad_states[controller_idx].l_stick; 372 if (controller_type == Core::HID::NpadStyleIndex::GameCube) {
362 auto& rstick_entry = npad_pad_states[controller_idx].r_stick; 373 const auto& trigger_state = controller.device->GetTriggers();
363 auto& trigger_entry = npad_trigger_states[controller_idx]; 374 trigger_entry.l_analog = trigger_state.left;
364 const auto& button_state = buttons[controller_idx]; 375 trigger_entry.r_analog = trigger_state.right;
365 const auto& analog_state = sticks[controller_idx]; 376 pad_entry.npad_buttons.zl.Assign(false);
366 const auto [stick_l_x_f, stick_l_y_f] = 377 pad_entry.npad_buttons.zr.Assign(button_state.r);
367 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Left)]->GetStatus(); 378 pad_entry.npad_buttons.l.Assign(button_state.zl);
368 const auto [stick_r_x_f, stick_r_y_f] = 379 pad_entry.npad_buttons.r.Assign(button_state.zr);
369 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Right)]->GetStatus();
370
371 using namespace Settings::NativeButton;
372 if (controller_type != NPadControllerType::JoyLeft) {
373 pad_state.a.Assign(button_state[A - BUTTON_HID_BEGIN]->GetStatus());
374 pad_state.b.Assign(button_state[B - BUTTON_HID_BEGIN]->GetStatus());
375 pad_state.x.Assign(button_state[X - BUTTON_HID_BEGIN]->GetStatus());
376 pad_state.y.Assign(button_state[Y - BUTTON_HID_BEGIN]->GetStatus());
377 pad_state.r_stick.Assign(button_state[RStick - BUTTON_HID_BEGIN]->GetStatus());
378 pad_state.r.Assign(button_state[R - BUTTON_HID_BEGIN]->GetStatus());
379 pad_state.zr.Assign(button_state[ZR - BUTTON_HID_BEGIN]->GetStatus());
380 pad_state.plus.Assign(button_state[Plus - BUTTON_HID_BEGIN]->GetStatus());
381
382 pad_state.r_stick_right.Assign(
383 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Right)]
384 ->GetAnalogDirectionStatus(Input::AnalogDirection::RIGHT));
385 pad_state.r_stick_left.Assign(
386 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Right)]
387 ->GetAnalogDirectionStatus(Input::AnalogDirection::LEFT));
388 pad_state.r_stick_up.Assign(
389 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Right)]
390 ->GetAnalogDirectionStatus(Input::AnalogDirection::UP));
391 pad_state.r_stick_down.Assign(
392 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Right)]
393 ->GetAnalogDirectionStatus(Input::AnalogDirection::DOWN));
394 rstick_entry.x = static_cast<s32>(stick_r_x_f * HID_JOYSTICK_MAX);
395 rstick_entry.y = static_cast<s32>(stick_r_y_f * HID_JOYSTICK_MAX);
396 }
397
398 if (controller_type != NPadControllerType::JoyRight) {
399 pad_state.d_left.Assign(button_state[DLeft - BUTTON_HID_BEGIN]->GetStatus());
400 pad_state.d_up.Assign(button_state[DUp - BUTTON_HID_BEGIN]->GetStatus());
401 pad_state.d_right.Assign(button_state[DRight - BUTTON_HID_BEGIN]->GetStatus());
402 pad_state.d_down.Assign(button_state[DDown - BUTTON_HID_BEGIN]->GetStatus());
403 pad_state.l_stick.Assign(button_state[LStick - BUTTON_HID_BEGIN]->GetStatus());
404 pad_state.l.Assign(button_state[L - BUTTON_HID_BEGIN]->GetStatus());
405 pad_state.zl.Assign(button_state[ZL - BUTTON_HID_BEGIN]->GetStatus());
406 pad_state.minus.Assign(button_state[Minus - BUTTON_HID_BEGIN]->GetStatus());
407
408 pad_state.l_stick_right.Assign(
409 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Left)]
410 ->GetAnalogDirectionStatus(Input::AnalogDirection::RIGHT));
411 pad_state.l_stick_left.Assign(
412 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Left)]
413 ->GetAnalogDirectionStatus(Input::AnalogDirection::LEFT));
414 pad_state.l_stick_up.Assign(
415 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Left)]
416 ->GetAnalogDirectionStatus(Input::AnalogDirection::UP));
417 pad_state.l_stick_down.Assign(
418 analog_state[static_cast<std::size_t>(JoystickId::Joystick_Left)]
419 ->GetAnalogDirectionStatus(Input::AnalogDirection::DOWN));
420 lstick_entry.x = static_cast<s32>(stick_l_x_f * HID_JOYSTICK_MAX);
421 lstick_entry.y = static_cast<s32>(stick_l_y_f * HID_JOYSTICK_MAX);
422 }
423
424 if (controller_type == NPadControllerType::JoyLeft) {
425 pad_state.left_sl.Assign(button_state[SL - BUTTON_HID_BEGIN]->GetStatus());
426 pad_state.left_sr.Assign(button_state[SR - BUTTON_HID_BEGIN]->GetStatus());
427 }
428
429 if (controller_type == NPadControllerType::JoyRight) {
430 pad_state.right_sl.Assign(button_state[SL - BUTTON_HID_BEGIN]->GetStatus());
431 pad_state.right_sr.Assign(button_state[SR - BUTTON_HID_BEGIN]->GetStatus());
432 }
433
434 if (controller_type == NPadControllerType::GameCube) {
435 trigger_entry.l_analog = static_cast<s32>(
436 button_state[ZL - BUTTON_HID_BEGIN]->GetStatus() ? HID_TRIGGER_MAX : 0);
437 trigger_entry.r_analog = static_cast<s32>(
438 button_state[ZR - BUTTON_HID_BEGIN]->GetStatus() ? HID_TRIGGER_MAX : 0);
439 pad_state.zl.Assign(false);
440 pad_state.zr.Assign(button_state[R - BUTTON_HID_BEGIN]->GetStatus());
441 pad_state.l.Assign(button_state[ZL - BUTTON_HID_BEGIN]->GetStatus());
442 pad_state.r.Assign(button_state[ZR - BUTTON_HID_BEGIN]->GetStatus());
443 } 380 }
444} 381}
445 382
@@ -448,173 +385,132 @@ void Controller_NPad::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8*
448 if (!IsControllerActivated()) { 385 if (!IsControllerActivated()) {
449 return; 386 return;
450 } 387 }
451 for (std::size_t i = 0; i < shared_memory_entries.size(); ++i) {
452 auto& npad = shared_memory_entries[i];
453 const std::array<NPadGeneric*, 7> controller_npads{
454 &npad.fullkey_states, &npad.handheld_states, &npad.joy_dual_states,
455 &npad.joy_left_states, &npad.joy_right_states, &npad.palma_states,
456 &npad.system_ext_states};
457
458 // There is the posibility to have more controllers with analog triggers
459 const std::array<TriggerGeneric*, 1> controller_triggers{
460 &npad.gc_trigger_states,
461 };
462
463 for (auto* main_controller : controller_npads) {
464 main_controller->common.entry_count = 16;
465 main_controller->common.total_entry_count = 17;
466
467 const auto& last_entry =
468 main_controller->npad[main_controller->common.last_entry_index];
469
470 main_controller->common.timestamp = core_timing.GetCPUTicks();
471 main_controller->common.last_entry_index =
472 (main_controller->common.last_entry_index + 1) % 17;
473
474 auto& cur_entry = main_controller->npad[main_controller->common.last_entry_index];
475
476 cur_entry.timestamp = last_entry.timestamp + 1;
477 cur_entry.timestamp2 = cur_entry.timestamp;
478 }
479
480 for (auto* analog_trigger : controller_triggers) {
481 analog_trigger->entry_count = 16;
482 analog_trigger->total_entry_count = 17;
483 388
484 const auto& last_entry = analog_trigger->trigger[analog_trigger->last_entry_index]; 389 for (std::size_t i = 0; i < controller_data.size(); ++i) {
390 auto& controller = controller_data[i];
391 auto& npad = controller.shared_memory_entry;
485 392
486 analog_trigger->timestamp = core_timing.GetCPUTicks(); 393 const auto& controller_type = controller.device->GetNpadStyleIndex();
487 analog_trigger->last_entry_index = (analog_trigger->last_entry_index + 1) % 17;
488 394
489 auto& cur_entry = analog_trigger->trigger[analog_trigger->last_entry_index]; 395 if (controller_type == Core::HID::NpadStyleIndex::None ||
490 396 !controller.device->IsConnected()) {
491 cur_entry.timestamp = last_entry.timestamp + 1; 397 // Refresh shared memory
492 cur_entry.timestamp2 = cur_entry.timestamp; 398 std::memcpy(data + NPAD_OFFSET + (i * sizeof(NpadInternalState)),
493 } 399 &controller.shared_memory_entry, sizeof(NpadInternalState));
494
495 const auto& controller_type = connected_controllers[i].type;
496
497 if (controller_type == NPadControllerType::None || !connected_controllers[i].is_connected) {
498 continue; 400 continue;
499 } 401 }
500 const u32 npad_index = static_cast<u32>(i);
501
502 RequestPadStateUpdate(npad_index);
503 auto& pad_state = npad_pad_states[npad_index];
504 auto& trigger_state = npad_trigger_states[npad_index];
505
506 auto& main_controller =
507 npad.fullkey_states.npad[npad.fullkey_states.common.last_entry_index];
508 auto& handheld_entry =
509 npad.handheld_states.npad[npad.handheld_states.common.last_entry_index];
510 auto& dual_entry = npad.joy_dual_states.npad[npad.joy_dual_states.common.last_entry_index];
511 auto& left_entry = npad.joy_left_states.npad[npad.joy_left_states.common.last_entry_index];
512 auto& right_entry =
513 npad.joy_right_states.npad[npad.joy_right_states.common.last_entry_index];
514 auto& pokeball_entry = npad.palma_states.npad[npad.palma_states.common.last_entry_index];
515 auto& libnx_entry =
516 npad.system_ext_states.npad[npad.system_ext_states.common.last_entry_index];
517 auto& trigger_entry =
518 npad.gc_trigger_states.trigger[npad.gc_trigger_states.last_entry_index];
519
520 libnx_entry.connection_status.raw = 0;
521 libnx_entry.connection_status.is_connected.Assign(1);
522 402
403 RequestPadStateUpdate(controller.device->GetNpadIdType());
404 auto& pad_state = controller.npad_pad_state;
405 auto& libnx_state = controller.npad_libnx_state;
406 auto& trigger_state = controller.npad_trigger_state;
407
408 // LibNX exclusively uses this section, so we always update it since LibNX doesn't activate
409 // any controllers.
410 libnx_state.connection_status.raw = 0;
411 libnx_state.connection_status.is_connected.Assign(1);
523 switch (controller_type) { 412 switch (controller_type) {
524 case NPadControllerType::None: 413 case Core::HID::NpadStyleIndex::None:
525 UNREACHABLE(); 414 UNREACHABLE();
526 break; 415 break;
527 case NPadControllerType::ProController: 416 case Core::HID::NpadStyleIndex::ProController:
528 main_controller.connection_status.raw = 0; 417 case Core::HID::NpadStyleIndex::NES:
529 main_controller.connection_status.is_connected.Assign(1); 418 case Core::HID::NpadStyleIndex::SNES:
530 main_controller.connection_status.is_wired.Assign(1); 419 case Core::HID::NpadStyleIndex::N64:
531 main_controller.pad.pad_states.raw = pad_state.pad_states.raw; 420 case Core::HID::NpadStyleIndex::SegaGenesis:
532 main_controller.pad.l_stick = pad_state.l_stick; 421 pad_state.connection_status.raw = 0;
533 main_controller.pad.r_stick = pad_state.r_stick; 422 pad_state.connection_status.is_connected.Assign(1);
534 423 pad_state.connection_status.is_wired.Assign(1);
535 libnx_entry.connection_status.is_wired.Assign(1); 424
425 libnx_state.connection_status.is_wired.Assign(1);
426 pad_state.sampling_number =
427 npad.fullkey_lifo.ReadCurrentEntry().state.sampling_number + 1;
428 npad.fullkey_lifo.WriteNextEntry(pad_state);
429 break;
430 case Core::HID::NpadStyleIndex::Handheld:
431 pad_state.connection_status.raw = 0;
432 pad_state.connection_status.is_connected.Assign(1);
433 pad_state.connection_status.is_wired.Assign(1);
434 pad_state.connection_status.is_left_connected.Assign(1);
435 pad_state.connection_status.is_right_connected.Assign(1);
436 pad_state.connection_status.is_left_wired.Assign(1);
437 pad_state.connection_status.is_right_wired.Assign(1);
438
439 libnx_state.connection_status.is_wired.Assign(1);
440 libnx_state.connection_status.is_left_connected.Assign(1);
441 libnx_state.connection_status.is_right_connected.Assign(1);
442 libnx_state.connection_status.is_left_wired.Assign(1);
443 libnx_state.connection_status.is_right_wired.Assign(1);
444 pad_state.sampling_number =
445 npad.handheld_lifo.ReadCurrentEntry().state.sampling_number + 1;
446 npad.handheld_lifo.WriteNextEntry(pad_state);
536 break; 447 break;
537 case NPadControllerType::Handheld: 448 case Core::HID::NpadStyleIndex::JoyconDual:
538 handheld_entry.connection_status.raw = 0; 449 pad_state.connection_status.raw = 0;
539 handheld_entry.connection_status.is_connected.Assign(1); 450 pad_state.connection_status.is_connected.Assign(1);
540 handheld_entry.connection_status.is_wired.Assign(1); 451 pad_state.connection_status.is_left_connected.Assign(1);
541 handheld_entry.connection_status.is_left_connected.Assign(1); 452 pad_state.connection_status.is_right_connected.Assign(1);
542 handheld_entry.connection_status.is_right_connected.Assign(1); 453
543 handheld_entry.connection_status.is_left_wired.Assign(1); 454 libnx_state.connection_status.is_left_connected.Assign(1);
544 handheld_entry.connection_status.is_right_wired.Assign(1); 455 libnx_state.connection_status.is_right_connected.Assign(1);
545 handheld_entry.pad.pad_states.raw = pad_state.pad_states.raw; 456 pad_state.sampling_number =
546 handheld_entry.pad.l_stick = pad_state.l_stick; 457 npad.joy_dual_lifo.ReadCurrentEntry().state.sampling_number + 1;
547 handheld_entry.pad.r_stick = pad_state.r_stick; 458 npad.joy_dual_lifo.WriteNextEntry(pad_state);
548
549 libnx_entry.connection_status.is_wired.Assign(1);
550 libnx_entry.connection_status.is_left_connected.Assign(1);
551 libnx_entry.connection_status.is_right_connected.Assign(1);
552 libnx_entry.connection_status.is_left_wired.Assign(1);
553 libnx_entry.connection_status.is_right_wired.Assign(1);
554 break; 459 break;
555 case NPadControllerType::JoyDual: 460 case Core::HID::NpadStyleIndex::JoyconLeft:
556 dual_entry.connection_status.raw = 0; 461 pad_state.connection_status.raw = 0;
557 dual_entry.connection_status.is_connected.Assign(1); 462 pad_state.connection_status.is_connected.Assign(1);
558 dual_entry.connection_status.is_left_connected.Assign(1); 463 pad_state.connection_status.is_left_connected.Assign(1);
559 dual_entry.connection_status.is_right_connected.Assign(1); 464
560 dual_entry.pad.pad_states.raw = pad_state.pad_states.raw; 465 libnx_state.connection_status.is_left_connected.Assign(1);
561 dual_entry.pad.l_stick = pad_state.l_stick; 466 pad_state.sampling_number =
562 dual_entry.pad.r_stick = pad_state.r_stick; 467 npad.joy_left_lifo.ReadCurrentEntry().state.sampling_number + 1;
563 468 npad.joy_left_lifo.WriteNextEntry(pad_state);
564 libnx_entry.connection_status.is_left_connected.Assign(1);
565 libnx_entry.connection_status.is_right_connected.Assign(1);
566 break; 469 break;
567 case NPadControllerType::JoyLeft: 470 case Core::HID::NpadStyleIndex::JoyconRight:
568 left_entry.connection_status.raw = 0; 471 pad_state.connection_status.raw = 0;
569 left_entry.connection_status.is_connected.Assign(1); 472 pad_state.connection_status.is_connected.Assign(1);
570 left_entry.connection_status.is_left_connected.Assign(1); 473 pad_state.connection_status.is_right_connected.Assign(1);
571 left_entry.pad.pad_states.raw = pad_state.pad_states.raw; 474
572 left_entry.pad.l_stick = pad_state.l_stick; 475 libnx_state.connection_status.is_right_connected.Assign(1);
573 left_entry.pad.r_stick = pad_state.r_stick; 476 pad_state.sampling_number =
574 477 npad.joy_right_lifo.ReadCurrentEntry().state.sampling_number + 1;
575 libnx_entry.connection_status.is_left_connected.Assign(1); 478 npad.joy_right_lifo.WriteNextEntry(pad_state);
576 break; 479 break;
577 case NPadControllerType::JoyRight: 480 case Core::HID::NpadStyleIndex::GameCube:
578 right_entry.connection_status.raw = 0; 481 pad_state.connection_status.raw = 0;
579 right_entry.connection_status.is_connected.Assign(1); 482 pad_state.connection_status.is_connected.Assign(1);
580 right_entry.connection_status.is_right_connected.Assign(1); 483 pad_state.connection_status.is_wired.Assign(1);
581 right_entry.pad.pad_states.raw = pad_state.pad_states.raw; 484
582 right_entry.pad.l_stick = pad_state.l_stick; 485 libnx_state.connection_status.is_wired.Assign(1);
583 right_entry.pad.r_stick = pad_state.r_stick; 486 pad_state.sampling_number =
584 487 npad.fullkey_lifo.ReadCurrentEntry().state.sampling_number + 1;
585 libnx_entry.connection_status.is_right_connected.Assign(1); 488 trigger_state.sampling_number =
489 npad.gc_trigger_lifo.ReadCurrentEntry().state.sampling_number + 1;
490 npad.fullkey_lifo.WriteNextEntry(pad_state);
491 npad.gc_trigger_lifo.WriteNextEntry(trigger_state);
586 break; 492 break;
587 case NPadControllerType::GameCube: 493 case Core::HID::NpadStyleIndex::Pokeball:
588 main_controller.connection_status.raw = 0; 494 pad_state.connection_status.raw = 0;
589 main_controller.connection_status.is_connected.Assign(1); 495 pad_state.connection_status.is_connected.Assign(1);
590 main_controller.connection_status.is_wired.Assign(1); 496 pad_state.sampling_number =
591 main_controller.pad.pad_states.raw = pad_state.pad_states.raw; 497 npad.palma_lifo.ReadCurrentEntry().state.sampling_number + 1;
592 main_controller.pad.l_stick = pad_state.l_stick; 498 npad.palma_lifo.WriteNextEntry(pad_state);
593 main_controller.pad.r_stick = pad_state.r_stick;
594 trigger_entry.l_analog = trigger_state.l_analog;
595 trigger_entry.r_analog = trigger_state.r_analog;
596
597 libnx_entry.connection_status.is_wired.Assign(1);
598 break; 499 break;
599 case NPadControllerType::Pokeball: 500 default:
600 pokeball_entry.connection_status.raw = 0;
601 pokeball_entry.connection_status.is_connected.Assign(1);
602 pokeball_entry.pad.pad_states.raw = pad_state.pad_states.raw;
603 pokeball_entry.pad.l_stick = pad_state.l_stick;
604 pokeball_entry.pad.r_stick = pad_state.r_stick;
605 break; 501 break;
606 } 502 }
607 503
608 // LibNX exclusively uses this section, so we always update it since LibNX doesn't activate 504 libnx_state.npad_buttons.raw = pad_state.npad_buttons.raw;
609 // any controllers. 505 libnx_state.l_stick = pad_state.l_stick;
610 libnx_entry.pad.pad_states.raw = pad_state.pad_states.raw; 506 libnx_state.r_stick = pad_state.r_stick;
611 libnx_entry.pad.l_stick = pad_state.l_stick; 507 npad.system_ext_lifo.WriteNextEntry(pad_state);
612 libnx_entry.pad.r_stick = pad_state.r_stick;
613 508
614 press_state |= static_cast<u32>(pad_state.pad_states.raw); 509 press_state |= static_cast<u32>(pad_state.npad_buttons.raw);
510
511 std::memcpy(data + NPAD_OFFSET + (i * sizeof(NpadInternalState)),
512 &controller.shared_memory_entry, sizeof(NpadInternalState));
615 } 513 }
616 std::memcpy(data + NPAD_OFFSET, shared_memory_entries.data(),
617 shared_memory_entries.size() * sizeof(NPadEntry));
618} 514}
619 515
620void Controller_NPad::OnMotionUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 516void Controller_NPad::OnMotionUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
@@ -622,145 +518,138 @@ void Controller_NPad::OnMotionUpdate(const Core::Timing::CoreTiming& core_timing
622 if (!IsControllerActivated()) { 518 if (!IsControllerActivated()) {
623 return; 519 return;
624 } 520 }
625 for (std::size_t i = 0; i < shared_memory_entries.size(); ++i) {
626 auto& npad = shared_memory_entries[i];
627
628 const auto& controller_type = connected_controllers[i].type;
629
630 if (controller_type == NPadControllerType::None || !connected_controllers[i].is_connected) {
631 continue;
632 }
633 521
634 const std::array<SixAxisGeneric*, 6> controller_sixaxes{ 522 for (std::size_t i = 0; i < controller_data.size(); ++i) {
635 &npad.sixaxis_fullkey, &npad.sixaxis_handheld, &npad.sixaxis_dual_left, 523 auto& controller = controller_data[i];
636 &npad.sixaxis_dual_right, &npad.sixaxis_left, &npad.sixaxis_right,
637 };
638 524
639 for (auto* sixaxis_sensor : controller_sixaxes) { 525 const auto& controller_type = controller.device->GetNpadStyleIndex();
640 sixaxis_sensor->common.entry_count = 16;
641 sixaxis_sensor->common.total_entry_count = 17;
642 526
643 const auto& last_entry = 527 if (controller_type == Core::HID::NpadStyleIndex::None ||
644 sixaxis_sensor->sixaxis[sixaxis_sensor->common.last_entry_index]; 528 !controller.device->IsConnected()) {
645 529 continue;
646 sixaxis_sensor->common.timestamp = core_timing.GetCPUTicks();
647 sixaxis_sensor->common.last_entry_index =
648 (sixaxis_sensor->common.last_entry_index + 1) % 17;
649
650 auto& cur_entry = sixaxis_sensor->sixaxis[sixaxis_sensor->common.last_entry_index];
651
652 cur_entry.timestamp = last_entry.timestamp + 1;
653 cur_entry.timestamp2 = cur_entry.timestamp;
654 } 530 }
655 531
656 // Try to read sixaxis sensor states 532 auto& npad = controller.shared_memory_entry;
657 std::array<MotionDevice, 2> motion_devices; 533 const auto& motion_state = controller.device->GetMotions();
658 534 auto& sixaxis_fullkey_state = controller.sixaxis_fullkey_state;
659 if (sixaxis_sensors_enabled && Settings::values.motion_enabled.GetValue()) { 535 auto& sixaxis_handheld_state = controller.sixaxis_handheld_state;
660 sixaxis_at_rest = true; 536 auto& sixaxis_dual_left_state = controller.sixaxis_dual_left_state;
661 for (std::size_t e = 0; e < motion_devices.size(); ++e) { 537 auto& sixaxis_dual_right_state = controller.sixaxis_dual_right_state;
662 const auto& device = motions[i][e]; 538 auto& sixaxis_left_lifo_state = controller.sixaxis_left_lifo_state;
663 if (device) { 539 auto& sixaxis_right_lifo_state = controller.sixaxis_right_lifo_state;
664 std::tie(motion_devices[e].accel, motion_devices[e].gyro, 540
665 motion_devices[e].rotation, motion_devices[e].orientation, 541 if (controller.sixaxis_sensor_enabled && Settings::values.motion_enabled.GetValue()) {
666 motion_devices[e].quaternion) = device->GetStatus(); 542 controller.sixaxis_at_rest = true;
667 sixaxis_at_rest = sixaxis_at_rest && motion_devices[e].gyro.Length2() < 0.0001f; 543 for (std::size_t e = 0; e < motion_state.size(); ++e) {
668 } 544 controller.sixaxis_at_rest =
545 controller.sixaxis_at_rest && motion_state[e].is_at_rest;
669 } 546 }
670 } 547 }
671 548
672 auto& full_sixaxis_entry =
673 npad.sixaxis_fullkey.sixaxis[npad.sixaxis_fullkey.common.last_entry_index];
674 auto& handheld_sixaxis_entry =
675 npad.sixaxis_handheld.sixaxis[npad.sixaxis_handheld.common.last_entry_index];
676 auto& dual_left_sixaxis_entry =
677 npad.sixaxis_dual_left.sixaxis[npad.sixaxis_dual_left.common.last_entry_index];
678 auto& dual_right_sixaxis_entry =
679 npad.sixaxis_dual_right.sixaxis[npad.sixaxis_dual_right.common.last_entry_index];
680 auto& left_sixaxis_entry =
681 npad.sixaxis_left.sixaxis[npad.sixaxis_left.common.last_entry_index];
682 auto& right_sixaxis_entry =
683 npad.sixaxis_right.sixaxis[npad.sixaxis_right.common.last_entry_index];
684
685 switch (controller_type) { 549 switch (controller_type) {
686 case NPadControllerType::None: 550 case Core::HID::NpadStyleIndex::None:
687 UNREACHABLE(); 551 UNREACHABLE();
688 break; 552 break;
689 case NPadControllerType::ProController: 553 case Core::HID::NpadStyleIndex::ProController:
690 full_sixaxis_entry.attribute.raw = 0; 554 sixaxis_fullkey_state.attribute.raw = 0;
691 if (sixaxis_sensors_enabled && motions[i][0]) { 555 if (controller.sixaxis_sensor_enabled) {
692 full_sixaxis_entry.attribute.is_connected.Assign(1); 556 sixaxis_fullkey_state.attribute.is_connected.Assign(1);
693 full_sixaxis_entry.accel = motion_devices[0].accel; 557 sixaxis_fullkey_state.accel = motion_state[0].accel;
694 full_sixaxis_entry.gyro = motion_devices[0].gyro; 558 sixaxis_fullkey_state.gyro = motion_state[0].gyro;
695 full_sixaxis_entry.rotation = motion_devices[0].rotation; 559 sixaxis_fullkey_state.rotation = motion_state[0].rotation;
696 full_sixaxis_entry.orientation = motion_devices[0].orientation; 560 sixaxis_fullkey_state.orientation = motion_state[0].orientation;
697 } 561 }
698 break; 562 break;
699 case NPadControllerType::Handheld: 563 case Core::HID::NpadStyleIndex::Handheld:
700 handheld_sixaxis_entry.attribute.raw = 0; 564 sixaxis_handheld_state.attribute.raw = 0;
701 if (sixaxis_sensors_enabled && motions[i][0]) { 565 if (controller.sixaxis_sensor_enabled) {
702 handheld_sixaxis_entry.attribute.is_connected.Assign(1); 566 sixaxis_handheld_state.attribute.is_connected.Assign(1);
703 handheld_sixaxis_entry.accel = motion_devices[0].accel; 567 sixaxis_handheld_state.accel = motion_state[0].accel;
704 handheld_sixaxis_entry.gyro = motion_devices[0].gyro; 568 sixaxis_handheld_state.gyro = motion_state[0].gyro;
705 handheld_sixaxis_entry.rotation = motion_devices[0].rotation; 569 sixaxis_handheld_state.rotation = motion_state[0].rotation;
706 handheld_sixaxis_entry.orientation = motion_devices[0].orientation; 570 sixaxis_handheld_state.orientation = motion_state[0].orientation;
707 } 571 }
708 break; 572 break;
709 case NPadControllerType::JoyDual: 573 case Core::HID::NpadStyleIndex::JoyconDual:
710 dual_left_sixaxis_entry.attribute.raw = 0; 574 sixaxis_dual_left_state.attribute.raw = 0;
711 dual_right_sixaxis_entry.attribute.raw = 0; 575 sixaxis_dual_right_state.attribute.raw = 0;
712 if (sixaxis_sensors_enabled && motions[i][0]) { 576 if (controller.sixaxis_sensor_enabled) {
713 // Set motion for the left joycon 577 // Set motion for the left joycon
714 dual_left_sixaxis_entry.attribute.is_connected.Assign(1); 578 sixaxis_dual_left_state.attribute.is_connected.Assign(1);
715 dual_left_sixaxis_entry.accel = motion_devices[0].accel; 579 sixaxis_dual_left_state.accel = motion_state[0].accel;
716 dual_left_sixaxis_entry.gyro = motion_devices[0].gyro; 580 sixaxis_dual_left_state.gyro = motion_state[0].gyro;
717 dual_left_sixaxis_entry.rotation = motion_devices[0].rotation; 581 sixaxis_dual_left_state.rotation = motion_state[0].rotation;
718 dual_left_sixaxis_entry.orientation = motion_devices[0].orientation; 582 sixaxis_dual_left_state.orientation = motion_state[0].orientation;
719 } 583 }
720 if (sixaxis_sensors_enabled && motions[i][1]) { 584 if (controller.sixaxis_sensor_enabled) {
721 // Set motion for the right joycon 585 // Set motion for the right joycon
722 dual_right_sixaxis_entry.attribute.is_connected.Assign(1); 586 sixaxis_dual_right_state.attribute.is_connected.Assign(1);
723 dual_right_sixaxis_entry.accel = motion_devices[1].accel; 587 sixaxis_dual_right_state.accel = motion_state[1].accel;
724 dual_right_sixaxis_entry.gyro = motion_devices[1].gyro; 588 sixaxis_dual_right_state.gyro = motion_state[1].gyro;
725 dual_right_sixaxis_entry.rotation = motion_devices[1].rotation; 589 sixaxis_dual_right_state.rotation = motion_state[1].rotation;
726 dual_right_sixaxis_entry.orientation = motion_devices[1].orientation; 590 sixaxis_dual_right_state.orientation = motion_state[1].orientation;
727 } 591 }
728 break; 592 break;
729 case NPadControllerType::JoyLeft: 593 case Core::HID::NpadStyleIndex::JoyconLeft:
730 left_sixaxis_entry.attribute.raw = 0; 594 sixaxis_left_lifo_state.attribute.raw = 0;
731 if (sixaxis_sensors_enabled && motions[i][0]) { 595 if (controller.sixaxis_sensor_enabled) {
732 left_sixaxis_entry.attribute.is_connected.Assign(1); 596 sixaxis_left_lifo_state.attribute.is_connected.Assign(1);
733 left_sixaxis_entry.accel = motion_devices[0].accel; 597 sixaxis_left_lifo_state.accel = motion_state[0].accel;
734 left_sixaxis_entry.gyro = motion_devices[0].gyro; 598 sixaxis_left_lifo_state.gyro = motion_state[0].gyro;
735 left_sixaxis_entry.rotation = motion_devices[0].rotation; 599 sixaxis_left_lifo_state.rotation = motion_state[0].rotation;
736 left_sixaxis_entry.orientation = motion_devices[0].orientation; 600 sixaxis_left_lifo_state.orientation = motion_state[0].orientation;
737 } 601 }
738 break; 602 break;
739 case NPadControllerType::JoyRight: 603 case Core::HID::NpadStyleIndex::JoyconRight:
740 right_sixaxis_entry.attribute.raw = 0; 604 sixaxis_right_lifo_state.attribute.raw = 0;
741 if (sixaxis_sensors_enabled && motions[i][1]) { 605 if (controller.sixaxis_sensor_enabled) {
742 right_sixaxis_entry.attribute.is_connected.Assign(1); 606 sixaxis_right_lifo_state.attribute.is_connected.Assign(1);
743 right_sixaxis_entry.accel = motion_devices[1].accel; 607 sixaxis_right_lifo_state.accel = motion_state[1].accel;
744 right_sixaxis_entry.gyro = motion_devices[1].gyro; 608 sixaxis_right_lifo_state.gyro = motion_state[1].gyro;
745 right_sixaxis_entry.rotation = motion_devices[1].rotation; 609 sixaxis_right_lifo_state.rotation = motion_state[1].rotation;
746 right_sixaxis_entry.orientation = motion_devices[1].orientation; 610 sixaxis_right_lifo_state.orientation = motion_state[1].orientation;
747 } 611 }
748 break; 612 break;
749 case NPadControllerType::GameCube: 613 default:
750 case NPadControllerType::Pokeball:
751 break; 614 break;
752 } 615 }
616
617 sixaxis_fullkey_state.sampling_number =
618 npad.sixaxis_fullkey_lifo.ReadCurrentEntry().state.sampling_number + 1;
619 sixaxis_handheld_state.sampling_number =
620 npad.sixaxis_handheld_lifo.ReadCurrentEntry().state.sampling_number + 1;
621 sixaxis_dual_left_state.sampling_number =
622 npad.sixaxis_dual_left_lifo.ReadCurrentEntry().state.sampling_number + 1;
623 sixaxis_dual_right_state.sampling_number =
624 npad.sixaxis_dual_right_lifo.ReadCurrentEntry().state.sampling_number + 1;
625 sixaxis_left_lifo_state.sampling_number =
626 npad.sixaxis_left_lifo.ReadCurrentEntry().state.sampling_number + 1;
627 sixaxis_right_lifo_state.sampling_number =
628 npad.sixaxis_right_lifo.ReadCurrentEntry().state.sampling_number + 1;
629
630 if (Core::HID::IndexToNpadIdType(i) == Core::HID::NpadIdType::Handheld) {
631 // This buffer only is updated on handheld on HW
632 npad.sixaxis_handheld_lifo.WriteNextEntry(sixaxis_handheld_state);
633 } else {
634 // Hanheld doesn't update this buffer on HW
635 npad.sixaxis_fullkey_lifo.WriteNextEntry(sixaxis_fullkey_state);
636 }
637
638 npad.sixaxis_dual_left_lifo.WriteNextEntry(sixaxis_dual_left_state);
639 npad.sixaxis_dual_right_lifo.WriteNextEntry(sixaxis_dual_right_state);
640 npad.sixaxis_left_lifo.WriteNextEntry(sixaxis_left_lifo_state);
641 npad.sixaxis_right_lifo.WriteNextEntry(sixaxis_right_lifo_state);
642 std::memcpy(data + NPAD_OFFSET + (i * sizeof(NpadInternalState)),
643 &controller.shared_memory_entry, sizeof(NpadInternalState));
753 } 644 }
754 std::memcpy(data + NPAD_OFFSET, shared_memory_entries.data(),
755 shared_memory_entries.size() * sizeof(NPadEntry));
756} 645}
757 646
758void Controller_NPad::SetSupportedStyleSet(NpadStyleSet style_set) { 647void Controller_NPad::SetSupportedStyleSet(Core::HID::NpadStyleTag style_set) {
759 style.raw = style_set.raw; 648 hid_core.SetSupportedStyleTag(style_set);
760} 649}
761 650
762Controller_NPad::NpadStyleSet Controller_NPad::GetSupportedStyleSet() const { 651Core::HID::NpadStyleTag Controller_NPad::GetSupportedStyleSet() const {
763 return style; 652 return hid_core.GetSupportedStyleTag();
764} 653}
765 654
766void Controller_NPad::SetSupportedNpadIdTypes(u8* data, std::size_t length) { 655void Controller_NPad::SetSupportedNpadIdTypes(u8* data, std::size_t length) {
@@ -779,11 +668,11 @@ std::size_t Controller_NPad::GetSupportedNpadIdTypesSize() const {
779 return supported_npad_id_types.size(); 668 return supported_npad_id_types.size();
780} 669}
781 670
782void Controller_NPad::SetHoldType(NpadHoldType joy_hold_type) { 671void Controller_NPad::SetHoldType(NpadJoyHoldType joy_hold_type) {
783 hold_type = joy_hold_type; 672 hold_type = joy_hold_type;
784} 673}
785 674
786Controller_NPad::NpadHoldType Controller_NPad::GetHoldType() const { 675Controller_NPad::NpadJoyHoldType Controller_NPad::GetHoldType() const {
787 return hold_type; 676 return hold_type;
788} 677}
789 678
@@ -803,29 +692,35 @@ Controller_NPad::NpadCommunicationMode Controller_NPad::GetNpadCommunicationMode
803 return communication_mode; 692 return communication_mode;
804} 693}
805 694
806void Controller_NPad::SetNpadMode(u32 npad_id, NpadAssignments assignment_mode) { 695void Controller_NPad::SetNpadMode(Core::HID::NpadIdType npad_id,
807 const std::size_t npad_index = NPadIdToIndex(npad_id); 696 NpadJoyAssignmentMode assignment_mode) {
808 ASSERT(npad_index < shared_memory_entries.size()); 697 if (!IsNpadIdValid(npad_id)) {
809 if (shared_memory_entries[npad_index].assignment_mode != assignment_mode) { 698 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
810 shared_memory_entries[npad_index].assignment_mode = assignment_mode; 699 return;
700 }
701
702 auto& controller = GetControllerFromNpadIdType(npad_id);
703 if (controller.shared_memory_entry.assignment_mode != assignment_mode) {
704 controller.shared_memory_entry.assignment_mode = assignment_mode;
811 } 705 }
812} 706}
813 707
814bool Controller_NPad::VibrateControllerAtIndex(std::size_t npad_index, std::size_t device_index, 708bool Controller_NPad::VibrateControllerAtIndex(Core::HID::NpadIdType npad_id,
815 const VibrationValue& vibration_value) { 709 std::size_t device_index,
816 if (!connected_controllers[npad_index].is_connected || !vibrations[npad_index][device_index]) { 710 const Core::HID::VibrationValue& vibration_value) {
711 auto& controller = GetControllerFromNpadIdType(npad_id);
712 if (!controller.device->IsConnected()) {
817 return false; 713 return false;
818 } 714 }
819 715
820 const auto& player = Settings::values.players.GetValue()[npad_index]; 716 if (!controller.device->IsVibrationEnabled()) {
821 717 if (controller.vibration[device_index].latest_vibration_value.low_amplitude != 0.0f ||
822 if (!player.vibration_enabled) { 718 controller.vibration[device_index].latest_vibration_value.high_amplitude != 0.0f) {
823 if (latest_vibration_values[npad_index][device_index].amp_low != 0.0f ||
824 latest_vibration_values[npad_index][device_index].amp_high != 0.0f) {
825 // Send an empty vibration to stop any vibrations. 719 // Send an empty vibration to stop any vibrations.
826 vibrations[npad_index][device_index]->SetRumblePlay(0.0f, 160.0f, 0.0f, 320.0f); 720 Core::HID::VibrationValue vibration{0.0f, 160.0f, 0.0f, 320.0f};
721 controller.device->SetVibration(device_index, vibration);
827 // Then reset the vibration value to its default value. 722 // Then reset the vibration value to its default value.
828 latest_vibration_values[npad_index][device_index] = DEFAULT_VIBRATION_VALUE; 723 controller.vibration[device_index].latest_vibration_value = DEFAULT_VIBRATION_VALUE;
829 } 724 }
830 725
831 return false; 726 return false;
@@ -839,27 +734,25 @@ bool Controller_NPad::VibrateControllerAtIndex(std::size_t npad_index, std::size
839 const auto now = steady_clock::now(); 734 const auto now = steady_clock::now();
840 735
841 // Filter out non-zero vibrations that are within 10ms of each other. 736 // Filter out non-zero vibrations that are within 10ms of each other.
842 if ((vibration_value.amp_low != 0.0f || vibration_value.amp_high != 0.0f) && 737 if ((vibration_value.low_amplitude != 0.0f || vibration_value.high_amplitude != 0.0f) &&
843 duration_cast<milliseconds>(now - last_vibration_timepoints[npad_index][device_index]) < 738 duration_cast<milliseconds>(
739 now - controller.vibration[device_index].last_vibration_timepoint) <
844 milliseconds(10)) { 740 milliseconds(10)) {
845 return false; 741 return false;
846 } 742 }
847 743
848 last_vibration_timepoints[npad_index][device_index] = now; 744 controller.vibration[device_index].last_vibration_timepoint = now;
849 } 745 }
850 746
851 auto& vibration = vibrations[npad_index][device_index]; 747 Core::HID::VibrationValue vibration{
852 const auto player_vibration_strength = static_cast<f32>(player.vibration_strength); 748 vibration_value.low_amplitude, vibration_value.low_frequency,
853 const auto amp_low = 749 vibration_value.high_amplitude, vibration_value.high_frequency};
854 std::min(vibration_value.amp_low * player_vibration_strength / 100.0f, 1.0f); 750 return controller.device->SetVibration(device_index, vibration);
855 const auto amp_high =
856 std::min(vibration_value.amp_high * player_vibration_strength / 100.0f, 1.0f);
857 return vibration->SetRumblePlay(amp_low, vibration_value.freq_low, amp_high,
858 vibration_value.freq_high);
859} 751}
860 752
861void Controller_NPad::VibrateController(const DeviceHandle& vibration_device_handle, 753void Controller_NPad::VibrateController(
862 const VibrationValue& vibration_value) { 754 const Core::HID::VibrationDeviceHandle& vibration_device_handle,
755 const Core::HID::VibrationValue& vibration_value) {
863 if (!IsDeviceHandleValid(vibration_device_handle)) { 756 if (!IsDeviceHandleValid(vibration_device_handle)) {
864 return; 757 return;
865 } 758 }
@@ -868,42 +761,45 @@ void Controller_NPad::VibrateController(const DeviceHandle& vibration_device_han
868 return; 761 return;
869 } 762 }
870 763
871 const auto npad_index = NPadIdToIndex(vibration_device_handle.npad_id); 764 auto& controller = GetControllerFromHandle(vibration_device_handle);
872 const auto device_index = static_cast<std::size_t>(vibration_device_handle.device_index); 765 const auto device_index = static_cast<std::size_t>(vibration_device_handle.device_index);
873 766
874 if (!vibration_devices_mounted[npad_index][device_index] || 767 if (!controller.vibration[device_index].device_mounted || !controller.device->IsConnected()) {
875 !connected_controllers[npad_index].is_connected) {
876 return; 768 return;
877 } 769 }
878 770
879 if (vibration_device_handle.device_index == DeviceIndex::None) { 771 if (vibration_device_handle.device_index == Core::HID::DeviceIndex::None) {
880 UNREACHABLE_MSG("DeviceIndex should never be None!"); 772 UNREACHABLE_MSG("DeviceIndex should never be None!");
881 return; 773 return;
882 } 774 }
883 775
884 // Some games try to send mismatched parameters in the device handle, block these. 776 // Some games try to send mismatched parameters in the device handle, block these.
885 if ((connected_controllers[npad_index].type == NPadControllerType::JoyLeft && 777 if ((controller.device->GetNpadStyleIndex() == Core::HID::NpadStyleIndex::JoyconLeft &&
886 (vibration_device_handle.npad_type == NpadType::JoyconRight || 778 (vibration_device_handle.npad_type == Core::HID::NpadStyleIndex::JoyconRight ||
887 vibration_device_handle.device_index == DeviceIndex::Right)) || 779 vibration_device_handle.device_index == Core::HID::DeviceIndex::Right)) ||
888 (connected_controllers[npad_index].type == NPadControllerType::JoyRight && 780 (controller.device->GetNpadStyleIndex() == Core::HID::NpadStyleIndex::JoyconRight &&
889 (vibration_device_handle.npad_type == NpadType::JoyconLeft || 781 (vibration_device_handle.npad_type == Core::HID::NpadStyleIndex::JoyconLeft ||
890 vibration_device_handle.device_index == DeviceIndex::Left))) { 782 vibration_device_handle.device_index == Core::HID::DeviceIndex::Left))) {
891 return; 783 return;
892 } 784 }
893 785
894 // Filter out vibrations with equivalent values to reduce unnecessary state changes. 786 // Filter out vibrations with equivalent values to reduce unnecessary state changes.
895 if (vibration_value.amp_low == latest_vibration_values[npad_index][device_index].amp_low && 787 if (vibration_value.low_amplitude ==
896 vibration_value.amp_high == latest_vibration_values[npad_index][device_index].amp_high) { 788 controller.vibration[device_index].latest_vibration_value.low_amplitude &&
789 vibration_value.high_amplitude ==
790 controller.vibration[device_index].latest_vibration_value.high_amplitude) {
897 return; 791 return;
898 } 792 }
899 793
900 if (VibrateControllerAtIndex(npad_index, device_index, vibration_value)) { 794 if (VibrateControllerAtIndex(controller.device->GetNpadIdType(), device_index,
901 latest_vibration_values[npad_index][device_index] = vibration_value; 795 vibration_value)) {
796 controller.vibration[device_index].latest_vibration_value = vibration_value;
902 } 797 }
903} 798}
904 799
905void Controller_NPad::VibrateControllers(const std::vector<DeviceHandle>& vibration_device_handles, 800void Controller_NPad::VibrateControllers(
906 const std::vector<VibrationValue>& vibration_values) { 801 const std::vector<Core::HID::VibrationDeviceHandle>& vibration_device_handles,
802 const std::vector<Core::HID::VibrationValue>& vibration_values) {
907 if (!Settings::values.vibration_enabled.GetValue() && !permit_vibration_session_enabled) { 803 if (!Settings::values.vibration_enabled.GetValue() && !permit_vibration_session_enabled) {
908 return; 804 return;
909 } 805 }
@@ -918,167 +814,231 @@ void Controller_NPad::VibrateControllers(const std::vector<DeviceHandle>& vibrat
918 } 814 }
919} 815}
920 816
921Controller_NPad::VibrationValue Controller_NPad::GetLastVibration( 817Core::HID::VibrationValue Controller_NPad::GetLastVibration(
922 const DeviceHandle& vibration_device_handle) const { 818 const Core::HID::VibrationDeviceHandle& vibration_device_handle) const {
923 if (!IsDeviceHandleValid(vibration_device_handle)) { 819 if (!IsDeviceHandleValid(vibration_device_handle)) {
924 return {}; 820 return {};
925 } 821 }
926 822
927 const auto npad_index = NPadIdToIndex(vibration_device_handle.npad_id); 823 const auto& controller = GetControllerFromHandle(vibration_device_handle);
928 const auto device_index = static_cast<std::size_t>(vibration_device_handle.device_index); 824 const auto device_index = static_cast<std::size_t>(vibration_device_handle.device_index);
929 return latest_vibration_values[npad_index][device_index]; 825 return controller.vibration[device_index].latest_vibration_value;
930} 826}
931 827
932void Controller_NPad::InitializeVibrationDevice(const DeviceHandle& vibration_device_handle) { 828void Controller_NPad::InitializeVibrationDevice(
829 const Core::HID::VibrationDeviceHandle& vibration_device_handle) {
933 if (!IsDeviceHandleValid(vibration_device_handle)) { 830 if (!IsDeviceHandleValid(vibration_device_handle)) {
934 return; 831 return;
935 } 832 }
936 833
937 const auto npad_index = NPadIdToIndex(vibration_device_handle.npad_id); 834 const auto npad_index = static_cast<Core::HID::NpadIdType>(vibration_device_handle.npad_id);
938 const auto device_index = static_cast<std::size_t>(vibration_device_handle.device_index); 835 const auto device_index = static_cast<std::size_t>(vibration_device_handle.device_index);
939 InitializeVibrationDeviceAtIndex(npad_index, device_index); 836 InitializeVibrationDeviceAtIndex(npad_index, device_index);
940} 837}
941 838
942void Controller_NPad::InitializeVibrationDeviceAtIndex(std::size_t npad_index, 839void Controller_NPad::InitializeVibrationDeviceAtIndex(Core::HID::NpadIdType npad_id,
943 std::size_t device_index) { 840 std::size_t device_index) {
841 auto& controller = GetControllerFromNpadIdType(npad_id);
944 if (!Settings::values.vibration_enabled.GetValue()) { 842 if (!Settings::values.vibration_enabled.GetValue()) {
945 vibration_devices_mounted[npad_index][device_index] = false; 843 controller.vibration[device_index].device_mounted = false;
946 return; 844 return;
947 } 845 }
948 846
949 if (vibrations[npad_index][device_index]) { 847 controller.vibration[device_index].device_mounted =
950 vibration_devices_mounted[npad_index][device_index] = 848 controller.device->TestVibration(device_index);
951 vibrations[npad_index][device_index]->GetStatus() == 1;
952 } else {
953 vibration_devices_mounted[npad_index][device_index] = false;
954 }
955} 849}
956 850
957void Controller_NPad::SetPermitVibrationSession(bool permit_vibration_session) { 851void Controller_NPad::SetPermitVibrationSession(bool permit_vibration_session) {
958 permit_vibration_session_enabled = permit_vibration_session; 852 permit_vibration_session_enabled = permit_vibration_session;
959} 853}
960 854
961bool Controller_NPad::IsVibrationDeviceMounted(const DeviceHandle& vibration_device_handle) const { 855bool Controller_NPad::IsVibrationDeviceMounted(
856 const Core::HID::VibrationDeviceHandle& vibration_device_handle) const {
962 if (!IsDeviceHandleValid(vibration_device_handle)) { 857 if (!IsDeviceHandleValid(vibration_device_handle)) {
963 return false; 858 return false;
964 } 859 }
965 860
966 const auto npad_index = NPadIdToIndex(vibration_device_handle.npad_id); 861 const auto& controller = GetControllerFromHandle(vibration_device_handle);
967 const auto device_index = static_cast<std::size_t>(vibration_device_handle.device_index); 862 const auto device_index = static_cast<std::size_t>(vibration_device_handle.device_index);
968 return vibration_devices_mounted[npad_index][device_index]; 863 return controller.vibration[device_index].device_mounted;
969} 864}
970 865
971Kernel::KReadableEvent& Controller_NPad::GetStyleSetChangedEvent(u32 npad_id) { 866Kernel::KReadableEvent& Controller_NPad::GetStyleSetChangedEvent(Core::HID::NpadIdType npad_id) {
972 return styleset_changed_events[NPadIdToIndex(npad_id)]->GetReadableEvent(); 867 if (!IsNpadIdValid(npad_id)) {
868 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
869 // Fallback to player 1
870 const auto& controller = GetControllerFromNpadIdType(Core::HID::NpadIdType::Player1);
871 return controller.styleset_changed_event->GetReadableEvent();
872 }
873
874 const auto& controller = GetControllerFromNpadIdType(npad_id);
875 return controller.styleset_changed_event->GetReadableEvent();
973} 876}
974 877
975void Controller_NPad::SignalStyleSetChangedEvent(u32 npad_id) const { 878void Controller_NPad::SignalStyleSetChangedEvent(Core::HID::NpadIdType npad_id) const {
976 styleset_changed_events[NPadIdToIndex(npad_id)]->GetWritableEvent().Signal(); 879 const auto& controller = GetControllerFromNpadIdType(npad_id);
880 controller.styleset_changed_event->GetWritableEvent().Signal();
977} 881}
978 882
979void Controller_NPad::AddNewControllerAt(NPadControllerType controller, std::size_t npad_index) { 883void Controller_NPad::AddNewControllerAt(Core::HID::NpadStyleIndex controller,
980 UpdateControllerAt(controller, npad_index, true); 884 Core::HID::NpadIdType npad_id) {
885 UpdateControllerAt(controller, npad_id, true);
981} 886}
982 887
983void Controller_NPad::UpdateControllerAt(NPadControllerType controller, std::size_t npad_index, 888void Controller_NPad::UpdateControllerAt(Core::HID::NpadStyleIndex type,
984 bool connected) { 889 Core::HID::NpadIdType npad_id, bool connected) {
890 auto& controller = GetControllerFromNpadIdType(npad_id);
985 if (!connected) { 891 if (!connected) {
986 DisconnectNpadAtIndex(npad_index); 892 DisconnectNpad(npad_id);
987 return; 893 return;
988 } 894 }
989 895
990 if (controller == NPadControllerType::Handheld && npad_index == HANDHELD_INDEX) { 896 controller.device->SetNpadStyleIndex(type);
991 Settings::values.players.GetValue()[HANDHELD_INDEX].controller_type = 897 InitNewlyAddedController(npad_id);
992 MapNPadToSettingsType(controller);
993 Settings::values.players.GetValue()[HANDHELD_INDEX].connected = true;
994 connected_controllers[HANDHELD_INDEX] = {controller, true};
995 InitNewlyAddedController(HANDHELD_INDEX);
996 return;
997 }
998
999 Settings::values.players.GetValue()[npad_index].controller_type =
1000 MapNPadToSettingsType(controller);
1001 Settings::values.players.GetValue()[npad_index].connected = true;
1002 connected_controllers[npad_index] = {controller, true};
1003 InitNewlyAddedController(npad_index);
1004} 898}
1005 899
1006void Controller_NPad::DisconnectNpad(u32 npad_id) { 900void Controller_NPad::DisconnectNpad(Core::HID::NpadIdType npad_id) {
1007 DisconnectNpadAtIndex(NPadIdToIndex(npad_id)); 901 if (!IsNpadIdValid(npad_id)) {
1008} 902 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
903 return;
904 }
1009 905
1010void Controller_NPad::DisconnectNpadAtIndex(std::size_t npad_index) { 906 LOG_DEBUG(Service_HID, "Npad disconnected {}", npad_id);
1011 for (std::size_t device_idx = 0; device_idx < vibrations[npad_index].size(); ++device_idx) { 907 auto& controller = GetControllerFromNpadIdType(npad_id);
908 for (std::size_t device_idx = 0; device_idx < controller.vibration.size(); ++device_idx) {
1012 // Send an empty vibration to stop any vibrations. 909 // Send an empty vibration to stop any vibrations.
1013 VibrateControllerAtIndex(npad_index, device_idx, {}); 910 VibrateControllerAtIndex(npad_id, device_idx, {});
1014 vibration_devices_mounted[npad_index][device_idx] = false; 911 controller.vibration[device_idx].device_mounted = false;
1015 } 912 }
1016 913
1017 Settings::values.players.GetValue()[npad_index].connected = false; 914 auto& shared_memory_entry = controller.shared_memory_entry;
1018 connected_controllers[npad_index].is_connected = false; 915 shared_memory_entry.style_tag.raw = Core::HID::NpadStyleSet::None; // Zero out
916 shared_memory_entry.device_type.raw = 0;
917 shared_memory_entry.system_properties.raw = 0;
918 shared_memory_entry.button_properties.raw = 0;
919 shared_memory_entry.battery_level_dual = 0;
920 shared_memory_entry.battery_level_left = 0;
921 shared_memory_entry.battery_level_right = 0;
922 shared_memory_entry.fullkey_color = {
923 .attribute = ColorAttribute::NoController,
924 .fullkey = {},
925 };
926 shared_memory_entry.joycon_color = {
927 .attribute = ColorAttribute::NoController,
928 .left = {},
929 .right = {},
930 };
931 shared_memory_entry.assignment_mode = NpadJoyAssignmentMode::Dual;
932 shared_memory_entry.applet_footer.type = AppletFooterUiType::None;
1019 933
1020 auto& controller = shared_memory_entries[npad_index]; 934 controller.is_connected = false;
1021 controller.style_set.raw = 0; // Zero out 935 controller.device->Disconnect();
1022 controller.device_type.raw = 0; 936 SignalStyleSetChangedEvent(npad_id);
1023 controller.system_properties.raw = 0; 937 WriteEmptyEntry(controller.shared_memory_entry);
1024 controller.button_properties.raw = 0; 938}
1025 controller.battery_level_dual = 0;
1026 controller.battery_level_left = 0;
1027 controller.battery_level_right = 0;
1028 controller.fullkey_color = {};
1029 controller.joycon_color = {};
1030 controller.assignment_mode = NpadAssignments::Dual;
1031 controller.footer_type = AppletFooterUiType::None;
1032 939
1033 SignalStyleSetChangedEvent(IndexToNPad(npad_index)); 940void Controller_NPad::SetGyroscopeZeroDriftMode(Core::HID::SixAxisSensorHandle sixaxis_handle,
941 GyroscopeZeroDriftMode drift_mode) {
942 if (!IsDeviceHandleValid(sixaxis_handle)) {
943 LOG_ERROR(Service_HID, "Invalid handle");
944 return;
945 }
946 auto& controller = GetControllerFromHandle(sixaxis_handle);
947 controller.gyroscope_zero_drift_mode = drift_mode;
1034} 948}
1035 949
1036void Controller_NPad::SetGyroscopeZeroDriftMode(GyroscopeZeroDriftMode drift_mode) { 950Controller_NPad::GyroscopeZeroDriftMode Controller_NPad::GetGyroscopeZeroDriftMode(
1037 gyroscope_zero_drift_mode = drift_mode; 951 Core::HID::SixAxisSensorHandle sixaxis_handle) const {
952 if (!IsDeviceHandleValid(sixaxis_handle)) {
953 LOG_ERROR(Service_HID, "Invalid handle");
954 // Return the default value
955 return GyroscopeZeroDriftMode::Standard;
956 }
957 const auto& controller = GetControllerFromHandle(sixaxis_handle);
958 return controller.gyroscope_zero_drift_mode;
1038} 959}
1039 960
1040Controller_NPad::GyroscopeZeroDriftMode Controller_NPad::GetGyroscopeZeroDriftMode() const { 961bool Controller_NPad::IsSixAxisSensorAtRest(Core::HID::SixAxisSensorHandle sixaxis_handle) const {
1041 return gyroscope_zero_drift_mode; 962 if (!IsDeviceHandleValid(sixaxis_handle)) {
963 LOG_ERROR(Service_HID, "Invalid handle");
964 // Return the default value
965 return true;
966 }
967 const auto& controller = GetControllerFromHandle(sixaxis_handle);
968 return controller.sixaxis_at_rest;
1042} 969}
1043 970
1044bool Controller_NPad::IsSixAxisSensorAtRest() const { 971void Controller_NPad::SetSixAxisEnabled(Core::HID::SixAxisSensorHandle sixaxis_handle,
1045 return sixaxis_at_rest; 972 bool sixaxis_status) {
973 if (!IsDeviceHandleValid(sixaxis_handle)) {
974 LOG_ERROR(Service_HID, "Invalid handle");
975 return;
976 }
977 auto& controller = GetControllerFromHandle(sixaxis_handle);
978 controller.sixaxis_sensor_enabled = sixaxis_status;
1046} 979}
1047 980
1048void Controller_NPad::SetSixAxisEnabled(bool six_axis_status) { 981void Controller_NPad::SetSixAxisFusionEnabled(Core::HID::SixAxisSensorHandle sixaxis_handle,
1049 sixaxis_sensors_enabled = six_axis_status; 982 bool sixaxis_fusion_status) {
983 if (!IsDeviceHandleValid(sixaxis_handle)) {
984 LOG_ERROR(Service_HID, "Invalid handle");
985 return;
986 }
987 auto& controller = GetControllerFromHandle(sixaxis_handle);
988 controller.sixaxis_fusion_enabled = sixaxis_fusion_status;
1050} 989}
1051 990
1052void Controller_NPad::SetSixAxisFusionParameters(f32 parameter1, f32 parameter2) { 991void Controller_NPad::SetSixAxisFusionParameters(
1053 sixaxis_fusion_parameter1 = parameter1; 992 Core::HID::SixAxisSensorHandle sixaxis_handle,
1054 sixaxis_fusion_parameter2 = parameter2; 993 Core::HID::SixAxisSensorFusionParameters sixaxis_fusion_parameters) {
994 if (!IsDeviceHandleValid(sixaxis_handle)) {
995 LOG_ERROR(Service_HID, "Invalid handle");
996 return;
997 }
998 auto& controller = GetControllerFromHandle(sixaxis_handle);
999 controller.sixaxis_fusion = sixaxis_fusion_parameters;
1055} 1000}
1056 1001
1057std::pair<f32, f32> Controller_NPad::GetSixAxisFusionParameters() { 1002Core::HID::SixAxisSensorFusionParameters Controller_NPad::GetSixAxisFusionParameters(
1058 return { 1003 Core::HID::SixAxisSensorHandle sixaxis_handle) {
1059 sixaxis_fusion_parameter1, 1004 if (!IsDeviceHandleValid(sixaxis_handle)) {
1060 sixaxis_fusion_parameter2, 1005 LOG_ERROR(Service_HID, "Invalid handle");
1061 }; 1006 // Since these parameters are unknow just return zeros
1007 return {};
1008 }
1009 auto& controller = GetControllerFromHandle(sixaxis_handle);
1010 return controller.sixaxis_fusion;
1062} 1011}
1063 1012
1064void Controller_NPad::ResetSixAxisFusionParameters() { 1013void Controller_NPad::ResetSixAxisFusionParameters(Core::HID::SixAxisSensorHandle sixaxis_handle) {
1065 sixaxis_fusion_parameter1 = 0.0f; 1014 if (!IsDeviceHandleValid(sixaxis_handle)) {
1066 sixaxis_fusion_parameter2 = 0.0f; 1015 LOG_ERROR(Service_HID, "Invalid handle");
1016 return;
1017 }
1018 auto& controller = GetControllerFromHandle(sixaxis_handle);
1019 // Since these parameters are unknow just fill with zeros
1020 controller.sixaxis_fusion = {};
1067} 1021}
1068 1022
1069void Controller_NPad::MergeSingleJoyAsDualJoy(u32 npad_id_1, u32 npad_id_2) { 1023void Controller_NPad::MergeSingleJoyAsDualJoy(Core::HID::NpadIdType npad_id_1,
1070 const auto npad_index_1 = NPadIdToIndex(npad_id_1); 1024 Core::HID::NpadIdType npad_id_2) {
1071 const auto npad_index_2 = NPadIdToIndex(npad_id_2); 1025 if (!IsNpadIdValid(npad_id_1) || !IsNpadIdValid(npad_id_2)) {
1026 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id_1:{}, npad_id_2:{}", npad_id_1,
1027 npad_id_2);
1028 return;
1029 }
1030 auto& controller_1 = GetControllerFromNpadIdType(npad_id_1).device;
1031 auto& controller_2 = GetControllerFromNpadIdType(npad_id_2).device;
1072 1032
1073 // If the controllers at both npad indices form a pair of left and right joycons, merge them. 1033 // If the controllers at both npad indices form a pair of left and right joycons, merge them.
1074 // Otherwise, do nothing. 1034 // Otherwise, do nothing.
1075 if ((connected_controllers[npad_index_1].type == NPadControllerType::JoyLeft && 1035 if ((controller_1->GetNpadStyleIndex() == Core::HID::NpadStyleIndex::JoyconLeft &&
1076 connected_controllers[npad_index_2].type == NPadControllerType::JoyRight) || 1036 controller_2->GetNpadStyleIndex() == Core::HID::NpadStyleIndex::JoyconRight) ||
1077 (connected_controllers[npad_index_2].type == NPadControllerType::JoyLeft && 1037 (controller_2->GetNpadStyleIndex() == Core::HID::NpadStyleIndex::JoyconLeft &&
1078 connected_controllers[npad_index_1].type == NPadControllerType::JoyRight)) { 1038 controller_1->GetNpadStyleIndex() == Core::HID::NpadStyleIndex::JoyconRight)) {
1079 // Disconnect the joycon at the second id and connect the dual joycon at the first index. 1039 // Disconnect the joycon at the second id and connect the dual joycon at the first index.
1080 DisconnectNpad(npad_id_2); 1040 DisconnectNpad(npad_id_2);
1081 AddNewControllerAt(NPadControllerType::JoyDual, npad_index_1); 1041 AddNewControllerAt(Core::HID::NpadStyleIndex::JoyconDual, npad_id_1);
1082 } 1042 }
1083} 1043}
1084 1044
@@ -1092,61 +1052,61 @@ void Controller_NPad::StopLRAssignmentMode() {
1092 is_in_lr_assignment_mode = false; 1052 is_in_lr_assignment_mode = false;
1093} 1053}
1094 1054
1095bool Controller_NPad::SwapNpadAssignment(u32 npad_id_1, u32 npad_id_2) { 1055bool Controller_NPad::SwapNpadAssignment(Core::HID::NpadIdType npad_id_1,
1096 if (npad_id_1 == NPAD_HANDHELD || npad_id_2 == NPAD_HANDHELD || npad_id_1 == NPAD_UNKNOWN || 1056 Core::HID::NpadIdType npad_id_2) {
1097 npad_id_2 == NPAD_UNKNOWN) { 1057 if (!IsNpadIdValid(npad_id_1) || !IsNpadIdValid(npad_id_2)) {
1058 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id_1:{}, npad_id_2:{}", npad_id_1,
1059 npad_id_2);
1060 return false;
1061 }
1062 if (npad_id_1 == Core::HID::NpadIdType::Handheld ||
1063 npad_id_2 == Core::HID::NpadIdType::Handheld || npad_id_1 == Core::HID::NpadIdType::Other ||
1064 npad_id_2 == Core::HID::NpadIdType::Other) {
1098 return true; 1065 return true;
1099 } 1066 }
1100 const auto npad_index_1 = NPadIdToIndex(npad_id_1); 1067 const auto& controller_1 = GetControllerFromNpadIdType(npad_id_1).device;
1101 const auto npad_index_2 = NPadIdToIndex(npad_id_2); 1068 const auto& controller_2 = GetControllerFromNpadIdType(npad_id_2).device;
1069 const auto type_index_1 = controller_1->GetNpadStyleIndex();
1070 const auto type_index_2 = controller_2->GetNpadStyleIndex();
1102 1071
1103 if (!IsControllerSupported(connected_controllers[npad_index_1].type) || 1072 if (!IsControllerSupported(type_index_1) || !IsControllerSupported(type_index_2)) {
1104 !IsControllerSupported(connected_controllers[npad_index_2].type)) {
1105 return false; 1073 return false;
1106 } 1074 }
1107 1075
1108 std::swap(connected_controllers[npad_index_1].type, connected_controllers[npad_index_2].type); 1076 AddNewControllerAt(type_index_2, npad_id_1);
1109 1077 AddNewControllerAt(type_index_1, npad_id_2);
1110 AddNewControllerAt(connected_controllers[npad_index_1].type, npad_index_1);
1111 AddNewControllerAt(connected_controllers[npad_index_2].type, npad_index_2);
1112 1078
1113 return true; 1079 return true;
1114} 1080}
1115 1081
1116Controller_NPad::LedPattern Controller_NPad::GetLedPattern(u32 npad_id) { 1082Core::HID::LedPattern Controller_NPad::GetLedPattern(Core::HID::NpadIdType npad_id) {
1117 if (npad_id == npad_id_list.back() || npad_id == npad_id_list[npad_id_list.size() - 2]) { 1083 if (!IsNpadIdValid(npad_id)) {
1118 // These are controllers without led patterns 1084 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
1119 return LedPattern{0, 0, 0, 0}; 1085 return Core::HID::LedPattern{0, 0, 0, 0};
1120 }
1121 switch (npad_id) {
1122 case 0:
1123 return LedPattern{1, 0, 0, 0};
1124 case 1:
1125 return LedPattern{1, 1, 0, 0};
1126 case 2:
1127 return LedPattern{1, 1, 1, 0};
1128 case 3:
1129 return LedPattern{1, 1, 1, 1};
1130 case 4:
1131 return LedPattern{1, 0, 0, 1};
1132 case 5:
1133 return LedPattern{1, 0, 1, 0};
1134 case 6:
1135 return LedPattern{1, 0, 1, 1};
1136 case 7:
1137 return LedPattern{0, 1, 1, 0};
1138 default:
1139 return LedPattern{0, 0, 0, 0};
1140 } 1086 }
1087 const auto& controller = GetControllerFromNpadIdType(npad_id).device;
1088 return controller->GetLedPattern();
1141} 1089}
1142 1090
1143bool Controller_NPad::IsUnintendedHomeButtonInputProtectionEnabled(u32 npad_id) const { 1091bool Controller_NPad::IsUnintendedHomeButtonInputProtectionEnabled(
1144 return unintended_home_button_input_protection[NPadIdToIndex(npad_id)]; 1092 Core::HID::NpadIdType npad_id) const {
1093 if (!IsNpadIdValid(npad_id)) {
1094 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
1095 // Return the default value
1096 return false;
1097 }
1098 const auto& controller = GetControllerFromNpadIdType(npad_id);
1099 return controller.unintended_home_button_input_protection;
1145} 1100}
1146 1101
1147void Controller_NPad::SetUnintendedHomeButtonInputProtectionEnabled(bool is_protection_enabled, 1102void Controller_NPad::SetUnintendedHomeButtonInputProtectionEnabled(bool is_protection_enabled,
1148 u32 npad_id) { 1103 Core::HID::NpadIdType npad_id) {
1149 unintended_home_button_input_protection[NPadIdToIndex(npad_id)] = is_protection_enabled; 1104 if (!IsNpadIdValid(npad_id)) {
1105 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
1106 return;
1107 }
1108 auto& controller = GetControllerFromNpadIdType(npad_id);
1109 controller.unintended_home_button_input_protection = is_protection_enabled;
1150} 1110}
1151 1111
1152void Controller_NPad::SetAnalogStickUseCenterClamp(bool use_center_clamp) { 1112void Controller_NPad::SetAnalogStickUseCenterClamp(bool use_center_clamp) {
@@ -1154,32 +1114,34 @@ void Controller_NPad::SetAnalogStickUseCenterClamp(bool use_center_clamp) {
1154} 1114}
1155 1115
1156void Controller_NPad::ClearAllConnectedControllers() { 1116void Controller_NPad::ClearAllConnectedControllers() {
1157 for (auto& controller : connected_controllers) { 1117 for (auto& controller : controller_data) {
1158 if (controller.is_connected && controller.type != NPadControllerType::None) { 1118 if (controller.device->IsConnected() &&
1159 controller.type = NPadControllerType::None; 1119 controller.device->GetNpadStyleIndex() != Core::HID::NpadStyleIndex::None) {
1160 controller.is_connected = false; 1120 controller.device->Disconnect();
1121 controller.device->SetNpadStyleIndex(Core::HID::NpadStyleIndex::None);
1161 } 1122 }
1162 } 1123 }
1163} 1124}
1164 1125
1165void Controller_NPad::DisconnectAllConnectedControllers() { 1126void Controller_NPad::DisconnectAllConnectedControllers() {
1166 for (auto& controller : connected_controllers) { 1127 for (auto& controller : controller_data) {
1167 controller.is_connected = false; 1128 controller.device->Disconnect();
1168 } 1129 }
1169} 1130}
1170 1131
1171void Controller_NPad::ConnectAllDisconnectedControllers() { 1132void Controller_NPad::ConnectAllDisconnectedControllers() {
1172 for (auto& controller : connected_controllers) { 1133 for (auto& controller : controller_data) {
1173 if (controller.type != NPadControllerType::None && !controller.is_connected) { 1134 if (controller.device->GetNpadStyleIndex() != Core::HID::NpadStyleIndex::None &&
1174 controller.is_connected = true; 1135 !controller.device->IsConnected()) {
1136 controller.device->Connect();
1175 } 1137 }
1176 } 1138 }
1177} 1139}
1178 1140
1179void Controller_NPad::ClearAllControllers() { 1141void Controller_NPad::ClearAllControllers() {
1180 for (auto& controller : connected_controllers) { 1142 for (auto& controller : controller_data) {
1181 controller.type = NPadControllerType::None; 1143 controller.device->Disconnect();
1182 controller.is_connected = false; 1144 controller.device->SetNpadStyleIndex(Core::HID::NpadStyleIndex::None);
1183 } 1145 }
1184} 1146}
1185 1147
@@ -1187,16 +1149,16 @@ u32 Controller_NPad::GetAndResetPressState() {
1187 return press_state.exchange(0); 1149 return press_state.exchange(0);
1188} 1150}
1189 1151
1190bool Controller_NPad::IsControllerSupported(NPadControllerType controller) const { 1152bool Controller_NPad::IsControllerSupported(Core::HID::NpadStyleIndex controller) const {
1191 if (controller == NPadControllerType::Handheld) { 1153 if (controller == Core::HID::NpadStyleIndex::Handheld) {
1192 const bool support_handheld = 1154 const bool support_handheld =
1193 std::find(supported_npad_id_types.begin(), supported_npad_id_types.end(), 1155 std::find(supported_npad_id_types.begin(), supported_npad_id_types.end(),
1194 NPAD_HANDHELD) != supported_npad_id_types.end(); 1156 Core::HID::NpadIdType::Handheld) != supported_npad_id_types.end();
1195 // Handheld is not even a supported type, lets stop here 1157 // Handheld is not even a supported type, lets stop here
1196 if (!support_handheld) { 1158 if (!support_handheld) {
1197 return false; 1159 return false;
1198 } 1160 }
1199 // Handheld should not be supported in docked mode 1161 // Handheld shouldn't be supported in docked mode
1200 if (Settings::values.use_docked_mode.GetValue()) { 1162 if (Settings::values.use_docked_mode.GetValue()) {
1201 return false; 1163 return false;
1202 } 1164 }
@@ -1205,20 +1167,31 @@ bool Controller_NPad::IsControllerSupported(NPadControllerType controller) const
1205 } 1167 }
1206 1168
1207 if (std::any_of(supported_npad_id_types.begin(), supported_npad_id_types.end(), 1169 if (std::any_of(supported_npad_id_types.begin(), supported_npad_id_types.end(),
1208 [](u32 npad_id) { return npad_id <= MAX_NPAD_ID; })) { 1170 [](Core::HID::NpadIdType npad_id) {
1171 return npad_id <= Core::HID::NpadIdType::Player8;
1172 })) {
1173 Core::HID::NpadStyleTag style = GetSupportedStyleSet();
1209 switch (controller) { 1174 switch (controller) {
1210 case NPadControllerType::ProController: 1175 case Core::HID::NpadStyleIndex::ProController:
1211 return style.fullkey; 1176 return style.fullkey;
1212 case NPadControllerType::JoyDual: 1177 case Core::HID::NpadStyleIndex::JoyconDual:
1213 return style.joycon_dual; 1178 return style.joycon_dual;
1214 case NPadControllerType::JoyLeft: 1179 case Core::HID::NpadStyleIndex::JoyconLeft:
1215 return style.joycon_left; 1180 return style.joycon_left;
1216 case NPadControllerType::JoyRight: 1181 case Core::HID::NpadStyleIndex::JoyconRight:
1217 return style.joycon_right; 1182 return style.joycon_right;
1218 case NPadControllerType::GameCube: 1183 case Core::HID::NpadStyleIndex::GameCube:
1219 return style.gamecube; 1184 return style.gamecube;
1220 case NPadControllerType::Pokeball: 1185 case Core::HID::NpadStyleIndex::Pokeball:
1221 return style.palma; 1186 return style.palma;
1187 case Core::HID::NpadStyleIndex::NES:
1188 return style.lark;
1189 case Core::HID::NpadStyleIndex::SNES:
1190 return style.lucia;
1191 case Core::HID::NpadStyleIndex::N64:
1192 return style.lagoon;
1193 case Core::HID::NpadStyleIndex::SegaGenesis:
1194 return style.lager;
1222 default: 1195 default:
1223 return false; 1196 return false;
1224 } 1197 }
@@ -1227,4 +1200,48 @@ bool Controller_NPad::IsControllerSupported(NPadControllerType controller) const
1227 return false; 1200 return false;
1228} 1201}
1229 1202
1203Controller_NPad::NpadControllerData& Controller_NPad::GetControllerFromHandle(
1204 const Core::HID::SixAxisSensorHandle& device_handle) {
1205 const auto npad_id = static_cast<Core::HID::NpadIdType>(device_handle.npad_id);
1206 return GetControllerFromNpadIdType(npad_id);
1207}
1208
1209const Controller_NPad::NpadControllerData& Controller_NPad::GetControllerFromHandle(
1210 const Core::HID::SixAxisSensorHandle& device_handle) const {
1211 const auto npad_id = static_cast<Core::HID::NpadIdType>(device_handle.npad_id);
1212 return GetControllerFromNpadIdType(npad_id);
1213}
1214
1215Controller_NPad::NpadControllerData& Controller_NPad::GetControllerFromHandle(
1216 const Core::HID::VibrationDeviceHandle& device_handle) {
1217 const auto npad_id = static_cast<Core::HID::NpadIdType>(device_handle.npad_id);
1218 return GetControllerFromNpadIdType(npad_id);
1219}
1220
1221const Controller_NPad::NpadControllerData& Controller_NPad::GetControllerFromHandle(
1222 const Core::HID::VibrationDeviceHandle& device_handle) const {
1223 const auto npad_id = static_cast<Core::HID::NpadIdType>(device_handle.npad_id);
1224 return GetControllerFromNpadIdType(npad_id);
1225}
1226
1227Controller_NPad::NpadControllerData& Controller_NPad::GetControllerFromNpadIdType(
1228 Core::HID::NpadIdType npad_id) {
1229 if (!IsNpadIdValid(npad_id)) {
1230 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
1231 npad_id = Core::HID::NpadIdType::Player1;
1232 }
1233 const auto npad_index = Core::HID::NpadIdTypeToIndex(npad_id);
1234 return controller_data[npad_index];
1235}
1236
1237const Controller_NPad::NpadControllerData& Controller_NPad::GetControllerFromNpadIdType(
1238 Core::HID::NpadIdType npad_id) const {
1239 if (!IsNpadIdValid(npad_id)) {
1240 LOG_ERROR(Service_HID, "Invalid NpadIdType npad_id:{}", npad_id);
1241 npad_id = Core::HID::NpadIdType::Player1;
1242 }
1243 const auto npad_index = Core::HID::NpadIdTypeToIndex(npad_id);
1244 return controller_data[npad_index];
1245}
1246
1230} // namespace Service::HID 1247} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/npad.h b/src/core/hle/service/hid/controllers/npad.h
index 9ee146caf..9fa113bb6 100644
--- a/src/core/hle/service/hid/controllers/npad.h
+++ b/src/core/hle/service/hid/controllers/npad.h
@@ -11,9 +11,14 @@
11#include "common/bit_field.h" 11#include "common/bit_field.h"
12#include "common/common_types.h" 12#include "common/common_types.h"
13#include "common/quaternion.h" 13#include "common/quaternion.h"
14#include "common/settings.h" 14#include "core/hid/hid_types.h"
15#include "core/frontend/input.h"
16#include "core/hle/service/hid/controllers/controller_base.h" 15#include "core/hle/service/hid/controllers/controller_base.h"
16#include "core/hle/service/hid/ring_lifo.h"
17
18namespace Core::HID {
19class EmulatedController;
20enum class ControllerTriggerType;
21} // namespace Core::HID
17 22
18namespace Kernel { 23namespace Kernel {
19class KEvent; 24class KEvent;
@@ -26,12 +31,9 @@ class ServiceContext;
26 31
27namespace Service::HID { 32namespace Service::HID {
28 33
29constexpr u32 NPAD_HANDHELD = 32;
30constexpr u32 NPAD_UNKNOWN = 16; // TODO(ogniK): What is this?
31
32class Controller_NPad final : public ControllerBase { 34class Controller_NPad final : public ControllerBase {
33public: 35public:
34 explicit Controller_NPad(Core::System& system_, 36 explicit Controller_NPad(Core::HID::HIDCore& hid_core_,
35 KernelHelpers::ServiceContext& service_context_); 37 KernelHelpers::ServiceContext& service_context_);
36 ~Controller_NPad() override; 38 ~Controller_NPad() override;
37 39
@@ -48,60 +50,39 @@ public:
48 void OnMotionUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 50 void OnMotionUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
49 std::size_t size) override; 51 std::size_t size) override;
50 52
51 // Called when input devices should be loaded 53 // This is nn::hid::GyroscopeZeroDriftMode
52 void OnLoadInputDevices() override;
53
54 enum class NPadControllerType {
55 None,
56 ProController,
57 Handheld,
58 JoyDual,
59 JoyLeft,
60 JoyRight,
61 GameCube,
62 Pokeball,
63 };
64
65 enum class NpadType : u8 {
66 ProController = 3,
67 Handheld = 4,
68 JoyconDual = 5,
69 JoyconLeft = 6,
70 JoyconRight = 7,
71 GameCube = 8,
72 Pokeball = 9,
73 MaxNpadType = 10,
74 };
75
76 enum class DeviceIndex : u8 {
77 Left = 0,
78 Right = 1,
79 None = 2,
80 MaxDeviceIndex = 3,
81 };
82
83 enum class GyroscopeZeroDriftMode : u32 { 54 enum class GyroscopeZeroDriftMode : u32 {
84 Loose = 0, 55 Loose = 0,
85 Standard = 1, 56 Standard = 1,
86 Tight = 2, 57 Tight = 2,
87 }; 58 };
88 59
89 enum class NpadHoldType : u64 { 60 // This is nn::hid::NpadJoyHoldType
61 enum class NpadJoyHoldType : u64 {
90 Vertical = 0, 62 Vertical = 0,
91 Horizontal = 1, 63 Horizontal = 1,
92 }; 64 };
93 65
94 enum class NpadAssignments : u32 { 66 // This is nn::hid::NpadJoyAssignmentMode
67 enum class NpadJoyAssignmentMode : u32 {
95 Dual = 0, 68 Dual = 0,
96 Single = 1, 69 Single = 1,
97 }; 70 };
98 71
72 // This is nn::hid::NpadJoyDeviceType
73 enum class NpadJoyDeviceType : s64 {
74 Left = 0,
75 Right = 1,
76 };
77
78 // This is nn::hid::NpadHandheldActivationMode
99 enum class NpadHandheldActivationMode : u64 { 79 enum class NpadHandheldActivationMode : u64 {
100 Dual = 0, 80 Dual = 0,
101 Single = 1, 81 Single = 1,
102 None = 2, 82 None = 2,
103 }; 83 };
104 84
85 // This is nn::hid::NpadCommunicationMode
105 enum class NpadCommunicationMode : u64 { 86 enum class NpadCommunicationMode : u64 {
106 Mode_5ms = 0, 87 Mode_5ms = 0,
107 Mode_10ms = 1, 88 Mode_10ms = 1,
@@ -109,74 +90,22 @@ public:
109 Default = 3, 90 Default = 3,
110 }; 91 };
111 92
112 struct DeviceHandle { 93 static constexpr Core::HID::VibrationValue DEFAULT_VIBRATION_VALUE{
113 NpadType npad_type; 94 .low_amplitude = 0.0f,
114 u8 npad_id; 95 .low_frequency = 160.0f,
115 DeviceIndex device_index; 96 .high_amplitude = 0.0f,
116 INSERT_PADDING_BYTES_NOINIT(1); 97 .high_frequency = 320.0f,
117 }; 98 };
118 static_assert(sizeof(DeviceHandle) == 4, "DeviceHandle is an invalid size");
119 99
120 struct NpadStyleSet { 100 void SetSupportedStyleSet(Core::HID::NpadStyleTag style_set);
121 union { 101 Core::HID::NpadStyleTag GetSupportedStyleSet() const;
122 u32_le raw{};
123
124 BitField<0, 1, u32> fullkey;
125 BitField<1, 1, u32> handheld;
126 BitField<2, 1, u32> joycon_dual;
127 BitField<3, 1, u32> joycon_left;
128 BitField<4, 1, u32> joycon_right;
129 BitField<5, 1, u32> gamecube;
130 BitField<6, 1, u32> palma;
131 BitField<7, 1, u32> lark;
132 BitField<8, 1, u32> handheld_lark;
133 BitField<9, 1, u32> lucia;
134 BitField<29, 1, u32> system_ext;
135 BitField<30, 1, u32> system;
136 };
137 };
138 static_assert(sizeof(NpadStyleSet) == 4, "NpadStyleSet is an invalid size");
139
140 struct VibrationValue {
141 f32 amp_low;
142 f32 freq_low;
143 f32 amp_high;
144 f32 freq_high;
145 };
146 static_assert(sizeof(VibrationValue) == 0x10, "Vibration is an invalid size");
147
148 static constexpr VibrationValue DEFAULT_VIBRATION_VALUE{
149 .amp_low = 0.0f,
150 .freq_low = 160.0f,
151 .amp_high = 0.0f,
152 .freq_high = 320.0f,
153 };
154
155 struct LedPattern {
156 explicit LedPattern(u64 light1, u64 light2, u64 light3, u64 light4) {
157 position1.Assign(light1);
158 position2.Assign(light2);
159 position3.Assign(light3);
160 position4.Assign(light4);
161 }
162 union {
163 u64 raw{};
164 BitField<0, 1, u64> position1;
165 BitField<1, 1, u64> position2;
166 BitField<2, 1, u64> position3;
167 BitField<3, 1, u64> position4;
168 };
169 };
170
171 void SetSupportedStyleSet(NpadStyleSet style_set);
172 NpadStyleSet GetSupportedStyleSet() const;
173 102
174 void SetSupportedNpadIdTypes(u8* data, std::size_t length); 103 void SetSupportedNpadIdTypes(u8* data, std::size_t length);
175 void GetSupportedNpadIdTypes(u32* data, std::size_t max_length); 104 void GetSupportedNpadIdTypes(u32* data, std::size_t max_length);
176 std::size_t GetSupportedNpadIdTypesSize() const; 105 std::size_t GetSupportedNpadIdTypesSize() const;
177 106
178 void SetHoldType(NpadHoldType joy_hold_type); 107 void SetHoldType(NpadJoyHoldType joy_hold_type);
179 NpadHoldType GetHoldType() const; 108 NpadJoyHoldType GetHoldType() const;
180 109
181 void SetNpadHandheldActivationMode(NpadHandheldActivationMode activation_mode); 110 void SetNpadHandheldActivationMode(NpadHandheldActivationMode activation_mode);
182 NpadHandheldActivationMode GetNpadHandheldActivationMode() const; 111 NpadHandheldActivationMode GetNpadHandheldActivationMode() const;
@@ -184,162 +113,106 @@ public:
184 void SetNpadCommunicationMode(NpadCommunicationMode communication_mode_); 113 void SetNpadCommunicationMode(NpadCommunicationMode communication_mode_);
185 NpadCommunicationMode GetNpadCommunicationMode() const; 114 NpadCommunicationMode GetNpadCommunicationMode() const;
186 115
187 void SetNpadMode(u32 npad_id, NpadAssignments assignment_mode); 116 void SetNpadMode(Core::HID::NpadIdType npad_id, NpadJoyAssignmentMode assignment_mode);
188 117
189 bool VibrateControllerAtIndex(std::size_t npad_index, std::size_t device_index, 118 bool VibrateControllerAtIndex(Core::HID::NpadIdType npad_id, std::size_t device_index,
190 const VibrationValue& vibration_value); 119 const Core::HID::VibrationValue& vibration_value);
191 120
192 void VibrateController(const DeviceHandle& vibration_device_handle, 121 void VibrateController(const Core::HID::VibrationDeviceHandle& vibration_device_handle,
193 const VibrationValue& vibration_value); 122 const Core::HID::VibrationValue& vibration_value);
194 123
195 void VibrateControllers(const std::vector<DeviceHandle>& vibration_device_handles, 124 void VibrateControllers(
196 const std::vector<VibrationValue>& vibration_values); 125 const std::vector<Core::HID::VibrationDeviceHandle>& vibration_device_handles,
126 const std::vector<Core::HID::VibrationValue>& vibration_values);
197 127
198 VibrationValue GetLastVibration(const DeviceHandle& vibration_device_handle) const; 128 Core::HID::VibrationValue GetLastVibration(
129 const Core::HID::VibrationDeviceHandle& vibration_device_handle) const;
199 130
200 void InitializeVibrationDevice(const DeviceHandle& vibration_device_handle); 131 void InitializeVibrationDevice(const Core::HID::VibrationDeviceHandle& vibration_device_handle);
201 132
202 void InitializeVibrationDeviceAtIndex(std::size_t npad_index, std::size_t device_index); 133 void InitializeVibrationDeviceAtIndex(Core::HID::NpadIdType npad_id, std::size_t device_index);
203 134
204 void SetPermitVibrationSession(bool permit_vibration_session); 135 void SetPermitVibrationSession(bool permit_vibration_session);
205 136
206 bool IsVibrationDeviceMounted(const DeviceHandle& vibration_device_handle) const; 137 bool IsVibrationDeviceMounted(
138 const Core::HID::VibrationDeviceHandle& vibration_device_handle) const;
207 139
208 Kernel::KReadableEvent& GetStyleSetChangedEvent(u32 npad_id); 140 Kernel::KReadableEvent& GetStyleSetChangedEvent(Core::HID::NpadIdType npad_id);
209 void SignalStyleSetChangedEvent(u32 npad_id) const; 141 void SignalStyleSetChangedEvent(Core::HID::NpadIdType npad_id) const;
210 142
211 // Adds a new controller at an index. 143 // Adds a new controller at an index.
212 void AddNewControllerAt(NPadControllerType controller, std::size_t npad_index); 144 void AddNewControllerAt(Core::HID::NpadStyleIndex controller, Core::HID::NpadIdType npad_id);
213 // Adds a new controller at an index with connection status. 145 // Adds a new controller at an index with connection status.
214 void UpdateControllerAt(NPadControllerType controller, std::size_t npad_index, bool connected); 146 void UpdateControllerAt(Core::HID::NpadStyleIndex controller, Core::HID::NpadIdType npad_id,
215 147 bool connected);
216 void DisconnectNpad(u32 npad_id); 148
217 void DisconnectNpadAtIndex(std::size_t index); 149 void DisconnectNpad(Core::HID::NpadIdType npad_id);
218 150
219 void SetGyroscopeZeroDriftMode(GyroscopeZeroDriftMode drift_mode); 151 void SetGyroscopeZeroDriftMode(Core::HID::SixAxisSensorHandle sixaxis_handle,
220 GyroscopeZeroDriftMode GetGyroscopeZeroDriftMode() const; 152 GyroscopeZeroDriftMode drift_mode);
221 bool IsSixAxisSensorAtRest() const; 153 GyroscopeZeroDriftMode GetGyroscopeZeroDriftMode(
222 void SetSixAxisEnabled(bool six_axis_status); 154 Core::HID::SixAxisSensorHandle sixaxis_handle) const;
223 void SetSixAxisFusionParameters(f32 parameter1, f32 parameter2); 155 bool IsSixAxisSensorAtRest(Core::HID::SixAxisSensorHandle sixaxis_handle) const;
224 std::pair<f32, f32> GetSixAxisFusionParameters(); 156 void SetSixAxisEnabled(Core::HID::SixAxisSensorHandle sixaxis_handle, bool sixaxis_status);
225 void ResetSixAxisFusionParameters(); 157 void SetSixAxisFusionEnabled(Core::HID::SixAxisSensorHandle sixaxis_handle,
226 LedPattern GetLedPattern(u32 npad_id); 158 bool sixaxis_fusion_status);
227 bool IsUnintendedHomeButtonInputProtectionEnabled(u32 npad_id) const; 159 void SetSixAxisFusionParameters(
228 void SetUnintendedHomeButtonInputProtectionEnabled(bool is_protection_enabled, u32 npad_id); 160 Core::HID::SixAxisSensorHandle sixaxis_handle,
161 Core::HID::SixAxisSensorFusionParameters sixaxis_fusion_parameters);
162 Core::HID::SixAxisSensorFusionParameters GetSixAxisFusionParameters(
163 Core::HID::SixAxisSensorHandle sixaxis_handle);
164 void ResetSixAxisFusionParameters(Core::HID::SixAxisSensorHandle sixaxis_handle);
165 Core::HID::LedPattern GetLedPattern(Core::HID::NpadIdType npad_id);
166 bool IsUnintendedHomeButtonInputProtectionEnabled(Core::HID::NpadIdType npad_id) const;
167 void SetUnintendedHomeButtonInputProtectionEnabled(bool is_protection_enabled,
168 Core::HID::NpadIdType npad_id);
229 void SetAnalogStickUseCenterClamp(bool use_center_clamp); 169 void SetAnalogStickUseCenterClamp(bool use_center_clamp);
230 void ClearAllConnectedControllers(); 170 void ClearAllConnectedControllers();
231 void DisconnectAllConnectedControllers(); 171 void DisconnectAllConnectedControllers();
232 void ConnectAllDisconnectedControllers(); 172 void ConnectAllDisconnectedControllers();
233 void ClearAllControllers(); 173 void ClearAllControllers();
234 174
235 void MergeSingleJoyAsDualJoy(u32 npad_id_1, u32 npad_id_2); 175 void MergeSingleJoyAsDualJoy(Core::HID::NpadIdType npad_id_1, Core::HID::NpadIdType npad_id_2);
236 void StartLRAssignmentMode(); 176 void StartLRAssignmentMode();
237 void StopLRAssignmentMode(); 177 void StopLRAssignmentMode();
238 bool SwapNpadAssignment(u32 npad_id_1, u32 npad_id_2); 178 bool SwapNpadAssignment(Core::HID::NpadIdType npad_id_1, Core::HID::NpadIdType npad_id_2);
239 179
240 // Logical OR for all buttons presses on all controllers 180 // Logical OR for all buttons presses on all controllers
241 // Specifically for cheat engine and other features. 181 // Specifically for cheat engine and other features.
242 u32 GetAndResetPressState(); 182 u32 GetAndResetPressState();
243 183
244 static Controller_NPad::NPadControllerType MapSettingsTypeToNPad(Settings::ControllerType type); 184 static bool IsNpadIdValid(Core::HID::NpadIdType npad_id);
245 static Settings::ControllerType MapNPadToSettingsType(Controller_NPad::NPadControllerType type); 185 static bool IsDeviceHandleValid(const Core::HID::SixAxisSensorHandle& device_handle);
246 static std::size_t NPadIdToIndex(u32 npad_id); 186 static bool IsDeviceHandleValid(const Core::HID::VibrationDeviceHandle& device_handle);
247 static u32 IndexToNPad(std::size_t index);
248 static bool IsNpadIdValid(u32 npad_id);
249 static bool IsDeviceHandleValid(const DeviceHandle& device_handle);
250 187
251private: 188private:
252 struct CommonHeader { 189 // This is nn::hid::detail::ColorAttribute
253 s64_le timestamp; 190 enum class ColorAttribute : u32 {
254 s64_le total_entry_count;
255 s64_le last_entry_index;
256 s64_le entry_count;
257 };
258 static_assert(sizeof(CommonHeader) == 0x20, "CommonHeader is an invalid size");
259
260 enum class ColorAttributes : u32_le {
261 Ok = 0, 191 Ok = 0,
262 ReadError = 1, 192 ReadError = 1,
263 NoController = 2, 193 NoController = 2,
264 }; 194 };
265 static_assert(sizeof(ColorAttributes) == 4, "ColorAttributes is an invalid size"); 195 static_assert(sizeof(ColorAttribute) == 4, "ColorAttribute is an invalid size");
266 196
267 struct ControllerColor { 197 // This is nn::hid::detail::NpadFullKeyColorState
268 u32_le body; 198 struct NpadFullKeyColorState {
269 u32_le button; 199 ColorAttribute attribute;
200 Core::HID::NpadControllerColor fullkey;
270 }; 201 };
271 static_assert(sizeof(ControllerColor) == 8, "ControllerColor is an invalid size"); 202 static_assert(sizeof(NpadFullKeyColorState) == 0xC, "NpadFullKeyColorState is an invalid size");
272 203
273 struct FullKeyColor { 204 // This is nn::hid::detail::NpadJoyColorState
274 ColorAttributes attribute; 205 struct NpadJoyColorState {
275 ControllerColor fullkey; 206 ColorAttribute attribute;
207 Core::HID::NpadControllerColor left;
208 Core::HID::NpadControllerColor right;
276 }; 209 };
277 static_assert(sizeof(FullKeyColor) == 0xC, "FullKeyColor is an invalid size"); 210 static_assert(sizeof(NpadJoyColorState) == 0x14, "NpadJoyColorState is an invalid size");
278 211
279 struct JoyconColor { 212 // This is nn::hid::NpadAttribute
280 ColorAttributes attribute; 213 struct NpadAttribute {
281 ControllerColor left;
282 ControllerColor right;
283 };
284 static_assert(sizeof(JoyconColor) == 0x14, "JoyconColor is an invalid size");
285
286 struct ControllerPadState {
287 union {
288 u64_le raw{};
289 // Button states
290 BitField<0, 1, u64> a;
291 BitField<1, 1, u64> b;
292 BitField<2, 1, u64> x;
293 BitField<3, 1, u64> y;
294 BitField<4, 1, u64> l_stick;
295 BitField<5, 1, u64> r_stick;
296 BitField<6, 1, u64> l;
297 BitField<7, 1, u64> r;
298 BitField<8, 1, u64> zl;
299 BitField<9, 1, u64> zr;
300 BitField<10, 1, u64> plus;
301 BitField<11, 1, u64> minus;
302
303 // D-Pad
304 BitField<12, 1, u64> d_left;
305 BitField<13, 1, u64> d_up;
306 BitField<14, 1, u64> d_right;
307 BitField<15, 1, u64> d_down;
308
309 // Left JoyStick
310 BitField<16, 1, u64> l_stick_left;
311 BitField<17, 1, u64> l_stick_up;
312 BitField<18, 1, u64> l_stick_right;
313 BitField<19, 1, u64> l_stick_down;
314
315 // Right JoyStick
316 BitField<20, 1, u64> r_stick_left;
317 BitField<21, 1, u64> r_stick_up;
318 BitField<22, 1, u64> r_stick_right;
319 BitField<23, 1, u64> r_stick_down;
320
321 // Not always active?
322 BitField<24, 1, u64> left_sl;
323 BitField<25, 1, u64> left_sr;
324
325 BitField<26, 1, u64> right_sl;
326 BitField<27, 1, u64> right_sr;
327
328 BitField<28, 1, u64> palma;
329 BitField<30, 1, u64> handheld_left_b;
330 };
331 };
332 static_assert(sizeof(ControllerPadState) == 8, "ControllerPadState is an invalid size");
333
334 struct AnalogPosition {
335 s32_le x;
336 s32_le y;
337 };
338 static_assert(sizeof(AnalogPosition) == 8, "AnalogPosition is an invalid size");
339
340 struct ConnectionState {
341 union { 214 union {
342 u32_le raw{}; 215 u32 raw{};
343 BitField<0, 1, u32> is_connected; 216 BitField<0, 1, u32> is_connected;
344 BitField<1, 1, u32> is_wired; 217 BitField<1, 1, u32> is_wired;
345 BitField<2, 1, u32> is_left_connected; 218 BitField<2, 1, u32> is_left_connected;
@@ -348,79 +221,60 @@ private:
348 BitField<5, 1, u32> is_right_wired; 221 BitField<5, 1, u32> is_right_wired;
349 }; 222 };
350 }; 223 };
351 static_assert(sizeof(ConnectionState) == 4, "ConnectionState is an invalid size"); 224 static_assert(sizeof(NpadAttribute) == 4, "NpadAttribute is an invalid size");
352 225
353 struct ControllerPad { 226 // This is nn::hid::NpadFullKeyState
354 ControllerPadState pad_states; 227 // This is nn::hid::NpadHandheldState
355 AnalogPosition l_stick; 228 // This is nn::hid::NpadJoyDualState
356 AnalogPosition r_stick; 229 // This is nn::hid::NpadJoyLeftState
357 }; 230 // This is nn::hid::NpadJoyRightState
358 static_assert(sizeof(ControllerPad) == 0x18, "ControllerPad is an invalid size"); 231 // This is nn::hid::NpadPalmaState
359 232 // This is nn::hid::NpadSystemExtState
360 struct GenericStates { 233 struct NPadGenericState {
361 s64_le timestamp; 234 s64_le sampling_number;
362 s64_le timestamp2; 235 Core::HID::NpadButtonState npad_buttons;
363 ControllerPad pad; 236 Core::HID::AnalogStickState l_stick;
364 ConnectionState connection_status; 237 Core::HID::AnalogStickState r_stick;
365 }; 238 NpadAttribute connection_status;
366 static_assert(sizeof(GenericStates) == 0x30, "NPadGenericStates is an invalid size"); 239 INSERT_PADDING_BYTES(4); // Reserved
367
368 struct NPadGeneric {
369 CommonHeader common;
370 std::array<GenericStates, 17> npad;
371 }; 240 };
372 static_assert(sizeof(NPadGeneric) == 0x350, "NPadGeneric is an invalid size"); 241 static_assert(sizeof(NPadGenericState) == 0x28, "NPadGenericState is an invalid size");
373 242
374 struct SixAxisAttributes { 243 // This is nn::hid::SixAxisSensorAttribute
244 struct SixAxisSensorAttribute {
375 union { 245 union {
376 u32_le raw{}; 246 u32 raw{};
377 BitField<0, 1, u32> is_connected; 247 BitField<0, 1, u32> is_connected;
378 BitField<1, 1, u32> is_interpolated; 248 BitField<1, 1, u32> is_interpolated;
379 }; 249 };
380 }; 250 };
381 static_assert(sizeof(SixAxisAttributes) == 4, "SixAxisAttributes is an invalid size"); 251 static_assert(sizeof(SixAxisSensorAttribute) == 4, "SixAxisSensorAttribute is an invalid size");
382 252
383 struct SixAxisStates { 253 // This is nn::hid::SixAxisSensorState
384 s64_le timestamp{}; 254 struct SixAxisSensorState {
385 INSERT_PADDING_WORDS(2); 255 s64 delta_time{};
386 s64_le timestamp2{}; 256 s64 sampling_number{};
387 Common::Vec3f accel{}; 257 Common::Vec3f accel{};
388 Common::Vec3f gyro{}; 258 Common::Vec3f gyro{};
389 Common::Vec3f rotation{}; 259 Common::Vec3f rotation{};
390 std::array<Common::Vec3f, 3> orientation{}; 260 std::array<Common::Vec3f, 3> orientation{};
391 SixAxisAttributes attribute; 261 SixAxisSensorAttribute attribute;
392 INSERT_PADDING_BYTES(4); // Reserved 262 INSERT_PADDING_BYTES(4); // Reserved
393 }; 263 };
394 static_assert(sizeof(SixAxisStates) == 0x68, "SixAxisStates is an invalid size"); 264 static_assert(sizeof(SixAxisSensorState) == 0x60, "SixAxisSensorState is an invalid size");
395
396 struct SixAxisGeneric {
397 CommonHeader common{};
398 std::array<SixAxisStates, 17> sixaxis{};
399 };
400 static_assert(sizeof(SixAxisGeneric) == 0x708, "SixAxisGeneric is an invalid size");
401 265
402 struct TriggerState { 266 // This is nn::hid::server::NpadGcTriggerState
403 s64_le timestamp{}; 267 struct NpadGcTriggerState {
404 s64_le timestamp2{}; 268 s64 sampling_number{};
405 s32_le l_analog{}; 269 s32 l_analog{};
406 s32_le r_analog{}; 270 s32 r_analog{};
407 }; 271 };
408 static_assert(sizeof(TriggerState) == 0x18, "TriggerState is an invalid size"); 272 static_assert(sizeof(NpadGcTriggerState) == 0x10, "NpadGcTriggerState is an invalid size");
409
410 struct TriggerGeneric {
411 INSERT_PADDING_BYTES(0x4);
412 s64_le timestamp;
413 INSERT_PADDING_BYTES(0x4);
414 s64_le total_entry_count;
415 s64_le last_entry_index;
416 s64_le entry_count;
417 std::array<TriggerState, 17> trigger{};
418 };
419 static_assert(sizeof(TriggerGeneric) == 0x1C8, "TriggerGeneric is an invalid size");
420 273
274 // This is nn::hid::NpadSystemProperties
421 struct NPadSystemProperties { 275 struct NPadSystemProperties {
422 union { 276 union {
423 s64_le raw{}; 277 s64 raw{};
424 BitField<0, 1, s64> is_charging_joy_dual; 278 BitField<0, 1, s64> is_charging_joy_dual;
425 BitField<1, 1, s64> is_charging_joy_left; 279 BitField<1, 1, s64> is_charging_joy_left;
426 BitField<2, 1, s64> is_charging_joy_right; 280 BitField<2, 1, s64> is_charging_joy_right;
@@ -438,17 +292,20 @@ private:
438 }; 292 };
439 static_assert(sizeof(NPadSystemProperties) == 0x8, "NPadSystemProperties is an invalid size"); 293 static_assert(sizeof(NPadSystemProperties) == 0x8, "NPadSystemProperties is an invalid size");
440 294
441 struct NPadButtonProperties { 295 // This is nn::hid::NpadSystemButtonProperties
296 struct NpadSystemButtonProperties {
442 union { 297 union {
443 s32_le raw{}; 298 s32 raw{};
444 BitField<0, 1, s32> is_home_button_protection_enabled; 299 BitField<0, 1, s32> is_home_button_protection_enabled;
445 }; 300 };
446 }; 301 };
447 static_assert(sizeof(NPadButtonProperties) == 0x4, "NPadButtonProperties is an invalid size"); 302 static_assert(sizeof(NpadSystemButtonProperties) == 0x4,
303 "NPadButtonProperties is an invalid size");
448 304
449 struct NPadDevice { 305 // This is nn::hid::system::DeviceType
306 struct DeviceType {
450 union { 307 union {
451 u32_le raw{}; 308 u32 raw{};
452 BitField<0, 1, s32> fullkey; 309 BitField<0, 1, s32> fullkey;
453 BitField<1, 1, s32> debug_pad; 310 BitField<1, 1, s32> debug_pad;
454 BitField<2, 1, s32> handheld_left; 311 BitField<2, 1, s32> handheld_left;
@@ -465,26 +322,29 @@ private:
465 BitField<13, 1, s32> handheld_lark_nes_left; 322 BitField<13, 1, s32> handheld_lark_nes_left;
466 BitField<14, 1, s32> handheld_lark_nes_right; 323 BitField<14, 1, s32> handheld_lark_nes_right;
467 BitField<15, 1, s32> lucia; 324 BitField<15, 1, s32> lucia;
325 BitField<16, 1, s32> lagon;
326 BitField<17, 1, s32> lager;
468 BitField<31, 1, s32> system; 327 BitField<31, 1, s32> system;
469 }; 328 };
470 }; 329 };
471 330
472 struct MotionDevice { 331 // This is nn::hid::detail::NfcXcdDeviceHandleStateImpl
473 Common::Vec3f accel; 332 struct NfcXcdDeviceHandleStateImpl {
474 Common::Vec3f gyro; 333 u64 handle;
475 Common::Vec3f rotation; 334 bool is_available;
476 std::array<Common::Vec3f, 3> orientation; 335 bool is_activated;
477 Common::Quaternion<f32> quaternion; 336 INSERT_PADDING_BYTES(0x6); // Reserved
478 }; 337 u64 sampling_number;
479
480 struct NfcXcdHandle {
481 INSERT_PADDING_BYTES(0x60);
482 }; 338 };
339 static_assert(sizeof(NfcXcdDeviceHandleStateImpl) == 0x18,
340 "NfcXcdDeviceHandleStateImpl is an invalid size");
483 341
342 // This is nn::hid::system::AppletFooterUiAttributesSet
484 struct AppletFooterUiAttributes { 343 struct AppletFooterUiAttributes {
485 INSERT_PADDING_BYTES(0x4); 344 INSERT_PADDING_BYTES(0x4);
486 }; 345 };
487 346
347 // This is nn::hid::system::AppletFooterUiType
488 enum class AppletFooterUiType : u8 { 348 enum class AppletFooterUiType : u8 {
489 None = 0, 349 None = 0,
490 HandheldNone = 1, 350 HandheldNone = 1,
@@ -510,95 +370,150 @@ private:
510 Lagon = 21, 370 Lagon = 21,
511 }; 371 };
512 372
513 struct NPadEntry { 373 struct AppletFooterUi {
514 NpadStyleSet style_set; 374 AppletFooterUiAttributes attributes;
515 NpadAssignments assignment_mode; 375 AppletFooterUiType type;
516 FullKeyColor fullkey_color; 376 INSERT_PADDING_BYTES(0x5B); // Reserved
517 JoyconColor joycon_color; 377 };
518 378 static_assert(sizeof(AppletFooterUi) == 0x60, "AppletFooterUi is an invalid size");
519 NPadGeneric fullkey_states; 379
520 NPadGeneric handheld_states; 380 // This is nn::hid::NpadLarkType
521 NPadGeneric joy_dual_states; 381 enum class NpadLarkType : u32 {
522 NPadGeneric joy_left_states; 382 Invalid,
523 NPadGeneric joy_right_states; 383 H1,
524 NPadGeneric palma_states; 384 H2,
525 NPadGeneric system_ext_states; 385 NL,
526 SixAxisGeneric sixaxis_fullkey; 386 NR,
527 SixAxisGeneric sixaxis_handheld; 387 };
528 SixAxisGeneric sixaxis_dual_left; 388
529 SixAxisGeneric sixaxis_dual_right; 389 // This is nn::hid::NpadLuciaType
530 SixAxisGeneric sixaxis_left; 390 enum class NpadLuciaType : u32 {
531 SixAxisGeneric sixaxis_right; 391 Invalid,
532 NPadDevice device_type; 392 J,
533 INSERT_PADDING_BYTES(0x4); // reserved 393 E,
394 U,
395 };
396
397 // This is nn::hid::NpadLagonType
398 enum class NpadLagonType : u32 {
399 Invalid,
400 };
401
402 // This is nn::hid::NpadLagerType
403 enum class NpadLagerType : u32 {
404 Invalid,
405 J,
406 E,
407 U,
408 };
409
410 // This is nn::hid::detail::NpadInternalState
411 struct NpadInternalState {
412 Core::HID::NpadStyleTag style_tag;
413 NpadJoyAssignmentMode assignment_mode;
414 NpadFullKeyColorState fullkey_color;
415 NpadJoyColorState joycon_color;
416 Lifo<NPadGenericState, hid_entry_count> fullkey_lifo;
417 Lifo<NPadGenericState, hid_entry_count> handheld_lifo;
418 Lifo<NPadGenericState, hid_entry_count> joy_dual_lifo;
419 Lifo<NPadGenericState, hid_entry_count> joy_left_lifo;
420 Lifo<NPadGenericState, hid_entry_count> joy_right_lifo;
421 Lifo<NPadGenericState, hid_entry_count> palma_lifo;
422 Lifo<NPadGenericState, hid_entry_count> system_ext_lifo;
423 Lifo<SixAxisSensorState, hid_entry_count> sixaxis_fullkey_lifo;
424 Lifo<SixAxisSensorState, hid_entry_count> sixaxis_handheld_lifo;
425 Lifo<SixAxisSensorState, hid_entry_count> sixaxis_dual_left_lifo;
426 Lifo<SixAxisSensorState, hid_entry_count> sixaxis_dual_right_lifo;
427 Lifo<SixAxisSensorState, hid_entry_count> sixaxis_left_lifo;
428 Lifo<SixAxisSensorState, hid_entry_count> sixaxis_right_lifo;
429 DeviceType device_type;
430 INSERT_PADDING_BYTES(0x4); // Reserved
534 NPadSystemProperties system_properties; 431 NPadSystemProperties system_properties;
535 NPadButtonProperties button_properties; 432 NpadSystemButtonProperties button_properties;
536 u32 battery_level_dual; 433 Core::HID::NpadBatteryLevel battery_level_dual;
537 u32 battery_level_left; 434 Core::HID::NpadBatteryLevel battery_level_left;
538 u32 battery_level_right; 435 Core::HID::NpadBatteryLevel battery_level_right;
539 AppletFooterUiAttributes footer_attributes; 436 union {
540 AppletFooterUiType footer_type; 437 Lifo<NfcXcdDeviceHandleStateImpl, 0x2> nfc_xcd_device_lifo{};
541 // nfc_states needs to be checked switchbrew does not match with HW 438 AppletFooterUi applet_footer;
542 NfcXcdHandle nfc_states; 439 };
543 INSERT_PADDING_BYTES(0x8); // Mutex 440 INSERT_PADDING_BYTES(0x20); // Unknown
544 TriggerGeneric gc_trigger_states; 441 Lifo<NpadGcTriggerState, hid_entry_count> gc_trigger_lifo;
545 INSERT_PADDING_BYTES(0xc1f); 442 NpadLarkType lark_type_l_and_main;
546 }; 443 NpadLarkType lark_type_r;
547 static_assert(sizeof(NPadEntry) == 0x5000, "NPadEntry is an invalid size"); 444 NpadLuciaType lucia_type;
548 445 NpadLagonType lagon_type;
549 struct ControllerHolder { 446 NpadLagerType lager_type;
550 NPadControllerType type; 447 // FW 13.x Investigate there is some sort of bitflag related to joycons
551 bool is_connected; 448 INSERT_PADDING_BYTES(0x4);
552 }; 449 INSERT_PADDING_BYTES(0xc08); // Unknown
553 450 };
554 void InitNewlyAddedController(std::size_t controller_idx); 451 static_assert(sizeof(NpadInternalState) == 0x5000, "NpadInternalState is an invalid size");
555 bool IsControllerSupported(NPadControllerType controller) const; 452
556 void RequestPadStateUpdate(u32 npad_id); 453 struct VibrationData {
454 bool device_mounted{};
455 Core::HID::VibrationValue latest_vibration_value{};
456 std::chrono::steady_clock::time_point last_vibration_timepoint{};
457 };
458
459 struct NpadControllerData {
460 Core::HID::EmulatedController* device;
461 Kernel::KEvent* styleset_changed_event{};
462 NpadInternalState shared_memory_entry{};
463
464 std::array<VibrationData, 2> vibration{};
465 bool unintended_home_button_input_protection{};
466 bool is_connected{};
467 Core::HID::NpadStyleIndex npad_type{Core::HID::NpadStyleIndex::None};
468
469 // Motion parameters
470 bool sixaxis_at_rest{true};
471 bool sixaxis_sensor_enabled{true};
472 bool sixaxis_fusion_enabled{false};
473 Core::HID::SixAxisSensorFusionParameters sixaxis_fusion{};
474 GyroscopeZeroDriftMode gyroscope_zero_drift_mode{GyroscopeZeroDriftMode::Standard};
475
476 // Current pad state
477 NPadGenericState npad_pad_state{};
478 NPadGenericState npad_libnx_state{};
479 NpadGcTriggerState npad_trigger_state{};
480 SixAxisSensorState sixaxis_fullkey_state{};
481 SixAxisSensorState sixaxis_handheld_state{};
482 SixAxisSensorState sixaxis_dual_left_state{};
483 SixAxisSensorState sixaxis_dual_right_state{};
484 SixAxisSensorState sixaxis_left_lifo_state{};
485 SixAxisSensorState sixaxis_right_lifo_state{};
486 int callback_key;
487 };
488
489 void ControllerUpdate(Core::HID::ControllerTriggerType type, std::size_t controller_idx);
490 void InitNewlyAddedController(Core::HID::NpadIdType npad_id);
491 bool IsControllerSupported(Core::HID::NpadStyleIndex controller) const;
492 void RequestPadStateUpdate(Core::HID::NpadIdType npad_id);
493 void WriteEmptyEntry(NpadInternalState& npad);
494
495 NpadControllerData& GetControllerFromHandle(
496 const Core::HID::SixAxisSensorHandle& device_handle);
497 const NpadControllerData& GetControllerFromHandle(
498 const Core::HID::SixAxisSensorHandle& device_handle) const;
499 NpadControllerData& GetControllerFromHandle(
500 const Core::HID::VibrationDeviceHandle& device_handle);
501 const NpadControllerData& GetControllerFromHandle(
502 const Core::HID::VibrationDeviceHandle& device_handle) const;
503 NpadControllerData& GetControllerFromNpadIdType(Core::HID::NpadIdType npad_id);
504 const NpadControllerData& GetControllerFromNpadIdType(Core::HID::NpadIdType npad_id) const;
557 505
558 std::atomic<u32> press_state{}; 506 std::atomic<u32> press_state{};
559 507
560 NpadStyleSet style{}; 508 std::array<NpadControllerData, 10> controller_data{};
561 std::array<NPadEntry, 10> shared_memory_entries{};
562 using ButtonArray = std::array<
563 std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeButton::NUM_BUTTONS_HID>,
564 10>;
565 using StickArray = std::array<
566 std::array<std::unique_ptr<Input::AnalogDevice>, Settings::NativeAnalog::NUM_STICKS_HID>,
567 10>;
568 using VibrationArray = std::array<std::array<std::unique_ptr<Input::VibrationDevice>,
569 Settings::NativeVibration::NUM_VIBRATIONS_HID>,
570 10>;
571 using MotionArray = std::array<
572 std::array<std::unique_ptr<Input::MotionDevice>, Settings::NativeMotion::NUM_MOTIONS_HID>,
573 10>;
574
575 KernelHelpers::ServiceContext& service_context; 509 KernelHelpers::ServiceContext& service_context;
576 std::mutex mutex; 510 std::mutex mutex;
577 ButtonArray buttons; 511 std::vector<Core::HID::NpadIdType> supported_npad_id_types{};
578 StickArray sticks; 512 NpadJoyHoldType hold_type{NpadJoyHoldType::Vertical};
579 VibrationArray vibrations;
580 MotionArray motions;
581 std::vector<u32> supported_npad_id_types{};
582 NpadHoldType hold_type{NpadHoldType::Vertical};
583 NpadHandheldActivationMode handheld_activation_mode{NpadHandheldActivationMode::Dual}; 513 NpadHandheldActivationMode handheld_activation_mode{NpadHandheldActivationMode::Dual};
584 NpadCommunicationMode communication_mode{NpadCommunicationMode::Default}; 514 NpadCommunicationMode communication_mode{NpadCommunicationMode::Default};
585 // Each controller should have their own styleset changed event
586 std::array<Kernel::KEvent*, 10> styleset_changed_events{};
587 std::array<std::array<std::chrono::steady_clock::time_point, 2>, 10>
588 last_vibration_timepoints{};
589 std::array<std::array<VibrationValue, 2>, 10> latest_vibration_values{};
590 bool permit_vibration_session_enabled{false}; 515 bool permit_vibration_session_enabled{false};
591 std::array<std::array<bool, 2>, 10> vibration_devices_mounted{};
592 std::array<ControllerHolder, 10> connected_controllers{};
593 std::array<bool, 10> unintended_home_button_input_protection{};
594 bool analog_stick_use_center_clamp{}; 516 bool analog_stick_use_center_clamp{};
595 GyroscopeZeroDriftMode gyroscope_zero_drift_mode{GyroscopeZeroDriftMode::Standard};
596 bool sixaxis_sensors_enabled{true};
597 f32 sixaxis_fusion_parameter1{};
598 f32 sixaxis_fusion_parameter2{};
599 bool sixaxis_at_rest{true};
600 std::array<ControllerPad, 10> npad_pad_states{};
601 std::array<TriggerState, 10> npad_trigger_states{};
602 bool is_in_lr_assignment_mode{false}; 517 bool is_in_lr_assignment_mode{false};
603}; 518};
604} // namespace Service::HID 519} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/stubbed.cpp b/src/core/hle/service/hid/controllers/stubbed.cpp
index 772c20453..b7d7a5756 100644
--- a/src/core/hle/service/hid/controllers/stubbed.cpp
+++ b/src/core/hle/service/hid/controllers/stubbed.cpp
@@ -5,11 +5,12 @@
5#include <cstring> 5#include <cstring>
6#include "common/common_types.h" 6#include "common/common_types.h"
7#include "core/core_timing.h" 7#include "core/core_timing.h"
8#include "core/hid/hid_core.h"
8#include "core/hle/service/hid/controllers/stubbed.h" 9#include "core/hle/service/hid/controllers/stubbed.h"
9 10
10namespace Service::HID { 11namespace Service::HID {
11 12
12Controller_Stubbed::Controller_Stubbed(Core::System& system_) : ControllerBase{system_} {} 13Controller_Stubbed::Controller_Stubbed(Core::HID::HIDCore& hid_core_) : ControllerBase{hid_core_} {}
13Controller_Stubbed::~Controller_Stubbed() = default; 14Controller_Stubbed::~Controller_Stubbed() = default;
14 15
15void Controller_Stubbed::OnInit() {} 16void Controller_Stubbed::OnInit() {}
@@ -31,10 +32,9 @@ void Controller_Stubbed::OnUpdate(const Core::Timing::CoreTiming& core_timing, u
31 std::memcpy(data + common_offset, &header, sizeof(CommonHeader)); 32 std::memcpy(data + common_offset, &header, sizeof(CommonHeader));
32} 33}
33 34
34void Controller_Stubbed::OnLoadInputDevices() {}
35
36void Controller_Stubbed::SetCommonHeaderOffset(std::size_t off) { 35void Controller_Stubbed::SetCommonHeaderOffset(std::size_t off) {
37 common_offset = off; 36 common_offset = off;
38 smart_update = true; 37 smart_update = true;
39} 38}
39
40} // namespace Service::HID 40} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/stubbed.h b/src/core/hle/service/hid/controllers/stubbed.h
index 21092af0d..0044a4efa 100644
--- a/src/core/hle/service/hid/controllers/stubbed.h
+++ b/src/core/hle/service/hid/controllers/stubbed.h
@@ -10,7 +10,7 @@
10namespace Service::HID { 10namespace Service::HID {
11class Controller_Stubbed final : public ControllerBase { 11class Controller_Stubbed final : public ControllerBase {
12public: 12public:
13 explicit Controller_Stubbed(Core::System& system_); 13 explicit Controller_Stubbed(Core::HID::HIDCore& hid_core_);
14 ~Controller_Stubbed() override; 14 ~Controller_Stubbed() override;
15 15
16 // Called when the controller is initialized 16 // Called when the controller is initialized
@@ -22,12 +22,17 @@ public:
22 // When the controller is requesting an update for the shared memory 22 // When the controller is requesting an update for the shared memory
23 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override; 23 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override;
24 24
25 // Called when input devices should be loaded
26 void OnLoadInputDevices() override;
27
28 void SetCommonHeaderOffset(std::size_t off); 25 void SetCommonHeaderOffset(std::size_t off);
29 26
30private: 27private:
28 struct CommonHeader {
29 s64 timestamp;
30 s64 total_entry_count;
31 s64 last_entry_index;
32 s64 entry_count;
33 };
34 static_assert(sizeof(CommonHeader) == 0x20, "CommonHeader is an invalid size");
35
31 bool smart_update{}; 36 bool smart_update{};
32 std::size_t common_offset{}; 37 std::size_t common_offset{};
33}; 38};
diff --git a/src/core/hle/service/hid/controllers/touchscreen.cpp b/src/core/hle/service/hid/controllers/touchscreen.cpp
index 6ef17acc5..48978e5c6 100644
--- a/src/core/hle/service/hid/controllers/touchscreen.cpp
+++ b/src/core/hle/service/hid/controllers/touchscreen.cpp
@@ -7,72 +7,82 @@
7#include "common/common_types.h" 7#include "common/common_types.h"
8#include "common/logging/log.h" 8#include "common/logging/log.h"
9#include "common/settings.h" 9#include "common/settings.h"
10#include "core/core.h"
10#include "core/core_timing.h" 11#include "core/core_timing.h"
11#include "core/frontend/emu_window.h" 12#include "core/frontend/emu_window.h"
12#include "core/frontend/input.h" 13#include "core/hid/emulated_console.h"
14#include "core/hid/hid_core.h"
13#include "core/hle/service/hid/controllers/touchscreen.h" 15#include "core/hle/service/hid/controllers/touchscreen.h"
14 16
15namespace Service::HID { 17namespace Service::HID {
16constexpr std::size_t SHARED_MEMORY_OFFSET = 0x400; 18constexpr std::size_t SHARED_MEMORY_OFFSET = 0x400;
17 19
18Controller_Touchscreen::Controller_Touchscreen(Core::System& system_) : ControllerBase{system_} {} 20Controller_Touchscreen::Controller_Touchscreen(Core::HID::HIDCore& hid_core_)
21 : ControllerBase{hid_core_} {
22 console = hid_core.GetEmulatedConsole();
23}
24
19Controller_Touchscreen::~Controller_Touchscreen() = default; 25Controller_Touchscreen::~Controller_Touchscreen() = default;
20 26
21void Controller_Touchscreen::OnInit() { 27void Controller_Touchscreen::OnInit() {}
22 for (std::size_t id = 0; id < MAX_FINGERS; ++id) {
23 mouse_finger_id[id] = MAX_FINGERS;
24 keyboard_finger_id[id] = MAX_FINGERS;
25 udp_finger_id[id] = MAX_FINGERS;
26 }
27}
28 28
29void Controller_Touchscreen::OnRelease() {} 29void Controller_Touchscreen::OnRelease() {}
30 30
31void Controller_Touchscreen::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 31void Controller_Touchscreen::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
32 std::size_t size) { 32 std::size_t size) {
33 shared_memory.header.timestamp = core_timing.GetCPUTicks(); 33 touch_screen_lifo.timestamp = core_timing.GetCPUTicks();
34 shared_memory.header.total_entry_count = 17;
35 34
36 if (!IsControllerActivated()) { 35 if (!IsControllerActivated()) {
37 shared_memory.header.entry_count = 0; 36 touch_screen_lifo.buffer_count = 0;
38 shared_memory.header.last_entry_index = 0; 37 touch_screen_lifo.buffer_tail = 0;
38 std::memcpy(data, &touch_screen_lifo, sizeof(touch_screen_lifo));
39 return; 39 return;
40 } 40 }
41 shared_memory.header.entry_count = 16;
42 41
43 const auto& last_entry = 42 const auto touch_status = console->GetTouch();
44 shared_memory.shared_memory_entries[shared_memory.header.last_entry_index]; 43 for (std::size_t id = 0; id < MAX_FINGERS; id++) {
45 shared_memory.header.last_entry_index = (shared_memory.header.last_entry_index + 1) % 17; 44 const auto& current_touch = touch_status[id];
46 auto& cur_entry = shared_memory.shared_memory_entries[shared_memory.header.last_entry_index]; 45 auto& finger = fingers[id];
46 finger.position = current_touch.position;
47 finger.id = current_touch.id;
47 48
48 cur_entry.sampling_number = last_entry.sampling_number + 1; 49 if (finger.attribute.start_touch) {
49 cur_entry.sampling_number2 = cur_entry.sampling_number; 50 finger.attribute.raw = 0;
51 continue;
52 }
50 53
51 const Input::TouchStatus& mouse_status = touch_mouse_device->GetStatus(); 54 if (finger.attribute.end_touch) {
52 const Input::TouchStatus& udp_status = touch_udp_device->GetStatus(); 55 finger.attribute.raw = 0;
53 for (std::size_t id = 0; id < mouse_status.size(); ++id) { 56 finger.pressed = false;
54 mouse_finger_id[id] = UpdateTouchInputEvent(mouse_status[id], mouse_finger_id[id]); 57 continue;
55 udp_finger_id[id] = UpdateTouchInputEvent(udp_status[id], udp_finger_id[id]); 58 }
56 } 59
60 if (!finger.pressed && current_touch.pressed) {
61 finger.attribute.start_touch.Assign(1);
62 finger.pressed = true;
63 continue;
64 }
57 65
58 if (Settings::values.use_touch_from_button) { 66 if (finger.pressed && !current_touch.pressed) {
59 const Input::TouchStatus& keyboard_status = touch_btn_device->GetStatus(); 67 finger.attribute.raw = 0;
60 for (std::size_t id = 0; id < mouse_status.size(); ++id) { 68 finger.attribute.end_touch.Assign(1);
61 keyboard_finger_id[id] =
62 UpdateTouchInputEvent(keyboard_status[id], keyboard_finger_id[id]);
63 } 69 }
64 } 70 }
65 71
66 std::array<Finger, 16> active_fingers; 72 std::array<Core::HID::TouchFinger, MAX_FINGERS> active_fingers;
67 const auto end_iter = std::copy_if(fingers.begin(), fingers.end(), active_fingers.begin(), 73 const auto end_iter = std::copy_if(fingers.begin(), fingers.end(), active_fingers.begin(),
68 [](const auto& finger) { return finger.pressed; }); 74 [](const auto& finger) { return finger.pressed; });
69 const auto active_fingers_count = 75 const auto active_fingers_count =
70 static_cast<std::size_t>(std::distance(active_fingers.begin(), end_iter)); 76 static_cast<std::size_t>(std::distance(active_fingers.begin(), end_iter));
71 77
72 const u64 tick = core_timing.GetCPUTicks(); 78 const u64 tick = core_timing.GetCPUTicks();
73 cur_entry.entry_count = static_cast<s32_le>(active_fingers_count); 79 const auto& last_entry = touch_screen_lifo.ReadCurrentEntry().state;
80
81 next_state.sampling_number = last_entry.sampling_number + 1;
82 next_state.entry_count = static_cast<s32>(active_fingers_count);
83
74 for (std::size_t id = 0; id < MAX_FINGERS; ++id) { 84 for (std::size_t id = 0; id < MAX_FINGERS; ++id) {
75 auto& touch_entry = cur_entry.states[id]; 85 auto& touch_entry = next_state.states[id];
76 if (id < active_fingers_count) { 86 if (id < active_fingers_count) {
77 const auto& [active_x, active_y] = active_fingers[id].position; 87 const auto& [active_x, active_y] = active_fingers[id].position;
78 touch_entry.position = { 88 touch_entry.position = {
@@ -97,66 +107,9 @@ void Controller_Touchscreen::OnUpdate(const Core::Timing::CoreTiming& core_timin
97 touch_entry.finger = 0; 107 touch_entry.finger = 0;
98 } 108 }
99 } 109 }
100 std::memcpy(data + SHARED_MEMORY_OFFSET, &shared_memory, sizeof(TouchScreenSharedMemory));
101}
102
103void Controller_Touchscreen::OnLoadInputDevices() {
104 touch_mouse_device = Input::CreateDevice<Input::TouchDevice>("engine:emu_window");
105 touch_udp_device = Input::CreateDevice<Input::TouchDevice>("engine:cemuhookudp");
106 touch_btn_device = Input::CreateDevice<Input::TouchDevice>("engine:touch_from_button");
107}
108
109std::optional<std::size_t> Controller_Touchscreen::GetUnusedFingerID() const {
110 // Dont assign any touch input to a finger if disabled
111 if (!Settings::values.touchscreen.enabled) {
112 return std::nullopt;
113 }
114 std::size_t first_free_id = 0;
115 while (first_free_id < MAX_FINGERS) {
116 if (!fingers[first_free_id].pressed) {
117 return first_free_id;
118 } else {
119 first_free_id++;
120 }
121 }
122 return std::nullopt;
123}
124
125std::size_t Controller_Touchscreen::UpdateTouchInputEvent(
126 const std::tuple<float, float, bool>& touch_input, std::size_t finger_id) {
127 const auto& [x, y, pressed] = touch_input;
128 if (finger_id > MAX_FINGERS) {
129 LOG_ERROR(Service_HID, "Invalid finger id {}", finger_id);
130 return MAX_FINGERS;
131 }
132 if (pressed) {
133 Attributes attribute{};
134 if (finger_id == MAX_FINGERS) {
135 const auto first_free_id = GetUnusedFingerID();
136 if (!first_free_id) {
137 // Invalid finger id do nothing
138 return MAX_FINGERS;
139 }
140 finger_id = first_free_id.value();
141 fingers[finger_id].pressed = true;
142 fingers[finger_id].id = static_cast<u32_le>(finger_id);
143 attribute.start_touch.Assign(1);
144 }
145 fingers[finger_id].position = {x, y};
146 fingers[finger_id].attribute = attribute;
147 return finger_id;
148 }
149
150 if (finger_id != MAX_FINGERS) {
151 if (!fingers[finger_id].attribute.end_touch) {
152 fingers[finger_id].attribute.end_touch.Assign(1);
153 fingers[finger_id].attribute.start_touch.Assign(0);
154 return finger_id;
155 }
156 fingers[finger_id].pressed = false;
157 }
158 110
159 return MAX_FINGERS; 111 touch_screen_lifo.WriteNextEntry(next_state);
112 std::memcpy(data + SHARED_MEMORY_OFFSET, &touch_screen_lifo, sizeof(touch_screen_lifo));
160} 113}
161 114
162} // namespace Service::HID 115} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/touchscreen.h b/src/core/hle/service/hid/controllers/touchscreen.h
index 8e9b40c0a..708dde4f0 100644
--- a/src/core/hle/service/hid/controllers/touchscreen.h
+++ b/src/core/hle/service/hid/controllers/touchscreen.h
@@ -9,18 +9,25 @@
9#include "common/common_types.h" 9#include "common/common_types.h"
10#include "common/point.h" 10#include "common/point.h"
11#include "common/swap.h" 11#include "common/swap.h"
12#include "core/frontend/input.h" 12#include "core/hid/hid_types.h"
13#include "core/hle/service/hid/controllers/controller_base.h" 13#include "core/hle/service/hid/controllers/controller_base.h"
14#include "core/hle/service/hid/ring_lifo.h"
15
16namespace Core::HID {
17class EmulatedConsole;
18} // namespace Core::HID
14 19
15namespace Service::HID { 20namespace Service::HID {
16class Controller_Touchscreen final : public ControllerBase { 21class Controller_Touchscreen final : public ControllerBase {
17public: 22public:
23 // This is nn::hid::TouchScreenModeForNx
18 enum class TouchScreenModeForNx : u8 { 24 enum class TouchScreenModeForNx : u8 {
19 UseSystemSetting, 25 UseSystemSetting,
20 Finger, 26 Finger,
21 Heat2, 27 Heat2,
22 }; 28 };
23 29
30 // This is nn::hid::TouchScreenConfigurationForNx
24 struct TouchScreenConfigurationForNx { 31 struct TouchScreenConfigurationForNx {
25 TouchScreenModeForNx mode; 32 TouchScreenModeForNx mode;
26 INSERT_PADDING_BYTES_NOINIT(0x7); 33 INSERT_PADDING_BYTES_NOINIT(0x7);
@@ -29,7 +36,7 @@ public:
29 static_assert(sizeof(TouchScreenConfigurationForNx) == 0x17, 36 static_assert(sizeof(TouchScreenConfigurationForNx) == 0x17,
30 "TouchScreenConfigurationForNx is an invalid size"); 37 "TouchScreenConfigurationForNx is an invalid size");
31 38
32 explicit Controller_Touchscreen(Core::System& system_); 39 explicit Controller_Touchscreen(Core::HID::HIDCore& hid_core_);
33 ~Controller_Touchscreen() override; 40 ~Controller_Touchscreen() override;
34 41
35 // Called when the controller is initialized 42 // Called when the controller is initialized
@@ -41,73 +48,24 @@ public:
41 // When the controller is requesting an update for the shared memory 48 // When the controller is requesting an update for the shared memory
42 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override; 49 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override;
43 50
44 // Called when input devices should be loaded
45 void OnLoadInputDevices() override;
46
47private: 51private:
48 static constexpr std::size_t MAX_FINGERS = 16; 52 static constexpr std::size_t MAX_FINGERS = 16;
49 53
50 // Returns an unused finger id, if there is no fingers available std::nullopt will be returned 54 // This is nn::hid::TouchScreenState
51 std::optional<std::size_t> GetUnusedFingerID() const; 55 struct TouchScreenState {
52 56 s64 sampling_number;
53 // If the touch is new it tries to assing a new finger id, if there is no fingers avaliable no 57 s32 entry_count;
54 // changes will be made. Updates the coordinates if the finger id it's already set. If the touch 58 INSERT_PADDING_BYTES(4); // Reserved
55 // ends delays the output by one frame to set the end_touch flag before finally freeing the 59 std::array<Core::HID::TouchState, MAX_FINGERS> states;
56 // finger id
57 std::size_t UpdateTouchInputEvent(const std::tuple<float, float, bool>& touch_input,
58 std::size_t finger_id);
59
60 struct Attributes {
61 union {
62 u32 raw{};
63 BitField<0, 1, u32> start_touch;
64 BitField<1, 1, u32> end_touch;
65 };
66 };
67 static_assert(sizeof(Attributes) == 0x4, "Attributes is an invalid size");
68
69 struct TouchState {
70 u64_le delta_time;
71 Attributes attribute;
72 u32_le finger;
73 Common::Point<u32_le> position;
74 u32_le diameter_x;
75 u32_le diameter_y;
76 u32_le rotation_angle;
77 }; 60 };
78 static_assert(sizeof(TouchState) == 0x28, "Touchstate is an invalid size"); 61 static_assert(sizeof(TouchScreenState) == 0x290, "TouchScreenState is an invalid size");
79 62
80 struct TouchScreenEntry { 63 // This is nn::hid::detail::TouchScreenLifo
81 s64_le sampling_number; 64 Lifo<TouchScreenState, hid_entry_count> touch_screen_lifo{};
82 s64_le sampling_number2; 65 static_assert(sizeof(touch_screen_lifo) == 0x2C38, "touch_screen_lifo is an invalid size");
83 s32_le entry_count; 66 TouchScreenState next_state{};
84 std::array<TouchState, MAX_FINGERS> states;
85 };
86 static_assert(sizeof(TouchScreenEntry) == 0x298, "TouchScreenEntry is an invalid size");
87
88 struct TouchScreenSharedMemory {
89 CommonHeader header;
90 std::array<TouchScreenEntry, 17> shared_memory_entries{};
91 INSERT_PADDING_BYTES(0x3c8);
92 };
93 static_assert(sizeof(TouchScreenSharedMemory) == 0x3000,
94 "TouchScreenSharedMemory is an invalid size");
95
96 struct Finger {
97 u64_le last_touch{};
98 Common::Point<float> position;
99 u32_le id{};
100 bool pressed{};
101 Attributes attribute;
102 };
103 67
104 TouchScreenSharedMemory shared_memory{}; 68 std::array<Core::HID::TouchFinger, MAX_FINGERS> fingers;
105 std::unique_ptr<Input::TouchDevice> touch_mouse_device; 69 Core::HID::EmulatedConsole* console;
106 std::unique_ptr<Input::TouchDevice> touch_udp_device;
107 std::unique_ptr<Input::TouchDevice> touch_btn_device;
108 std::array<std::size_t, MAX_FINGERS> mouse_finger_id;
109 std::array<std::size_t, MAX_FINGERS> keyboard_finger_id;
110 std::array<std::size_t, MAX_FINGERS> udp_finger_id;
111 std::array<Finger, MAX_FINGERS> fingers;
112}; 70};
113} // namespace Service::HID 71} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/xpad.cpp b/src/core/hle/service/hid/controllers/xpad.cpp
index 41dc22cf9..e4da16466 100644
--- a/src/core/hle/service/hid/controllers/xpad.cpp
+++ b/src/core/hle/service/hid/controllers/xpad.cpp
@@ -5,12 +5,13 @@
5#include <cstring> 5#include <cstring>
6#include "common/common_types.h" 6#include "common/common_types.h"
7#include "core/core_timing.h" 7#include "core/core_timing.h"
8#include "core/hid/hid_core.h"
8#include "core/hle/service/hid/controllers/xpad.h" 9#include "core/hle/service/hid/controllers/xpad.h"
9 10
10namespace Service::HID { 11namespace Service::HID {
11constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3C00; 12constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3C00;
12 13
13Controller_XPad::Controller_XPad(Core::System& system_) : ControllerBase{system_} {} 14Controller_XPad::Controller_XPad(Core::HID::HIDCore& hid_core_) : ControllerBase{hid_core_} {}
14Controller_XPad::~Controller_XPad() = default; 15Controller_XPad::~Controller_XPad() = default;
15 16
16void Controller_XPad::OnInit() {} 17void Controller_XPad::OnInit() {}
@@ -19,28 +20,19 @@ void Controller_XPad::OnRelease() {}
19 20
20void Controller_XPad::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, 21void Controller_XPad::OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data,
21 std::size_t size) { 22 std::size_t size) {
22 for (auto& xpad_entry : shared_memory.shared_memory_entries) { 23 if (!IsControllerActivated()) {
23 xpad_entry.header.timestamp = core_timing.GetCPUTicks(); 24 basic_xpad_lifo.buffer_count = 0;
24 xpad_entry.header.total_entry_count = 17; 25 basic_xpad_lifo.buffer_tail = 0;
25 26 std::memcpy(data + SHARED_MEMORY_OFFSET, &basic_xpad_lifo, sizeof(basic_xpad_lifo));
26 if (!IsControllerActivated()) { 27 return;
27 xpad_entry.header.entry_count = 0;
28 xpad_entry.header.last_entry_index = 0;
29 return;
30 }
31 xpad_entry.header.entry_count = 16;
32
33 const auto& last_entry = xpad_entry.pad_states[xpad_entry.header.last_entry_index];
34 xpad_entry.header.last_entry_index = (xpad_entry.header.last_entry_index + 1) % 17;
35 auto& cur_entry = xpad_entry.pad_states[xpad_entry.header.last_entry_index];
36
37 cur_entry.sampling_number = last_entry.sampling_number + 1;
38 cur_entry.sampling_number2 = cur_entry.sampling_number;
39 } 28 }
29
30 const auto& last_entry = basic_xpad_lifo.ReadCurrentEntry().state;
31 next_state.sampling_number = last_entry.sampling_number + 1;
40 // TODO(ogniK): Update xpad states 32 // TODO(ogniK): Update xpad states
41 33
42 std::memcpy(data + SHARED_MEMORY_OFFSET, &shared_memory, sizeof(SharedMemory)); 34 basic_xpad_lifo.WriteNextEntry(next_state);
35 std::memcpy(data + SHARED_MEMORY_OFFSET, &basic_xpad_lifo, sizeof(basic_xpad_lifo));
43} 36}
44 37
45void Controller_XPad::OnLoadInputDevices() {}
46} // namespace Service::HID 38} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/xpad.h b/src/core/hle/service/hid/controllers/xpad.h
index f9ab5facf..ba8db8d9d 100644
--- a/src/core/hle/service/hid/controllers/xpad.h
+++ b/src/core/hle/service/hid/controllers/xpad.h
@@ -8,12 +8,14 @@
8#include "common/common_funcs.h" 8#include "common/common_funcs.h"
9#include "common/common_types.h" 9#include "common/common_types.h"
10#include "common/swap.h" 10#include "common/swap.h"
11#include "core/hid/hid_types.h"
11#include "core/hle/service/hid/controllers/controller_base.h" 12#include "core/hle/service/hid/controllers/controller_base.h"
13#include "core/hle/service/hid/ring_lifo.h"
12 14
13namespace Service::HID { 15namespace Service::HID {
14class Controller_XPad final : public ControllerBase { 16class Controller_XPad final : public ControllerBase {
15public: 17public:
16 explicit Controller_XPad(Core::System& system_); 18 explicit Controller_XPad(Core::HID::HIDCore& hid_core_);
17 ~Controller_XPad() override; 19 ~Controller_XPad() override;
18 20
19 // Called when the controller is initialized 21 // Called when the controller is initialized
@@ -25,13 +27,11 @@ public:
25 // When the controller is requesting an update for the shared memory 27 // When the controller is requesting an update for the shared memory
26 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override; 28 void OnUpdate(const Core::Timing::CoreTiming& core_timing, u8* data, std::size_t size) override;
27 29
28 // Called when input devices should be loaded
29 void OnLoadInputDevices() override;
30
31private: 30private:
32 struct Attributes { 31 // This is nn::hid::BasicXpadAttributeSet
32 struct BasicXpadAttributeSet {
33 union { 33 union {
34 u32_le raw{}; 34 u32 raw{};
35 BitField<0, 1, u32> is_connected; 35 BitField<0, 1, u32> is_connected;
36 BitField<1, 1, u32> is_wired; 36 BitField<1, 1, u32> is_wired;
37 BitField<2, 1, u32> is_left_connected; 37 BitField<2, 1, u32> is_left_connected;
@@ -40,11 +40,12 @@ private:
40 BitField<5, 1, u32> is_right_wired; 40 BitField<5, 1, u32> is_right_wired;
41 }; 41 };
42 }; 42 };
43 static_assert(sizeof(Attributes) == 4, "Attributes is an invalid size"); 43 static_assert(sizeof(BasicXpadAttributeSet) == 4, "BasicXpadAttributeSet is an invalid size");
44 44
45 struct Buttons { 45 // This is nn::hid::BasicXpadButtonSet
46 struct BasicXpadButtonSet {
46 union { 47 union {
47 u32_le raw{}; 48 u32 raw{};
48 // Button states 49 // Button states
49 BitField<0, 1, u32> a; 50 BitField<0, 1, u32> a;
50 BitField<1, 1, u32> b; 51 BitField<1, 1, u32> b;
@@ -88,35 +89,21 @@ private:
88 BitField<30, 1, u32> handheld_left_b; 89 BitField<30, 1, u32> handheld_left_b;
89 }; 90 };
90 }; 91 };
91 static_assert(sizeof(Buttons) == 4, "Buttons is an invalid size"); 92 static_assert(sizeof(BasicXpadButtonSet) == 4, "BasicXpadButtonSet is an invalid size");
92 93
93 struct AnalogStick { 94 // This is nn::hid::detail::BasicXpadState
94 s32_le x; 95 struct BasicXpadState {
95 s32_le y; 96 s64 sampling_number;
96 }; 97 BasicXpadAttributeSet attributes;
97 static_assert(sizeof(AnalogStick) == 0x8, "AnalogStick is an invalid size"); 98 BasicXpadButtonSet pad_states;
98 99 Core::HID::AnalogStickState l_stick;
99 struct XPadState { 100 Core::HID::AnalogStickState r_stick;
100 s64_le sampling_number;
101 s64_le sampling_number2;
102 Attributes attributes;
103 Buttons pad_states;
104 AnalogStick l_stick;
105 AnalogStick r_stick;
106 }; 101 };
107 static_assert(sizeof(XPadState) == 0x28, "XPadState is an invalid size"); 102 static_assert(sizeof(BasicXpadState) == 0x20, "BasicXpadState is an invalid size");
108 103
109 struct XPadEntry { 104 // This is nn::hid::detail::BasicXpadLifo
110 CommonHeader header; 105 Lifo<BasicXpadState, hid_entry_count> basic_xpad_lifo{};
111 std::array<XPadState, 17> pad_states{}; 106 static_assert(sizeof(basic_xpad_lifo) == 0x2C8, "basic_xpad_lifo is an invalid size");
112 INSERT_PADDING_BYTES(0x138); 107 BasicXpadState next_state{};
113 };
114 static_assert(sizeof(XPadEntry) == 0x400, "XPadEntry is an invalid size");
115
116 struct SharedMemory {
117 std::array<XPadEntry, 4> shared_memory_entries{};
118 };
119 static_assert(sizeof(SharedMemory) == 0x1000, "SharedMemory is an invalid size");
120 SharedMemory shared_memory{};
121}; 108};
122} // namespace Service::HID 109} // namespace Service::HID
diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp
index 10c64d41a..95fc07325 100644
--- a/src/core/hle/service/hid/hid.cpp
+++ b/src/core/hle/service/hid/hid.cpp
@@ -8,7 +8,7 @@
8#include "common/settings.h" 8#include "common/settings.h"
9#include "core/core.h" 9#include "core/core.h"
10#include "core/core_timing.h" 10#include "core/core_timing.h"
11#include "core/frontend/input.h" 11#include "core/hid/hid_core.h"
12#include "core/hle/ipc_helpers.h" 12#include "core/hle/ipc_helpers.h"
13#include "core/hle/kernel/k_readable_event.h" 13#include "core/hle/kernel/k_readable_event.h"
14#include "core/hle/kernel/k_shared_memory.h" 14#include "core/hle/kernel/k_shared_memory.h"
@@ -34,10 +34,10 @@
34namespace Service::HID { 34namespace Service::HID {
35 35
36// Updating period for each HID device. 36// Updating period for each HID device.
37// HID is polled every 15ms, this value was derived from 37// Period time is obtained by measuring the number of samples in a second on HW using a homebrew
38// https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering#joy-con-status-data-packet 38constexpr auto pad_update_ns = std::chrono::nanoseconds{4 * 1000 * 1000}; // (4ms, 250Hz)
39constexpr auto pad_update_ns = std::chrono::nanoseconds{1000 * 1000}; // (1ms, 1000Hz) 39constexpr auto mouse_keyboard_update_ns = std::chrono::nanoseconds{8 * 1000 * 1000}; // (8ms, 125Hz)
40constexpr auto motion_update_ns = std::chrono::nanoseconds{15 * 1000 * 1000}; // (15ms, 66.666Hz) 40constexpr auto motion_update_ns = std::chrono::nanoseconds{5 * 1000 * 1000}; // (5ms, 200Hz)
41constexpr std::size_t SHARED_MEMORY_SIZE = 0x40000; 41constexpr std::size_t SHARED_MEMORY_SIZE = 0x40000;
42 42
43IAppletResource::IAppletResource(Core::System& system_, 43IAppletResource::IAppletResource(Core::System& system_,
@@ -79,17 +79,24 @@ IAppletResource::IAppletResource(Core::System& system_,
79 const auto guard = LockService(); 79 const auto guard = LockService();
80 UpdateControllers(user_data, ns_late); 80 UpdateControllers(user_data, ns_late);
81 }); 81 });
82 mouse_keyboard_update_event = Core::Timing::CreateEvent(
83 "HID::UpdateMouseKeyboardCallback",
84 [this](std::uintptr_t user_data, std::chrono::nanoseconds ns_late) {
85 const auto guard = LockService();
86 UpdateMouseKeyboard(user_data, ns_late);
87 });
82 motion_update_event = Core::Timing::CreateEvent( 88 motion_update_event = Core::Timing::CreateEvent(
83 "HID::MotionPadCallback", 89 "HID::UpdateMotionCallback",
84 [this](std::uintptr_t user_data, std::chrono::nanoseconds ns_late) { 90 [this](std::uintptr_t user_data, std::chrono::nanoseconds ns_late) {
85 const auto guard = LockService(); 91 const auto guard = LockService();
86 UpdateMotion(user_data, ns_late); 92 UpdateMotion(user_data, ns_late);
87 }); 93 });
88 94
89 system.CoreTiming().ScheduleEvent(pad_update_ns, pad_update_event); 95 system.CoreTiming().ScheduleEvent(pad_update_ns, pad_update_event);
96 system.CoreTiming().ScheduleEvent(mouse_keyboard_update_ns, mouse_keyboard_update_event);
90 system.CoreTiming().ScheduleEvent(motion_update_ns, motion_update_event); 97 system.CoreTiming().ScheduleEvent(motion_update_ns, motion_update_event);
91 98
92 ReloadInputDevices(); 99 system.HIDCore().ReloadInputDevices();
93} 100}
94 101
95void IAppletResource::ActivateController(HidController controller) { 102void IAppletResource::ActivateController(HidController controller) {
@@ -102,6 +109,7 @@ void IAppletResource::DeactivateController(HidController controller) {
102 109
103IAppletResource::~IAppletResource() { 110IAppletResource::~IAppletResource() {
104 system.CoreTiming().UnscheduleEvent(pad_update_event, 0); 111 system.CoreTiming().UnscheduleEvent(pad_update_event, 0);
112 system.CoreTiming().UnscheduleEvent(mouse_keyboard_update_event, 0);
105 system.CoreTiming().UnscheduleEvent(motion_update_event, 0); 113 system.CoreTiming().UnscheduleEvent(motion_update_event, 0);
106} 114}
107 115
@@ -117,23 +125,44 @@ void IAppletResource::UpdateControllers(std::uintptr_t user_data,
117 std::chrono::nanoseconds ns_late) { 125 std::chrono::nanoseconds ns_late) {
118 auto& core_timing = system.CoreTiming(); 126 auto& core_timing = system.CoreTiming();
119 127
120 const bool should_reload = Settings::values.is_device_reload_pending.exchange(false);
121 for (const auto& controller : controllers) { 128 for (const auto& controller : controllers) {
122 if (should_reload) { 129 // Keyboard has it's own update event
123 controller->OnLoadInputDevices(); 130 if (controller == controllers[static_cast<size_t>(HidController::Keyboard)]) {
131 continue;
132 }
133 // Mouse has it's own update event
134 if (controller == controllers[static_cast<size_t>(HidController::Mouse)]) {
135 continue;
124 } 136 }
125 controller->OnUpdate(core_timing, system.Kernel().GetHidSharedMem().GetPointer(), 137 controller->OnUpdate(core_timing, system.Kernel().GetHidSharedMem().GetPointer(),
126 SHARED_MEMORY_SIZE); 138 SHARED_MEMORY_SIZE);
127 } 139 }
128 140
129 // If ns_late is higher than the update rate ignore the delay 141 // If ns_late is higher than the update rate ignore the delay
130 if (ns_late > motion_update_ns) { 142 if (ns_late > pad_update_ns) {
131 ns_late = {}; 143 ns_late = {};
132 } 144 }
133 145
134 core_timing.ScheduleEvent(pad_update_ns - ns_late, pad_update_event); 146 core_timing.ScheduleEvent(pad_update_ns - ns_late, pad_update_event);
135} 147}
136 148
149void IAppletResource::UpdateMouseKeyboard(std::uintptr_t user_data,
150 std::chrono::nanoseconds ns_late) {
151 auto& core_timing = system.CoreTiming();
152
153 controllers[static_cast<size_t>(HidController::Mouse)]->OnUpdate(
154 core_timing, system.Kernel().GetHidSharedMem().GetPointer(), SHARED_MEMORY_SIZE);
155 controllers[static_cast<size_t>(HidController::Keyboard)]->OnUpdate(
156 core_timing, system.Kernel().GetHidSharedMem().GetPointer(), SHARED_MEMORY_SIZE);
157
158 // If ns_late is higher than the update rate ignore the delay
159 if (ns_late > mouse_keyboard_update_ns) {
160 ns_late = {};
161 }
162
163 core_timing.ScheduleEvent(mouse_keyboard_update_ns - ns_late, mouse_keyboard_update_event);
164}
165
137void IAppletResource::UpdateMotion(std::uintptr_t user_data, std::chrono::nanoseconds ns_late) { 166void IAppletResource::UpdateMotion(std::uintptr_t user_data, std::chrono::nanoseconds ns_late) {
138 auto& core_timing = system.CoreTiming(); 167 auto& core_timing = system.CoreTiming();
139 168
@@ -166,7 +195,7 @@ public:
166private: 195private:
167 void InitializeVibrationDevice(Kernel::HLERequestContext& ctx) { 196 void InitializeVibrationDevice(Kernel::HLERequestContext& ctx) {
168 IPC::RequestParser rp{ctx}; 197 IPC::RequestParser rp{ctx};
169 const auto vibration_device_handle{rp.PopRaw<Controller_NPad::DeviceHandle>()}; 198 const auto vibration_device_handle{rp.PopRaw<Core::HID::VibrationDeviceHandle>()};
170 199
171 if (applet_resource != nullptr) { 200 if (applet_resource != nullptr) {
172 applet_resource->GetController<Controller_NPad>(HidController::NPad) 201 applet_resource->GetController<Controller_NPad>(HidController::NPad)
@@ -422,6 +451,7 @@ void Hid::ActivateXpad(Kernel::HLERequestContext& ctx) {
422 INSERT_PADDING_WORDS_NOINIT(1); 451 INSERT_PADDING_WORDS_NOINIT(1);
423 u64 applet_resource_user_id; 452 u64 applet_resource_user_id;
424 }; 453 };
454 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
425 455
426 const auto parameters{rp.PopRaw<Parameters>()}; 456 const auto parameters{rp.PopRaw<Parameters>()};
427 457
@@ -448,19 +478,18 @@ void Hid::GetXpadIDs(Kernel::HLERequestContext& ctx) {
448void Hid::ActivateSixAxisSensor(Kernel::HLERequestContext& ctx) { 478void Hid::ActivateSixAxisSensor(Kernel::HLERequestContext& ctx) {
449 IPC::RequestParser rp{ctx}; 479 IPC::RequestParser rp{ctx};
450 struct Parameters { 480 struct Parameters {
451 Controller_NPad::DeviceHandle sixaxis_handle; 481 u32 basic_xpad_id;
452 INSERT_PADDING_WORDS_NOINIT(1); 482 INSERT_PADDING_WORDS_NOINIT(1);
453 u64 applet_resource_user_id; 483 u64 applet_resource_user_id;
454 }; 484 };
485 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
455 486
456 const auto parameters{rp.PopRaw<Parameters>()}; 487 const auto parameters{rp.PopRaw<Parameters>()};
457 488
458 applet_resource->GetController<Controller_NPad>(HidController::NPad).SetSixAxisEnabled(true); 489 // This function does nothing on 10.0.0+
459 490
460 LOG_DEBUG(Service_HID, 491 LOG_WARNING(Service_HID, "(STUBBED) called, basic_xpad_id={}, applet_resource_user_id={}",
461 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 492 parameters.basic_xpad_id, parameters.applet_resource_user_id);
462 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id,
463 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
464 493
465 IPC::ResponseBuilder rb{ctx, 2}; 494 IPC::ResponseBuilder rb{ctx, 2};
466 rb.Push(ResultSuccess); 495 rb.Push(ResultSuccess);
@@ -469,19 +498,18 @@ void Hid::ActivateSixAxisSensor(Kernel::HLERequestContext& ctx) {
469void Hid::DeactivateSixAxisSensor(Kernel::HLERequestContext& ctx) { 498void Hid::DeactivateSixAxisSensor(Kernel::HLERequestContext& ctx) {
470 IPC::RequestParser rp{ctx}; 499 IPC::RequestParser rp{ctx};
471 struct Parameters { 500 struct Parameters {
472 Controller_NPad::DeviceHandle sixaxis_handle; 501 u32 basic_xpad_id;
473 INSERT_PADDING_WORDS_NOINIT(1); 502 INSERT_PADDING_WORDS_NOINIT(1);
474 u64 applet_resource_user_id; 503 u64 applet_resource_user_id;
475 }; 504 };
505 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
476 506
477 const auto parameters{rp.PopRaw<Parameters>()}; 507 const auto parameters{rp.PopRaw<Parameters>()};
478 508
479 applet_resource->GetController<Controller_NPad>(HidController::NPad).SetSixAxisEnabled(false); 509 // This function does nothing on 10.0.0+
480 510
481 LOG_DEBUG(Service_HID, 511 LOG_WARNING(Service_HID, "(STUBBED) called, basic_xpad_id={}, applet_resource_user_id={}",
482 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 512 parameters.basic_xpad_id, parameters.applet_resource_user_id);
483 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id,
484 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
485 513
486 IPC::ResponseBuilder rb{ctx, 2}; 514 IPC::ResponseBuilder rb{ctx, 2};
487 rb.Push(ResultSuccess); 515 rb.Push(ResultSuccess);
@@ -490,14 +518,16 @@ void Hid::DeactivateSixAxisSensor(Kernel::HLERequestContext& ctx) {
490void Hid::StartSixAxisSensor(Kernel::HLERequestContext& ctx) { 518void Hid::StartSixAxisSensor(Kernel::HLERequestContext& ctx) {
491 IPC::RequestParser rp{ctx}; 519 IPC::RequestParser rp{ctx};
492 struct Parameters { 520 struct Parameters {
493 Controller_NPad::DeviceHandle sixaxis_handle; 521 Core::HID::SixAxisSensorHandle sixaxis_handle;
494 INSERT_PADDING_WORDS_NOINIT(1); 522 INSERT_PADDING_WORDS_NOINIT(1);
495 u64 applet_resource_user_id; 523 u64 applet_resource_user_id;
496 }; 524 };
525 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
497 526
498 const auto parameters{rp.PopRaw<Parameters>()}; 527 const auto parameters{rp.PopRaw<Parameters>()};
499 528
500 applet_resource->GetController<Controller_NPad>(HidController::NPad).SetSixAxisEnabled(true); 529 applet_resource->GetController<Controller_NPad>(HidController::NPad)
530 .SetSixAxisEnabled(parameters.sixaxis_handle, true);
501 531
502 LOG_DEBUG(Service_HID, 532 LOG_DEBUG(Service_HID,
503 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 533 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}",
@@ -511,14 +541,16 @@ void Hid::StartSixAxisSensor(Kernel::HLERequestContext& ctx) {
511void Hid::StopSixAxisSensor(Kernel::HLERequestContext& ctx) { 541void Hid::StopSixAxisSensor(Kernel::HLERequestContext& ctx) {
512 IPC::RequestParser rp{ctx}; 542 IPC::RequestParser rp{ctx};
513 struct Parameters { 543 struct Parameters {
514 Controller_NPad::DeviceHandle sixaxis_handle; 544 Core::HID::SixAxisSensorHandle sixaxis_handle;
515 INSERT_PADDING_WORDS_NOINIT(1); 545 INSERT_PADDING_WORDS_NOINIT(1);
516 u64 applet_resource_user_id; 546 u64 applet_resource_user_id;
517 }; 547 };
548 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
518 549
519 const auto parameters{rp.PopRaw<Parameters>()}; 550 const auto parameters{rp.PopRaw<Parameters>()};
520 551
521 applet_resource->GetController<Controller_NPad>(HidController::NPad).SetSixAxisEnabled(false); 552 applet_resource->GetController<Controller_NPad>(HidController::NPad)
553 .SetSixAxisEnabled(parameters.sixaxis_handle, false);
522 554
523 LOG_DEBUG(Service_HID, 555 LOG_DEBUG(Service_HID,
524 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 556 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}",
@@ -534,19 +566,23 @@ void Hid::EnableSixAxisSensorFusion(Kernel::HLERequestContext& ctx) {
534 struct Parameters { 566 struct Parameters {
535 bool enable_sixaxis_sensor_fusion; 567 bool enable_sixaxis_sensor_fusion;
536 INSERT_PADDING_BYTES_NOINIT(3); 568 INSERT_PADDING_BYTES_NOINIT(3);
537 Controller_NPad::DeviceHandle sixaxis_handle; 569 Core::HID::SixAxisSensorHandle sixaxis_handle;
538 u64 applet_resource_user_id; 570 u64 applet_resource_user_id;
539 }; 571 };
540 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size."); 572 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
541 573
542 const auto parameters{rp.PopRaw<Parameters>()}; 574 const auto parameters{rp.PopRaw<Parameters>()};
543 575
544 LOG_WARNING(Service_HID, 576 applet_resource->GetController<Controller_NPad>(HidController::NPad)
545 "(STUBBED) called, enable_sixaxis_sensor_fusion={}, npad_type={}, npad_id={}, " 577 .SetSixAxisFusionEnabled(parameters.sixaxis_handle,
546 "device_index={}, applet_resource_user_id={}", 578 parameters.enable_sixaxis_sensor_fusion);
547 parameters.enable_sixaxis_sensor_fusion, parameters.sixaxis_handle.npad_type, 579
548 parameters.sixaxis_handle.npad_id, parameters.sixaxis_handle.device_index, 580 LOG_DEBUG(Service_HID,
549 parameters.applet_resource_user_id); 581 "called, enable_sixaxis_sensor_fusion={}, npad_type={}, npad_id={}, "
582 "device_index={}, applet_resource_user_id={}",
583 parameters.enable_sixaxis_sensor_fusion, parameters.sixaxis_handle.npad_type,
584 parameters.sixaxis_handle.npad_id, parameters.sixaxis_handle.device_index,
585 parameters.applet_resource_user_id);
550 586
551 IPC::ResponseBuilder rb{ctx, 2}; 587 IPC::ResponseBuilder rb{ctx, 2};
552 rb.Push(ResultSuccess); 588 rb.Push(ResultSuccess);
@@ -555,9 +591,9 @@ void Hid::EnableSixAxisSensorFusion(Kernel::HLERequestContext& ctx) {
555void Hid::SetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) { 591void Hid::SetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) {
556 IPC::RequestParser rp{ctx}; 592 IPC::RequestParser rp{ctx};
557 struct Parameters { 593 struct Parameters {
558 Controller_NPad::DeviceHandle sixaxis_handle; 594 Core::HID::SixAxisSensorHandle sixaxis_handle;
559 f32 parameter1; 595 Core::HID::SixAxisSensorFusionParameters sixaxis_fusion;
560 f32 parameter2; 596 INSERT_PADDING_WORDS_NOINIT(1);
561 u64 applet_resource_user_id; 597 u64 applet_resource_user_id;
562 }; 598 };
563 static_assert(sizeof(Parameters) == 0x18, "Parameters has incorrect size."); 599 static_assert(sizeof(Parameters) == 0x18, "Parameters has incorrect size.");
@@ -565,14 +601,14 @@ void Hid::SetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) {
565 const auto parameters{rp.PopRaw<Parameters>()}; 601 const auto parameters{rp.PopRaw<Parameters>()};
566 602
567 applet_resource->GetController<Controller_NPad>(HidController::NPad) 603 applet_resource->GetController<Controller_NPad>(HidController::NPad)
568 .SetSixAxisFusionParameters(parameters.parameter1, parameters.parameter2); 604 .SetSixAxisFusionParameters(parameters.sixaxis_handle, parameters.sixaxis_fusion);
569 605
570 LOG_WARNING(Service_HID, 606 LOG_DEBUG(Service_HID,
571 "(STUBBED) called, npad_type={}, npad_id={}, device_index={}, parameter1={}, " 607 "called, npad_type={}, npad_id={}, device_index={}, parameter1={}, "
572 "parameter2={}, applet_resource_user_id={}", 608 "parameter2={}, applet_resource_user_id={}",
573 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id, 609 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id,
574 parameters.sixaxis_handle.device_index, parameters.parameter1, 610 parameters.sixaxis_handle.device_index, parameters.sixaxis_fusion.parameter1,
575 parameters.parameter2, parameters.applet_resource_user_id); 611 parameters.sixaxis_fusion.parameter2, parameters.applet_resource_user_id);
576 612
577 IPC::ResponseBuilder rb{ctx, 2}; 613 IPC::ResponseBuilder rb{ctx, 2};
578 rb.Push(ResultSuccess); 614 rb.Push(ResultSuccess);
@@ -581,35 +617,33 @@ void Hid::SetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) {
581void Hid::GetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) { 617void Hid::GetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) {
582 IPC::RequestParser rp{ctx}; 618 IPC::RequestParser rp{ctx};
583 struct Parameters { 619 struct Parameters {
584 Controller_NPad::DeviceHandle sixaxis_handle; 620 Core::HID::SixAxisSensorHandle sixaxis_handle;
621 INSERT_PADDING_WORDS_NOINIT(1);
585 u64 applet_resource_user_id; 622 u64 applet_resource_user_id;
586 }; 623 };
587 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size."); 624 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
588 625
589 f32 parameter1 = 0;
590 f32 parameter2 = 0;
591 const auto parameters{rp.PopRaw<Parameters>()}; 626 const auto parameters{rp.PopRaw<Parameters>()};
592 627
593 std::tie(parameter1, parameter2) = 628 const auto sixaxis_fusion_parameters =
594 applet_resource->GetController<Controller_NPad>(HidController::NPad) 629 applet_resource->GetController<Controller_NPad>(HidController::NPad)
595 .GetSixAxisFusionParameters(); 630 .GetSixAxisFusionParameters(parameters.sixaxis_handle);
596 631
597 LOG_WARNING( 632 LOG_DEBUG(Service_HID,
598 Service_HID, 633 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}",
599 "(STUBBED) called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 634 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id,
600 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id, 635 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
601 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
602 636
603 IPC::ResponseBuilder rb{ctx, 4}; 637 IPC::ResponseBuilder rb{ctx, 4};
604 rb.Push(ResultSuccess); 638 rb.Push(ResultSuccess);
605 rb.Push(parameter1); 639 rb.PushRaw(sixaxis_fusion_parameters);
606 rb.Push(parameter2);
607} 640}
608 641
609void Hid::ResetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) { 642void Hid::ResetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) {
610 IPC::RequestParser rp{ctx}; 643 IPC::RequestParser rp{ctx};
611 struct Parameters { 644 struct Parameters {
612 Controller_NPad::DeviceHandle sixaxis_handle; 645 Core::HID::SixAxisSensorHandle sixaxis_handle;
646 INSERT_PADDING_WORDS_NOINIT(1);
613 u64 applet_resource_user_id; 647 u64 applet_resource_user_id;
614 }; 648 };
615 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size."); 649 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
@@ -617,13 +651,12 @@ void Hid::ResetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) {
617 const auto parameters{rp.PopRaw<Parameters>()}; 651 const auto parameters{rp.PopRaw<Parameters>()};
618 652
619 applet_resource->GetController<Controller_NPad>(HidController::NPad) 653 applet_resource->GetController<Controller_NPad>(HidController::NPad)
620 .ResetSixAxisFusionParameters(); 654 .ResetSixAxisFusionParameters(parameters.sixaxis_handle);
621 655
622 LOG_WARNING( 656 LOG_DEBUG(Service_HID,
623 Service_HID, 657 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}",
624 "(STUBBED) called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 658 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id,
625 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id, 659 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
626 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
627 660
628 IPC::ResponseBuilder rb{ctx, 2}; 661 IPC::ResponseBuilder rb{ctx, 2};
629 rb.Push(ResultSuccess); 662 rb.Push(ResultSuccess);
@@ -631,12 +664,12 @@ void Hid::ResetSixAxisSensorFusionParameters(Kernel::HLERequestContext& ctx) {
631 664
632void Hid::SetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) { 665void Hid::SetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) {
633 IPC::RequestParser rp{ctx}; 666 IPC::RequestParser rp{ctx};
634 const auto sixaxis_handle{rp.PopRaw<Controller_NPad::DeviceHandle>()}; 667 const auto sixaxis_handle{rp.PopRaw<Core::HID::SixAxisSensorHandle>()};
635 const auto drift_mode{rp.PopEnum<Controller_NPad::GyroscopeZeroDriftMode>()}; 668 const auto drift_mode{rp.PopEnum<Controller_NPad::GyroscopeZeroDriftMode>()};
636 const auto applet_resource_user_id{rp.Pop<u64>()}; 669 const auto applet_resource_user_id{rp.Pop<u64>()};
637 670
638 applet_resource->GetController<Controller_NPad>(HidController::NPad) 671 applet_resource->GetController<Controller_NPad>(HidController::NPad)
639 .SetGyroscopeZeroDriftMode(drift_mode); 672 .SetGyroscopeZeroDriftMode(sixaxis_handle, drift_mode);
640 673
641 LOG_DEBUG(Service_HID, 674 LOG_DEBUG(Service_HID,
642 "called, npad_type={}, npad_id={}, device_index={}, drift_mode={}, " 675 "called, npad_type={}, npad_id={}, device_index={}, drift_mode={}, "
@@ -651,10 +684,11 @@ void Hid::SetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) {
651void Hid::GetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) { 684void Hid::GetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) {
652 IPC::RequestParser rp{ctx}; 685 IPC::RequestParser rp{ctx};
653 struct Parameters { 686 struct Parameters {
654 Controller_NPad::DeviceHandle sixaxis_handle; 687 Core::HID::SixAxisSensorHandle sixaxis_handle;
655 INSERT_PADDING_WORDS_NOINIT(1); 688 INSERT_PADDING_WORDS_NOINIT(1);
656 u64 applet_resource_user_id; 689 u64 applet_resource_user_id;
657 }; 690 };
691 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
658 692
659 const auto parameters{rp.PopRaw<Parameters>()}; 693 const auto parameters{rp.PopRaw<Parameters>()};
660 694
@@ -666,21 +700,23 @@ void Hid::GetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) {
666 IPC::ResponseBuilder rb{ctx, 3}; 700 IPC::ResponseBuilder rb{ctx, 3};
667 rb.Push(ResultSuccess); 701 rb.Push(ResultSuccess);
668 rb.PushEnum(applet_resource->GetController<Controller_NPad>(HidController::NPad) 702 rb.PushEnum(applet_resource->GetController<Controller_NPad>(HidController::NPad)
669 .GetGyroscopeZeroDriftMode()); 703 .GetGyroscopeZeroDriftMode(parameters.sixaxis_handle));
670} 704}
671 705
672void Hid::ResetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) { 706void Hid::ResetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) {
673 IPC::RequestParser rp{ctx}; 707 IPC::RequestParser rp{ctx};
674 struct Parameters { 708 struct Parameters {
675 Controller_NPad::DeviceHandle sixaxis_handle; 709 Core::HID::SixAxisSensorHandle sixaxis_handle;
676 INSERT_PADDING_WORDS_NOINIT(1); 710 INSERT_PADDING_WORDS_NOINIT(1);
677 u64 applet_resource_user_id; 711 u64 applet_resource_user_id;
678 }; 712 };
713 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
679 714
680 const auto parameters{rp.PopRaw<Parameters>()}; 715 const auto parameters{rp.PopRaw<Parameters>()};
716 const auto drift_mode{Controller_NPad::GyroscopeZeroDriftMode::Standard};
681 717
682 applet_resource->GetController<Controller_NPad>(HidController::NPad) 718 applet_resource->GetController<Controller_NPad>(HidController::NPad)
683 .SetGyroscopeZeroDriftMode(Controller_NPad::GyroscopeZeroDriftMode::Standard); 719 .SetGyroscopeZeroDriftMode(parameters.sixaxis_handle, drift_mode);
684 720
685 LOG_DEBUG(Service_HID, 721 LOG_DEBUG(Service_HID,
686 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 722 "called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}",
@@ -694,10 +730,11 @@ void Hid::ResetGyroscopeZeroDriftMode(Kernel::HLERequestContext& ctx) {
694void Hid::IsSixAxisSensorAtRest(Kernel::HLERequestContext& ctx) { 730void Hid::IsSixAxisSensorAtRest(Kernel::HLERequestContext& ctx) {
695 IPC::RequestParser rp{ctx}; 731 IPC::RequestParser rp{ctx};
696 struct Parameters { 732 struct Parameters {
697 Controller_NPad::DeviceHandle sixaxis_handle; 733 Core::HID::SixAxisSensorHandle sixaxis_handle;
698 INSERT_PADDING_WORDS_NOINIT(1); 734 INSERT_PADDING_WORDS_NOINIT(1);
699 u64 applet_resource_user_id; 735 u64 applet_resource_user_id;
700 }; 736 };
737 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
701 738
702 const auto parameters{rp.PopRaw<Parameters>()}; 739 const auto parameters{rp.PopRaw<Parameters>()};
703 740
@@ -709,16 +746,17 @@ void Hid::IsSixAxisSensorAtRest(Kernel::HLERequestContext& ctx) {
709 IPC::ResponseBuilder rb{ctx, 3}; 746 IPC::ResponseBuilder rb{ctx, 3};
710 rb.Push(ResultSuccess); 747 rb.Push(ResultSuccess);
711 rb.Push(applet_resource->GetController<Controller_NPad>(HidController::NPad) 748 rb.Push(applet_resource->GetController<Controller_NPad>(HidController::NPad)
712 .IsSixAxisSensorAtRest()); 749 .IsSixAxisSensorAtRest(parameters.sixaxis_handle));
713} 750}
714 751
715void Hid::IsFirmwareUpdateAvailableForSixAxisSensor(Kernel::HLERequestContext& ctx) { 752void Hid::IsFirmwareUpdateAvailableForSixAxisSensor(Kernel::HLERequestContext& ctx) {
716 IPC::RequestParser rp{ctx}; 753 IPC::RequestParser rp{ctx};
717 struct Parameters { 754 struct Parameters {
718 Controller_NPad::DeviceHandle sixaxis_handle; 755 Core::HID::SixAxisSensorHandle sixaxis_handle;
719 INSERT_PADDING_WORDS_NOINIT(1); 756 INSERT_PADDING_WORDS_NOINIT(1);
720 u64 applet_resource_user_id; 757 u64 applet_resource_user_id;
721 }; 758 };
759 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
722 760
723 const auto parameters{rp.PopRaw<Parameters>()}; 761 const auto parameters{rp.PopRaw<Parameters>()};
724 762
@@ -740,13 +778,14 @@ void Hid::ActivateGesture(Kernel::HLERequestContext& ctx) {
740 INSERT_PADDING_WORDS_NOINIT(1); 778 INSERT_PADDING_WORDS_NOINIT(1);
741 u64 applet_resource_user_id; 779 u64 applet_resource_user_id;
742 }; 780 };
781 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
743 782
744 const auto parameters{rp.PopRaw<Parameters>()}; 783 const auto parameters{rp.PopRaw<Parameters>()};
745 784
746 applet_resource->ActivateController(HidController::Gesture); 785 applet_resource->ActivateController(HidController::Gesture);
747 786
748 LOG_DEBUG(Service_HID, "called, unknown={}, applet_resource_user_id={}", parameters.unknown, 787 LOG_WARNING(Service_HID, "(STUBBED) called, unknown={}, applet_resource_user_id={}",
749 parameters.applet_resource_user_id); 788 parameters.unknown, parameters.applet_resource_user_id);
750 789
751 IPC::ResponseBuilder rb{ctx, 2}; 790 IPC::ResponseBuilder rb{ctx, 2};
752 rb.Push(ResultSuccess); 791 rb.Push(ResultSuccess);
@@ -754,12 +793,20 @@ void Hid::ActivateGesture(Kernel::HLERequestContext& ctx) {
754 793
755void Hid::SetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx) { 794void Hid::SetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx) {
756 IPC::RequestParser rp{ctx}; 795 IPC::RequestParser rp{ctx};
757 const auto supported_styleset{rp.Pop<u32>()}; 796 struct Parameters {
797 Core::HID::NpadStyleSet supported_styleset;
798 INSERT_PADDING_WORDS_NOINIT(1);
799 u64 applet_resource_user_id;
800 };
801 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
802
803 const auto parameters{rp.PopRaw<Parameters>()};
758 804
759 applet_resource->GetController<Controller_NPad>(HidController::NPad) 805 applet_resource->GetController<Controller_NPad>(HidController::NPad)
760 .SetSupportedStyleSet({supported_styleset}); 806 .SetSupportedStyleSet({parameters.supported_styleset});
761 807
762 LOG_DEBUG(Service_HID, "called, supported_styleset={}", supported_styleset); 808 LOG_DEBUG(Service_HID, "called, supported_styleset={}, applet_resource_user_id={}",
809 parameters.supported_styleset, parameters.applet_resource_user_id);
763 810
764 IPC::ResponseBuilder rb{ctx, 2}; 811 IPC::ResponseBuilder rb{ctx, 2};
765 rb.Push(ResultSuccess); 812 rb.Push(ResultSuccess);
@@ -773,9 +820,9 @@ void Hid::GetSupportedNpadStyleSet(Kernel::HLERequestContext& ctx) {
773 820
774 IPC::ResponseBuilder rb{ctx, 3}; 821 IPC::ResponseBuilder rb{ctx, 3};
775 rb.Push(ResultSuccess); 822 rb.Push(ResultSuccess);
776 rb.Push(applet_resource->GetController<Controller_NPad>(HidController::NPad) 823 rb.PushEnum(applet_resource->GetController<Controller_NPad>(HidController::NPad)
777 .GetSupportedStyleSet() 824 .GetSupportedStyleSet()
778 .raw); 825 .raw);
779} 826}
780 827
781void Hid::SetSupportedNpadIdType(Kernel::HLERequestContext& ctx) { 828void Hid::SetSupportedNpadIdType(Kernel::HLERequestContext& ctx) {
@@ -818,11 +865,12 @@ void Hid::DeactivateNpad(Kernel::HLERequestContext& ctx) {
818void Hid::AcquireNpadStyleSetUpdateEventHandle(Kernel::HLERequestContext& ctx) { 865void Hid::AcquireNpadStyleSetUpdateEventHandle(Kernel::HLERequestContext& ctx) {
819 IPC::RequestParser rp{ctx}; 866 IPC::RequestParser rp{ctx};
820 struct Parameters { 867 struct Parameters {
821 u32 npad_id; 868 Core::HID::NpadIdType npad_id;
822 INSERT_PADDING_WORDS_NOINIT(1); 869 INSERT_PADDING_WORDS_NOINIT(1);
823 u64 applet_resource_user_id; 870 u64 applet_resource_user_id;
824 u64 unknown; 871 u64 unknown;
825 }; 872 };
873 static_assert(sizeof(Parameters) == 0x18, "Parameters has incorrect size.");
826 874
827 const auto parameters{rp.PopRaw<Parameters>()}; 875 const auto parameters{rp.PopRaw<Parameters>()};
828 876
@@ -838,10 +886,11 @@ void Hid::AcquireNpadStyleSetUpdateEventHandle(Kernel::HLERequestContext& ctx) {
838void Hid::DisconnectNpad(Kernel::HLERequestContext& ctx) { 886void Hid::DisconnectNpad(Kernel::HLERequestContext& ctx) {
839 IPC::RequestParser rp{ctx}; 887 IPC::RequestParser rp{ctx};
840 struct Parameters { 888 struct Parameters {
841 u32 npad_id; 889 Core::HID::NpadIdType npad_id;
842 INSERT_PADDING_WORDS_NOINIT(1); 890 INSERT_PADDING_WORDS_NOINIT(1);
843 u64 applet_resource_user_id; 891 u64 applet_resource_user_id;
844 }; 892 };
893 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
845 894
846 const auto parameters{rp.PopRaw<Parameters>()}; 895 const auto parameters{rp.PopRaw<Parameters>()};
847 896
@@ -857,7 +906,7 @@ void Hid::DisconnectNpad(Kernel::HLERequestContext& ctx) {
857 906
858void Hid::GetPlayerLedPattern(Kernel::HLERequestContext& ctx) { 907void Hid::GetPlayerLedPattern(Kernel::HLERequestContext& ctx) {
859 IPC::RequestParser rp{ctx}; 908 IPC::RequestParser rp{ctx};
860 const auto npad_id{rp.Pop<u32>()}; 909 const auto npad_id{rp.PopEnum<Core::HID::NpadIdType>()};
861 910
862 LOG_DEBUG(Service_HID, "called, npad_id={}", npad_id); 911 LOG_DEBUG(Service_HID, "called, npad_id={}", npad_id);
863 912
@@ -872,16 +921,17 @@ void Hid::ActivateNpadWithRevision(Kernel::HLERequestContext& ctx) {
872 // Should have no effect with how our npad sets up the data 921 // Should have no effect with how our npad sets up the data
873 IPC::RequestParser rp{ctx}; 922 IPC::RequestParser rp{ctx};
874 struct Parameters { 923 struct Parameters {
875 u32 unknown; 924 s32 revision;
876 INSERT_PADDING_WORDS_NOINIT(1); 925 INSERT_PADDING_WORDS_NOINIT(1);
877 u64 applet_resource_user_id; 926 u64 applet_resource_user_id;
878 }; 927 };
928 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
879 929
880 const auto parameters{rp.PopRaw<Parameters>()}; 930 const auto parameters{rp.PopRaw<Parameters>()};
881 931
882 applet_resource->ActivateController(HidController::NPad); 932 applet_resource->ActivateController(HidController::NPad);
883 933
884 LOG_DEBUG(Service_HID, "called, unknown={}, applet_resource_user_id={}", parameters.unknown, 934 LOG_DEBUG(Service_HID, "called, revision={}, applet_resource_user_id={}", parameters.revision,
885 parameters.applet_resource_user_id); 935 parameters.applet_resource_user_id);
886 936
887 IPC::ResponseBuilder rb{ctx, 2}; 937 IPC::ResponseBuilder rb{ctx, 2};
@@ -891,7 +941,7 @@ void Hid::ActivateNpadWithRevision(Kernel::HLERequestContext& ctx) {
891void Hid::SetNpadJoyHoldType(Kernel::HLERequestContext& ctx) { 941void Hid::SetNpadJoyHoldType(Kernel::HLERequestContext& ctx) {
892 IPC::RequestParser rp{ctx}; 942 IPC::RequestParser rp{ctx};
893 const auto applet_resource_user_id{rp.Pop<u64>()}; 943 const auto applet_resource_user_id{rp.Pop<u64>()};
894 const auto hold_type{rp.PopEnum<Controller_NPad::NpadHoldType>()}; 944 const auto hold_type{rp.PopEnum<Controller_NPad::NpadJoyHoldType>()};
895 945
896 applet_resource->GetController<Controller_NPad>(HidController::NPad).SetHoldType(hold_type); 946 applet_resource->GetController<Controller_NPad>(HidController::NPad).SetHoldType(hold_type);
897 947
@@ -916,15 +966,16 @@ void Hid::GetNpadJoyHoldType(Kernel::HLERequestContext& ctx) {
916void Hid::SetNpadJoyAssignmentModeSingleByDefault(Kernel::HLERequestContext& ctx) { 966void Hid::SetNpadJoyAssignmentModeSingleByDefault(Kernel::HLERequestContext& ctx) {
917 IPC::RequestParser rp{ctx}; 967 IPC::RequestParser rp{ctx};
918 struct Parameters { 968 struct Parameters {
919 u32 npad_id; 969 Core::HID::NpadIdType npad_id;
920 INSERT_PADDING_WORDS_NOINIT(1); 970 INSERT_PADDING_WORDS_NOINIT(1);
921 u64 applet_resource_user_id; 971 u64 applet_resource_user_id;
922 }; 972 };
973 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
923 974
924 const auto parameters{rp.PopRaw<Parameters>()}; 975 const auto parameters{rp.PopRaw<Parameters>()};
925 976
926 applet_resource->GetController<Controller_NPad>(HidController::NPad) 977 applet_resource->GetController<Controller_NPad>(HidController::NPad)
927 .SetNpadMode(parameters.npad_id, Controller_NPad::NpadAssignments::Single); 978 .SetNpadMode(parameters.npad_id, Controller_NPad::NpadJoyAssignmentMode::Single);
928 979
929 LOG_WARNING(Service_HID, "(STUBBED) called, npad_id={}, applet_resource_user_id={}", 980 LOG_WARNING(Service_HID, "(STUBBED) called, npad_id={}, applet_resource_user_id={}",
930 parameters.npad_id, parameters.applet_resource_user_id); 981 parameters.npad_id, parameters.applet_resource_user_id);
@@ -937,16 +988,17 @@ void Hid::SetNpadJoyAssignmentModeSingle(Kernel::HLERequestContext& ctx) {
937 // TODO: Check the differences between this and SetNpadJoyAssignmentModeSingleByDefault 988 // TODO: Check the differences between this and SetNpadJoyAssignmentModeSingleByDefault
938 IPC::RequestParser rp{ctx}; 989 IPC::RequestParser rp{ctx};
939 struct Parameters { 990 struct Parameters {
940 u32 npad_id; 991 Core::HID::NpadIdType npad_id;
941 INSERT_PADDING_WORDS_NOINIT(1); 992 INSERT_PADDING_WORDS_NOINIT(1);
942 u64 applet_resource_user_id; 993 u64 applet_resource_user_id;
943 u64 npad_joy_device_type; 994 u64 npad_joy_device_type;
944 }; 995 };
996 static_assert(sizeof(Parameters) == 0x18, "Parameters has incorrect size.");
945 997
946 const auto parameters{rp.PopRaw<Parameters>()}; 998 const auto parameters{rp.PopRaw<Parameters>()};
947 999
948 applet_resource->GetController<Controller_NPad>(HidController::NPad) 1000 applet_resource->GetController<Controller_NPad>(HidController::NPad)
949 .SetNpadMode(parameters.npad_id, Controller_NPad::NpadAssignments::Single); 1001 .SetNpadMode(parameters.npad_id, Controller_NPad::NpadJoyAssignmentMode::Single);
950 1002
951 LOG_WARNING(Service_HID, 1003 LOG_WARNING(Service_HID,
952 "(STUBBED) called, npad_id={}, applet_resource_user_id={}, npad_joy_device_type={}", 1004 "(STUBBED) called, npad_id={}, applet_resource_user_id={}, npad_joy_device_type={}",
@@ -960,15 +1012,16 @@ void Hid::SetNpadJoyAssignmentModeSingle(Kernel::HLERequestContext& ctx) {
960void Hid::SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx) { 1012void Hid::SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx) {
961 IPC::RequestParser rp{ctx}; 1013 IPC::RequestParser rp{ctx};
962 struct Parameters { 1014 struct Parameters {
963 u32 npad_id; 1015 Core::HID::NpadIdType npad_id;
964 INSERT_PADDING_WORDS_NOINIT(1); 1016 INSERT_PADDING_WORDS_NOINIT(1);
965 u64 applet_resource_user_id; 1017 u64 applet_resource_user_id;
966 }; 1018 };
1019 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
967 1020
968 const auto parameters{rp.PopRaw<Parameters>()}; 1021 const auto parameters{rp.PopRaw<Parameters>()};
969 1022
970 applet_resource->GetController<Controller_NPad>(HidController::NPad) 1023 applet_resource->GetController<Controller_NPad>(HidController::NPad)
971 .SetNpadMode(parameters.npad_id, Controller_NPad::NpadAssignments::Dual); 1024 .SetNpadMode(parameters.npad_id, Controller_NPad::NpadJoyAssignmentMode::Dual);
972 1025
973 LOG_WARNING(Service_HID, "(STUBBED) called, npad_id={}, applet_resource_user_id={}", 1026 LOG_WARNING(Service_HID, "(STUBBED) called, npad_id={}, applet_resource_user_id={}",
974 parameters.npad_id, parameters.applet_resource_user_id); 1027 parameters.npad_id, parameters.applet_resource_user_id);
@@ -979,8 +1032,8 @@ void Hid::SetNpadJoyAssignmentModeDual(Kernel::HLERequestContext& ctx) {
979 1032
980void Hid::MergeSingleJoyAsDualJoy(Kernel::HLERequestContext& ctx) { 1033void Hid::MergeSingleJoyAsDualJoy(Kernel::HLERequestContext& ctx) {
981 IPC::RequestParser rp{ctx}; 1034 IPC::RequestParser rp{ctx};
982 const auto npad_id_1{rp.Pop<u32>()}; 1035 const auto npad_id_1{rp.PopEnum<Core::HID::NpadIdType>()};
983 const auto npad_id_2{rp.Pop<u32>()}; 1036 const auto npad_id_2{rp.PopEnum<Core::HID::NpadIdType>()};
984 const auto applet_resource_user_id{rp.Pop<u64>()}; 1037 const auto applet_resource_user_id{rp.Pop<u64>()};
985 1038
986 applet_resource->GetController<Controller_NPad>(HidController::NPad) 1039 applet_resource->GetController<Controller_NPad>(HidController::NPad)
@@ -1046,8 +1099,8 @@ void Hid::GetNpadHandheldActivationMode(Kernel::HLERequestContext& ctx) {
1046 1099
1047void Hid::SwapNpadAssignment(Kernel::HLERequestContext& ctx) { 1100void Hid::SwapNpadAssignment(Kernel::HLERequestContext& ctx) {
1048 IPC::RequestParser rp{ctx}; 1101 IPC::RequestParser rp{ctx};
1049 const auto npad_id_1{rp.Pop<u32>()}; 1102 const auto npad_id_1{rp.PopEnum<Core::HID::NpadIdType>()};
1050 const auto npad_id_2{rp.Pop<u32>()}; 1103 const auto npad_id_2{rp.PopEnum<Core::HID::NpadIdType>()};
1051 const auto applet_resource_user_id{rp.Pop<u64>()}; 1104 const auto applet_resource_user_id{rp.Pop<u64>()};
1052 1105
1053 const bool res = applet_resource->GetController<Controller_NPad>(HidController::NPad) 1106 const bool res = applet_resource->GetController<Controller_NPad>(HidController::NPad)
@@ -1068,10 +1121,11 @@ void Hid::SwapNpadAssignment(Kernel::HLERequestContext& ctx) {
1068void Hid::IsUnintendedHomeButtonInputProtectionEnabled(Kernel::HLERequestContext& ctx) { 1121void Hid::IsUnintendedHomeButtonInputProtectionEnabled(Kernel::HLERequestContext& ctx) {
1069 IPC::RequestParser rp{ctx}; 1122 IPC::RequestParser rp{ctx};
1070 struct Parameters { 1123 struct Parameters {
1071 u32 npad_id; 1124 Core::HID::NpadIdType npad_id;
1072 INSERT_PADDING_WORDS_NOINIT(1); 1125 INSERT_PADDING_WORDS_NOINIT(1);
1073 u64 applet_resource_user_id; 1126 u64 applet_resource_user_id;
1074 }; 1127 };
1128 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
1075 1129
1076 const auto parameters{rp.PopRaw<Parameters>()}; 1130 const auto parameters{rp.PopRaw<Parameters>()};
1077 1131
@@ -1089,9 +1143,10 @@ void Hid::EnableUnintendedHomeButtonInputProtection(Kernel::HLERequestContext& c
1089 struct Parameters { 1143 struct Parameters {
1090 bool unintended_home_button_input_protection; 1144 bool unintended_home_button_input_protection;
1091 INSERT_PADDING_BYTES_NOINIT(3); 1145 INSERT_PADDING_BYTES_NOINIT(3);
1092 u32 npad_id; 1146 Core::HID::NpadIdType npad_id;
1093 u64 applet_resource_user_id; 1147 u64 applet_resource_user_id;
1094 }; 1148 };
1149 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
1095 1150
1096 const auto parameters{rp.PopRaw<Parameters>()}; 1151 const auto parameters{rp.PopRaw<Parameters>()};
1097 1152
@@ -1113,6 +1168,7 @@ void Hid::SetNpadAnalogStickUseCenterClamp(Kernel::HLERequestContext& ctx) {
1113 IPC::RequestParser rp{ctx}; 1168 IPC::RequestParser rp{ctx};
1114 struct Parameters { 1169 struct Parameters {
1115 bool analog_stick_use_center_clamp; 1170 bool analog_stick_use_center_clamp;
1171 INSERT_PADDING_BYTES_NOINIT(7);
1116 u64 applet_resource_user_id; 1172 u64 applet_resource_user_id;
1117 }; 1173 };
1118 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size."); 1174 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
@@ -1132,38 +1188,38 @@ void Hid::SetNpadAnalogStickUseCenterClamp(Kernel::HLERequestContext& ctx) {
1132 1188
1133void Hid::GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx) { 1189void Hid::GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx) {
1134 IPC::RequestParser rp{ctx}; 1190 IPC::RequestParser rp{ctx};
1135 const auto vibration_device_handle{rp.PopRaw<Controller_NPad::DeviceHandle>()}; 1191 const auto vibration_device_handle{rp.PopRaw<Core::HID::VibrationDeviceHandle>()};
1136 1192
1137 VibrationDeviceInfo vibration_device_info; 1193 Core::HID::VibrationDeviceInfo vibration_device_info;
1138 1194
1139 switch (vibration_device_handle.npad_type) { 1195 switch (vibration_device_handle.npad_type) {
1140 case Controller_NPad::NpadType::ProController: 1196 case Core::HID::NpadStyleIndex::ProController:
1141 case Controller_NPad::NpadType::Handheld: 1197 case Core::HID::NpadStyleIndex::Handheld:
1142 case Controller_NPad::NpadType::JoyconDual: 1198 case Core::HID::NpadStyleIndex::JoyconDual:
1143 case Controller_NPad::NpadType::JoyconLeft: 1199 case Core::HID::NpadStyleIndex::JoyconLeft:
1144 case Controller_NPad::NpadType::JoyconRight: 1200 case Core::HID::NpadStyleIndex::JoyconRight:
1145 default: 1201 default:
1146 vibration_device_info.type = VibrationDeviceType::LinearResonantActuator; 1202 vibration_device_info.type = Core::HID::VibrationDeviceType::LinearResonantActuator;
1147 break; 1203 break;
1148 case Controller_NPad::NpadType::GameCube: 1204 case Core::HID::NpadStyleIndex::GameCube:
1149 vibration_device_info.type = VibrationDeviceType::GcErm; 1205 vibration_device_info.type = Core::HID::VibrationDeviceType::GcErm;
1150 break; 1206 break;
1151 case Controller_NPad::NpadType::Pokeball: 1207 case Core::HID::NpadStyleIndex::Pokeball:
1152 vibration_device_info.type = VibrationDeviceType::Unknown; 1208 vibration_device_info.type = Core::HID::VibrationDeviceType::Unknown;
1153 break; 1209 break;
1154 } 1210 }
1155 1211
1156 switch (vibration_device_handle.device_index) { 1212 switch (vibration_device_handle.device_index) {
1157 case Controller_NPad::DeviceIndex::Left: 1213 case Core::HID::DeviceIndex::Left:
1158 vibration_device_info.position = VibrationDevicePosition::Left; 1214 vibration_device_info.position = Core::HID::VibrationDevicePosition::Left;
1159 break; 1215 break;
1160 case Controller_NPad::DeviceIndex::Right: 1216 case Core::HID::DeviceIndex::Right:
1161 vibration_device_info.position = VibrationDevicePosition::Right; 1217 vibration_device_info.position = Core::HID::VibrationDevicePosition::Right;
1162 break; 1218 break;
1163 case Controller_NPad::DeviceIndex::None: 1219 case Core::HID::DeviceIndex::None:
1164 default: 1220 default:
1165 UNREACHABLE_MSG("DeviceIndex should never be None!"); 1221 UNREACHABLE_MSG("DeviceIndex should never be None!");
1166 vibration_device_info.position = VibrationDevicePosition::None; 1222 vibration_device_info.position = Core::HID::VibrationDevicePosition::None;
1167 break; 1223 break;
1168 } 1224 }
1169 1225
@@ -1178,11 +1234,12 @@ void Hid::GetVibrationDeviceInfo(Kernel::HLERequestContext& ctx) {
1178void Hid::SendVibrationValue(Kernel::HLERequestContext& ctx) { 1234void Hid::SendVibrationValue(Kernel::HLERequestContext& ctx) {
1179 IPC::RequestParser rp{ctx}; 1235 IPC::RequestParser rp{ctx};
1180 struct Parameters { 1236 struct Parameters {
1181 Controller_NPad::DeviceHandle vibration_device_handle; 1237 Core::HID::VibrationDeviceHandle vibration_device_handle;
1182 Controller_NPad::VibrationValue vibration_value; 1238 Core::HID::VibrationValue vibration_value;
1183 INSERT_PADDING_WORDS_NOINIT(1); 1239 INSERT_PADDING_WORDS_NOINIT(1);
1184 u64 applet_resource_user_id; 1240 u64 applet_resource_user_id;
1185 }; 1241 };
1242 static_assert(sizeof(Parameters) == 0x20, "Parameters has incorrect size.");
1186 1243
1187 const auto parameters{rp.PopRaw<Parameters>()}; 1244 const auto parameters{rp.PopRaw<Parameters>()};
1188 1245
@@ -1202,10 +1259,11 @@ void Hid::SendVibrationValue(Kernel::HLERequestContext& ctx) {
1202void Hid::GetActualVibrationValue(Kernel::HLERequestContext& ctx) { 1259void Hid::GetActualVibrationValue(Kernel::HLERequestContext& ctx) {
1203 IPC::RequestParser rp{ctx}; 1260 IPC::RequestParser rp{ctx};
1204 struct Parameters { 1261 struct Parameters {
1205 Controller_NPad::DeviceHandle vibration_device_handle; 1262 Core::HID::VibrationDeviceHandle vibration_device_handle;
1206 INSERT_PADDING_WORDS_NOINIT(1); 1263 INSERT_PADDING_WORDS_NOINIT(1);
1207 u64 applet_resource_user_id; 1264 u64 applet_resource_user_id;
1208 }; 1265 };
1266 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
1209 1267
1210 const auto parameters{rp.PopRaw<Parameters>()}; 1268 const auto parameters{rp.PopRaw<Parameters>()};
1211 1269
@@ -1256,10 +1314,10 @@ void Hid::SendVibrationValues(Kernel::HLERequestContext& ctx) {
1256 const auto handles = ctx.ReadBuffer(0); 1314 const auto handles = ctx.ReadBuffer(0);
1257 const auto vibrations = ctx.ReadBuffer(1); 1315 const auto vibrations = ctx.ReadBuffer(1);
1258 1316
1259 std::vector<Controller_NPad::DeviceHandle> vibration_device_handles( 1317 std::vector<Core::HID::VibrationDeviceHandle> vibration_device_handles(
1260 handles.size() / sizeof(Controller_NPad::DeviceHandle)); 1318 handles.size() / sizeof(Core::HID::VibrationDeviceHandle));
1261 std::vector<Controller_NPad::VibrationValue> vibration_values( 1319 std::vector<Core::HID::VibrationValue> vibration_values(vibrations.size() /
1262 vibrations.size() / sizeof(Controller_NPad::VibrationValue)); 1320 sizeof(Core::HID::VibrationValue));
1263 1321
1264 std::memcpy(vibration_device_handles.data(), handles.data(), handles.size()); 1322 std::memcpy(vibration_device_handles.data(), handles.data(), handles.size());
1265 std::memcpy(vibration_values.data(), vibrations.data(), vibrations.size()); 1323 std::memcpy(vibration_values.data(), vibrations.data(), vibrations.size());
@@ -1276,9 +1334,10 @@ void Hid::SendVibrationValues(Kernel::HLERequestContext& ctx) {
1276void Hid::SendVibrationGcErmCommand(Kernel::HLERequestContext& ctx) { 1334void Hid::SendVibrationGcErmCommand(Kernel::HLERequestContext& ctx) {
1277 IPC::RequestParser rp{ctx}; 1335 IPC::RequestParser rp{ctx};
1278 struct Parameters { 1336 struct Parameters {
1279 Controller_NPad::DeviceHandle vibration_device_handle; 1337 Core::HID::VibrationDeviceHandle vibration_device_handle;
1338 INSERT_PADDING_WORDS_NOINIT(1);
1280 u64 applet_resource_user_id; 1339 u64 applet_resource_user_id;
1281 VibrationGcErmCommand gc_erm_command; 1340 Core::HID::VibrationGcErmCommand gc_erm_command;
1282 }; 1341 };
1283 static_assert(sizeof(Parameters) == 0x18, "Parameters has incorrect size."); 1342 static_assert(sizeof(Parameters) == 0x18, "Parameters has incorrect size.");
1284 1343
@@ -1292,26 +1351,26 @@ void Hid::SendVibrationGcErmCommand(Kernel::HLERequestContext& ctx) {
1292 */ 1351 */
1293 const auto vibration_value = [parameters] { 1352 const auto vibration_value = [parameters] {
1294 switch (parameters.gc_erm_command) { 1353 switch (parameters.gc_erm_command) {
1295 case VibrationGcErmCommand::Stop: 1354 case Core::HID::VibrationGcErmCommand::Stop:
1296 return Controller_NPad::VibrationValue{ 1355 return Core::HID::VibrationValue{
1297 .amp_low = 0.0f, 1356 .low_amplitude = 0.0f,
1298 .freq_low = 160.0f, 1357 .low_frequency = 160.0f,
1299 .amp_high = 0.0f, 1358 .high_amplitude = 0.0f,
1300 .freq_high = 320.0f, 1359 .high_frequency = 320.0f,
1301 }; 1360 };
1302 case VibrationGcErmCommand::Start: 1361 case Core::HID::VibrationGcErmCommand::Start:
1303 return Controller_NPad::VibrationValue{ 1362 return Core::HID::VibrationValue{
1304 .amp_low = 1.0f, 1363 .low_amplitude = 1.0f,
1305 .freq_low = 160.0f, 1364 .low_frequency = 160.0f,
1306 .amp_high = 1.0f, 1365 .high_amplitude = 1.0f,
1307 .freq_high = 320.0f, 1366 .high_frequency = 320.0f,
1308 }; 1367 };
1309 case VibrationGcErmCommand::StopHard: 1368 case Core::HID::VibrationGcErmCommand::StopHard:
1310 return Controller_NPad::VibrationValue{ 1369 return Core::HID::VibrationValue{
1311 .amp_low = 0.0f, 1370 .low_amplitude = 0.0f,
1312 .freq_low = 0.0f, 1371 .low_frequency = 0.0f,
1313 .amp_high = 0.0f, 1372 .high_amplitude = 0.0f,
1314 .freq_high = 0.0f, 1373 .high_frequency = 0.0f,
1315 }; 1374 };
1316 default: 1375 default:
1317 return Controller_NPad::DEFAULT_VIBRATION_VALUE; 1376 return Controller_NPad::DEFAULT_VIBRATION_VALUE;
@@ -1336,7 +1395,7 @@ void Hid::SendVibrationGcErmCommand(Kernel::HLERequestContext& ctx) {
1336void Hid::GetActualVibrationGcErmCommand(Kernel::HLERequestContext& ctx) { 1395void Hid::GetActualVibrationGcErmCommand(Kernel::HLERequestContext& ctx) {
1337 IPC::RequestParser rp{ctx}; 1396 IPC::RequestParser rp{ctx};
1338 struct Parameters { 1397 struct Parameters {
1339 Controller_NPad::DeviceHandle vibration_device_handle; 1398 Core::HID::VibrationDeviceHandle vibration_device_handle;
1340 INSERT_PADDING_WORDS_NOINIT(1); 1399 INSERT_PADDING_WORDS_NOINIT(1);
1341 u64 applet_resource_user_id; 1400 u64 applet_resource_user_id;
1342 }; 1401 };
@@ -1347,8 +1406,8 @@ void Hid::GetActualVibrationGcErmCommand(Kernel::HLERequestContext& ctx) {
1347 .GetLastVibration(parameters.vibration_device_handle); 1406 .GetLastVibration(parameters.vibration_device_handle);
1348 1407
1349 const auto gc_erm_command = [last_vibration] { 1408 const auto gc_erm_command = [last_vibration] {
1350 if (last_vibration.amp_low != 0.0f || last_vibration.amp_high != 0.0f) { 1409 if (last_vibration.low_amplitude != 0.0f || last_vibration.high_amplitude != 0.0f) {
1351 return VibrationGcErmCommand::Start; 1410 return Core::HID::VibrationGcErmCommand::Start;
1352 } 1411 }
1353 1412
1354 /** 1413 /**
@@ -1357,11 +1416,11 @@ void Hid::GetActualVibrationGcErmCommand(Kernel::HLERequestContext& ctx) {
1357 * SendVibrationGcErmCommand, in order to differentiate between Stop and StopHard commands. 1416 * SendVibrationGcErmCommand, in order to differentiate between Stop and StopHard commands.
1358 * This is done to reuse the controller vibration functions made for regular controllers. 1417 * This is done to reuse the controller vibration functions made for regular controllers.
1359 */ 1418 */
1360 if (last_vibration.freq_low == 0.0f && last_vibration.freq_high == 0.0f) { 1419 if (last_vibration.low_frequency == 0.0f && last_vibration.high_frequency == 0.0f) {
1361 return VibrationGcErmCommand::StopHard; 1420 return Core::HID::VibrationGcErmCommand::StopHard;
1362 } 1421 }
1363 1422
1364 return VibrationGcErmCommand::Stop; 1423 return Core::HID::VibrationGcErmCommand::Stop;
1365 }(); 1424 }();
1366 1425
1367 LOG_DEBUG(Service_HID, 1426 LOG_DEBUG(Service_HID,
@@ -1401,10 +1460,11 @@ void Hid::EndPermitVibrationSession(Kernel::HLERequestContext& ctx) {
1401void Hid::IsVibrationDeviceMounted(Kernel::HLERequestContext& ctx) { 1460void Hid::IsVibrationDeviceMounted(Kernel::HLERequestContext& ctx) {
1402 IPC::RequestParser rp{ctx}; 1461 IPC::RequestParser rp{ctx};
1403 struct Parameters { 1462 struct Parameters {
1404 Controller_NPad::DeviceHandle vibration_device_handle; 1463 Core::HID::VibrationDeviceHandle vibration_device_handle;
1405 INSERT_PADDING_WORDS_NOINIT(1); 1464 INSERT_PADDING_WORDS_NOINIT(1);
1406 u64 applet_resource_user_id; 1465 u64 applet_resource_user_id;
1407 }; 1466 };
1467 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
1408 1468
1409 const auto parameters{rp.PopRaw<Parameters>()}; 1469 const auto parameters{rp.PopRaw<Parameters>()};
1410 1470
@@ -1435,18 +1495,18 @@ void Hid::ActivateConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) {
1435void Hid::StartConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) { 1495void Hid::StartConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) {
1436 IPC::RequestParser rp{ctx}; 1496 IPC::RequestParser rp{ctx};
1437 struct Parameters { 1497 struct Parameters {
1438 Controller_NPad::DeviceHandle sixaxis_handle; 1498 Core::HID::ConsoleSixAxisSensorHandle console_sixaxis_handle;
1439 INSERT_PADDING_WORDS_NOINIT(1); 1499 INSERT_PADDING_WORDS_NOINIT(1);
1440 u64 applet_resource_user_id; 1500 u64 applet_resource_user_id;
1441 }; 1501 };
1502 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
1442 1503
1443 const auto parameters{rp.PopRaw<Parameters>()}; 1504 const auto parameters{rp.PopRaw<Parameters>()};
1444 1505
1445 LOG_WARNING( 1506 LOG_WARNING(Service_HID,
1446 Service_HID, 1507 "(STUBBED) called, unknown_1={}, unknown_2={}, applet_resource_user_id={}",
1447 "(STUBBED) called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 1508 parameters.console_sixaxis_handle.unknown_1,
1448 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id, 1509 parameters.console_sixaxis_handle.unknown_2, parameters.applet_resource_user_id);
1449 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
1450 1510
1451 IPC::ResponseBuilder rb{ctx, 2}; 1511 IPC::ResponseBuilder rb{ctx, 2};
1452 rb.Push(ResultSuccess); 1512 rb.Push(ResultSuccess);
@@ -1455,18 +1515,18 @@ void Hid::StartConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) {
1455void Hid::StopConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) { 1515void Hid::StopConsoleSixAxisSensor(Kernel::HLERequestContext& ctx) {
1456 IPC::RequestParser rp{ctx}; 1516 IPC::RequestParser rp{ctx};
1457 struct Parameters { 1517 struct Parameters {
1458 Controller_NPad::DeviceHandle sixaxis_handle; 1518 Core::HID::ConsoleSixAxisSensorHandle console_sixaxis_handle;
1459 INSERT_PADDING_WORDS_NOINIT(1); 1519 INSERT_PADDING_WORDS_NOINIT(1);
1460 u64 applet_resource_user_id; 1520 u64 applet_resource_user_id;
1461 }; 1521 };
1522 static_assert(sizeof(Parameters) == 0x10, "Parameters has incorrect size.");
1462 1523
1463 const auto parameters{rp.PopRaw<Parameters>()}; 1524 const auto parameters{rp.PopRaw<Parameters>()};
1464 1525
1465 LOG_WARNING( 1526 LOG_WARNING(Service_HID,
1466 Service_HID, 1527 "(STUBBED) called, unknown_1={}, unknown_2={}, applet_resource_user_id={}",
1467 "(STUBBED) called, npad_type={}, npad_id={}, device_index={}, applet_resource_user_id={}", 1528 parameters.console_sixaxis_handle.unknown_1,
1468 parameters.sixaxis_handle.npad_type, parameters.sixaxis_handle.npad_id, 1529 parameters.console_sixaxis_handle.unknown_2, parameters.applet_resource_user_id);
1469 parameters.sixaxis_handle.device_index, parameters.applet_resource_user_id);
1470 1530
1471 IPC::ResponseBuilder rb{ctx, 2}; 1531 IPC::ResponseBuilder rb{ctx, 2};
1472 rb.Push(ResultSuccess); 1532 rb.Push(ResultSuccess);
@@ -1620,10 +1680,8 @@ void Hid::SetNpadCommunicationMode(Kernel::HLERequestContext& ctx) {
1620 1680
1621void Hid::GetNpadCommunicationMode(Kernel::HLERequestContext& ctx) { 1681void Hid::GetNpadCommunicationMode(Kernel::HLERequestContext& ctx) {
1622 IPC::RequestParser rp{ctx}; 1682 IPC::RequestParser rp{ctx};
1623 const auto applet_resource_user_id{rp.Pop<u64>()};
1624 1683
1625 LOG_WARNING(Service_HID, "(STUBBED) called, applet_resource_user_id={}", 1684 LOG_WARNING(Service_HID, "(STUBBED) called");
1626 applet_resource_user_id);
1627 1685
1628 IPC::ResponseBuilder rb{ctx, 4}; 1686 IPC::ResponseBuilder rb{ctx, 4};
1629 rb.Push(ResultSuccess); 1687 rb.Push(ResultSuccess);
@@ -2037,10 +2095,6 @@ public:
2037 } 2095 }
2038}; 2096};
2039 2097
2040void ReloadInputDevices() {
2041 Settings::values.is_device_reload_pending.store(true);
2042}
2043
2044void InstallInterfaces(SM::ServiceManager& service_manager, Core::System& system) { 2098void InstallInterfaces(SM::ServiceManager& service_manager, Core::System& system) {
2045 std::make_shared<Hid>(system)->InstallAsService(service_manager); 2099 std::make_shared<Hid>(system)->InstallAsService(service_manager);
2046 std::make_shared<HidBus>(system)->InstallAsService(service_manager); 2100 std::make_shared<HidBus>(system)->InstallAsService(service_manager);
diff --git a/src/core/hle/service/hid/hid.h b/src/core/hle/service/hid/hid.h
index b1fe75e94..ab0084118 100644
--- a/src/core/hle/service/hid/hid.h
+++ b/src/core/hle/service/hid/hid.h
@@ -60,21 +60,23 @@ public:
60private: 60private:
61 template <typename T> 61 template <typename T>
62 void MakeController(HidController controller) { 62 void MakeController(HidController controller) {
63 controllers[static_cast<std::size_t>(controller)] = std::make_unique<T>(system); 63 controllers[static_cast<std::size_t>(controller)] = std::make_unique<T>(system.HIDCore());
64 } 64 }
65 template <typename T> 65 template <typename T>
66 void MakeControllerWithServiceContext(HidController controller) { 66 void MakeControllerWithServiceContext(HidController controller) {
67 controllers[static_cast<std::size_t>(controller)] = 67 controllers[static_cast<std::size_t>(controller)] =
68 std::make_unique<T>(system, service_context); 68 std::make_unique<T>(system.HIDCore(), service_context);
69 } 69 }
70 70
71 void GetSharedMemoryHandle(Kernel::HLERequestContext& ctx); 71 void GetSharedMemoryHandle(Kernel::HLERequestContext& ctx);
72 void UpdateControllers(std::uintptr_t user_data, std::chrono::nanoseconds ns_late); 72 void UpdateControllers(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
73 void UpdateMouseKeyboard(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
73 void UpdateMotion(std::uintptr_t user_data, std::chrono::nanoseconds ns_late); 74 void UpdateMotion(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
74 75
75 KernelHelpers::ServiceContext& service_context; 76 KernelHelpers::ServiceContext& service_context;
76 77
77 std::shared_ptr<Core::Timing::EventType> pad_update_event; 78 std::shared_ptr<Core::Timing::EventType> pad_update_event;
79 std::shared_ptr<Core::Timing::EventType> mouse_keyboard_update_event;
78 std::shared_ptr<Core::Timing::EventType> motion_update_event; 80 std::shared_ptr<Core::Timing::EventType> motion_update_event;
79 81
80 std::array<std::unique_ptr<ControllerBase>, static_cast<size_t>(HidController::MaxControllers)> 82 std::array<std::unique_ptr<ControllerBase>, static_cast<size_t>(HidController::MaxControllers)>
@@ -161,38 +163,11 @@ private:
161 void GetNpadCommunicationMode(Kernel::HLERequestContext& ctx); 163 void GetNpadCommunicationMode(Kernel::HLERequestContext& ctx);
162 void SetTouchScreenConfiguration(Kernel::HLERequestContext& ctx); 164 void SetTouchScreenConfiguration(Kernel::HLERequestContext& ctx);
163 165
164 enum class VibrationDeviceType : u32 {
165 Unknown = 0,
166 LinearResonantActuator = 1,
167 GcErm = 2,
168 };
169
170 enum class VibrationDevicePosition : u32 {
171 None = 0,
172 Left = 1,
173 Right = 2,
174 };
175
176 enum class VibrationGcErmCommand : u64 {
177 Stop = 0,
178 Start = 1,
179 StopHard = 2,
180 };
181
182 struct VibrationDeviceInfo {
183 VibrationDeviceType type{};
184 VibrationDevicePosition position{};
185 };
186 static_assert(sizeof(VibrationDeviceInfo) == 0x8, "VibrationDeviceInfo has incorrect size.");
187
188 std::shared_ptr<IAppletResource> applet_resource; 166 std::shared_ptr<IAppletResource> applet_resource;
189 167
190 KernelHelpers::ServiceContext service_context; 168 KernelHelpers::ServiceContext service_context;
191}; 169};
192 170
193/// Reload input devices. Used when input configuration changed
194void ReloadInputDevices();
195
196/// Registers all HID services with the specified service manager. 171/// Registers all HID services with the specified service manager.
197void InstallInterfaces(SM::ServiceManager& service_manager, Core::System& system); 172void InstallInterfaces(SM::ServiceManager& service_manager, Core::System& system);
198 173
diff --git a/src/core/hle/service/hid/ring_lifo.h b/src/core/hle/service/hid/ring_lifo.h
new file mode 100644
index 000000000..44c20d967
--- /dev/null
+++ b/src/core/hle/service/hid/ring_lifo.h
@@ -0,0 +1,54 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included
4
5#pragma once
6
7#include <array>
8
9#include "common/common_types.h"
10
11namespace Service::HID {
12
13template <typename State>
14struct AtomicStorage {
15 s64 sampling_number;
16 State state;
17};
18
19template <typename State, std::size_t max_buffer_size>
20struct Lifo {
21 s64 timestamp{};
22 s64 total_buffer_count = static_cast<s64>(max_buffer_size);
23 s64 buffer_tail{};
24 s64 buffer_count{};
25 std::array<AtomicStorage<State>, max_buffer_size> entries{};
26
27 const AtomicStorage<State>& ReadCurrentEntry() const {
28 return entries[buffer_tail];
29 }
30
31 const AtomicStorage<State>& ReadPreviousEntry() const {
32 return entries[GetPreviousEntryIndex()];
33 }
34
35 std::size_t GetPreviousEntryIndex() const {
36 return static_cast<size_t>((buffer_tail + total_buffer_count - 1) % total_buffer_count);
37 }
38
39 std::size_t GetNextEntryIndex() const {
40 return static_cast<size_t>((buffer_tail + 1) % total_buffer_count);
41 }
42
43 void WriteNextEntry(const State& new_state) {
44 if (buffer_count < total_buffer_count - 1) {
45 buffer_count++;
46 }
47 buffer_tail = GetNextEntryIndex();
48 const auto& previous_entry = ReadPreviousEntry();
49 entries[buffer_tail].sampling_number = previous_entry.sampling_number + 1;
50 entries[buffer_tail].state = new_state;
51 }
52};
53
54} // namespace Service::HID