summaryrefslogtreecommitdiff
path: root/src/input_common
diff options
context:
space:
mode:
Diffstat (limited to 'src/input_common')
-rw-r--r--src/input_common/gcadapter/gc_adapter.cpp97
-rw-r--r--src/input_common/gcadapter/gc_adapter.h5
-rw-r--r--src/input_common/main.cpp57
-rw-r--r--src/input_common/main.h24
-rw-r--r--src/input_common/motion_emu.cpp17
-rw-r--r--src/input_common/sdl/sdl_impl.cpp39
-rw-r--r--src/input_common/settings.cpp7
-rw-r--r--src/input_common/settings.h17
-rw-r--r--src/input_common/udp/client.cpp176
-rw-r--r--src/input_common/udp/client.h77
-rw-r--r--src/input_common/udp/udp.cpp181
-rw-r--r--src/input_common/udp/udp.h61
12 files changed, 621 insertions, 137 deletions
diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp
index c6c423c4b..89c148aba 100644
--- a/src/input_common/gcadapter/gc_adapter.cpp
+++ b/src/input_common/gcadapter/gc_adapter.cpp
@@ -4,9 +4,20 @@
4 4
5#include <chrono> 5#include <chrono>
6#include <thread> 6#include <thread>
7
8#ifdef _MSC_VER
9#pragma warning(push)
10#pragma warning(disable : 4200) // nonstandard extension used : zero-sized array in struct/union
11#endif
7#include <libusb.h> 12#include <libusb.h>
13#ifdef _MSC_VER
14#pragma warning(pop)
15#endif
16
8#include "common/logging/log.h" 17#include "common/logging/log.h"
18#include "common/param_package.h"
9#include "input_common/gcadapter/gc_adapter.h" 19#include "input_common/gcadapter/gc_adapter.h"
20#include "input_common/settings.h"
10 21
11namespace GCAdapter { 22namespace GCAdapter {
12 23
@@ -283,6 +294,92 @@ void Adapter::Reset() {
283 } 294 }
284} 295}
285 296
297std::vector<Common::ParamPackage> Adapter::GetInputDevices() const {
298 std::vector<Common::ParamPackage> devices;
299 for (std::size_t port = 0; port < state.size(); ++port) {
300 if (!DeviceConnected(port)) {
301 continue;
302 }
303 std::string name = fmt::format("Gamecube Controller {}", port);
304 devices.emplace_back(Common::ParamPackage{
305 {"class", "gcpad"},
306 {"display", std::move(name)},
307 {"port", std::to_string(port)},
308 });
309 }
310 return devices;
311}
312
313InputCommon::ButtonMapping Adapter::GetButtonMappingForDevice(
314 const Common::ParamPackage& params) const {
315 // This list is missing ZL/ZR since those are not considered buttons.
316 // We will add those afterwards
317 // This list also excludes any button that can't be really mapped
318 static constexpr std::array<std::pair<Settings::NativeButton::Values, PadButton>, 12>
319 switch_to_gcadapter_button = {
320 std::pair{Settings::NativeButton::A, PadButton::PAD_BUTTON_A},
321 {Settings::NativeButton::B, PadButton::PAD_BUTTON_B},
322 {Settings::NativeButton::X, PadButton::PAD_BUTTON_X},
323 {Settings::NativeButton::Y, PadButton::PAD_BUTTON_Y},
324 {Settings::NativeButton::Plus, PadButton::PAD_BUTTON_START},
325 {Settings::NativeButton::DLeft, PadButton::PAD_BUTTON_LEFT},
326 {Settings::NativeButton::DUp, PadButton::PAD_BUTTON_UP},
327 {Settings::NativeButton::DRight, PadButton::PAD_BUTTON_RIGHT},
328 {Settings::NativeButton::DDown, PadButton::PAD_BUTTON_DOWN},
329 {Settings::NativeButton::SL, PadButton::PAD_TRIGGER_L},
330 {Settings::NativeButton::SR, PadButton::PAD_TRIGGER_R},
331 {Settings::NativeButton::R, PadButton::PAD_TRIGGER_Z},
332 };
333 if (!params.Has("port")) {
334 return {};
335 }
336
337 InputCommon::ButtonMapping mapping{};
338 for (const auto& [switch_button, gcadapter_button] : switch_to_gcadapter_button) {
339 Common::ParamPackage button_params({{"engine", "gcpad"}});
340 button_params.Set("port", params.Get("port", 0));
341 button_params.Set("button", static_cast<int>(gcadapter_button));
342 mapping.insert_or_assign(switch_button, std::move(button_params));
343 }
344
345 // Add the missing bindings for ZL/ZR
346 static constexpr std::array<std::pair<Settings::NativeButton::Values, PadAxes>, 2>
347 switch_to_gcadapter_axis = {
348 std::pair{Settings::NativeButton::ZL, PadAxes::TriggerLeft},
349 {Settings::NativeButton::ZR, PadAxes::TriggerRight},
350 };
351 for (const auto& [switch_button, gcadapter_axis] : switch_to_gcadapter_axis) {
352 Common::ParamPackage button_params({{"engine", "gcpad"}});
353 button_params.Set("port", params.Get("port", 0));
354 button_params.Set("button", static_cast<int>(PadButton::PAD_STICK));
355 button_params.Set("axis", static_cast<int>(gcadapter_axis));
356 mapping.insert_or_assign(switch_button, std::move(button_params));
357 }
358 return mapping;
359}
360
361InputCommon::AnalogMapping Adapter::GetAnalogMappingForDevice(
362 const Common::ParamPackage& params) const {
363 if (!params.Has("port")) {
364 return {};
365 }
366
367 InputCommon::AnalogMapping mapping = {};
368 Common::ParamPackage left_analog_params;
369 left_analog_params.Set("engine", "gcpad");
370 left_analog_params.Set("port", params.Get("port", 0));
371 left_analog_params.Set("axis_x", static_cast<int>(PadAxes::StickX));
372 left_analog_params.Set("axis_y", static_cast<int>(PadAxes::StickY));
373 mapping.insert_or_assign(Settings::NativeAnalog::LStick, std::move(left_analog_params));
374 Common::ParamPackage right_analog_params;
375 right_analog_params.Set("engine", "gcpad");
376 right_analog_params.Set("port", params.Get("port", 0));
377 right_analog_params.Set("axis_x", static_cast<int>(PadAxes::SubstickX));
378 right_analog_params.Set("axis_y", static_cast<int>(PadAxes::SubstickY));
379 mapping.insert_or_assign(Settings::NativeAnalog::RStick, std::move(right_analog_params));
380 return mapping;
381}
382
286bool Adapter::DeviceConnected(std::size_t port) const { 383bool Adapter::DeviceConnected(std::size_t port) const {
287 return adapter_controllers_status[port] != ControllerTypes::None; 384 return adapter_controllers_status[port] != ControllerTypes::None;
288} 385}
diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h
index 20e97d283..75bf9fe74 100644
--- a/src/input_common/gcadapter/gc_adapter.h
+++ b/src/input_common/gcadapter/gc_adapter.h
@@ -10,6 +10,7 @@
10#include <unordered_map> 10#include <unordered_map>
11#include "common/common_types.h" 11#include "common/common_types.h"
12#include "common/threadsafe_queue.h" 12#include "common/threadsafe_queue.h"
13#include "input_common/main.h"
13 14
14struct libusb_context; 15struct libusb_context;
15struct libusb_device; 16struct libusb_device;
@@ -75,6 +76,10 @@ public:
75 void BeginConfiguration(); 76 void BeginConfiguration();
76 void EndConfiguration(); 77 void EndConfiguration();
77 78
79 std::vector<Common::ParamPackage> GetInputDevices() const;
80 InputCommon::ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& params) const;
81 InputCommon::AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) const;
82
78 /// Returns true if there is a device connected to port 83 /// Returns true if there is a device connected to port
79 bool DeviceConnected(std::size_t port) const; 84 bool DeviceConnected(std::size_t port) const;
80 85
diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp
index ea1a1cee6..8da829132 100644
--- a/src/input_common/main.cpp
+++ b/src/input_common/main.cpp
@@ -12,6 +12,7 @@
12#include "input_common/main.h" 12#include "input_common/main.h"
13#include "input_common/motion_emu.h" 13#include "input_common/motion_emu.h"
14#include "input_common/touch_from_button.h" 14#include "input_common/touch_from_button.h"
15#include "input_common/udp/client.h"
15#include "input_common/udp/udp.h" 16#include "input_common/udp/udp.h"
16#ifdef HAVE_SDL2 17#ifdef HAVE_SDL2
17#include "input_common/sdl/sdl.h" 18#include "input_common/sdl/sdl.h"
@@ -21,7 +22,7 @@ namespace InputCommon {
21 22
22struct InputSubsystem::Impl { 23struct InputSubsystem::Impl {
23 void Initialize() { 24 void Initialize() {
24 auto gcadapter = std::make_shared<GCAdapter::Adapter>(); 25 gcadapter = std::make_shared<GCAdapter::Adapter>();
25 gcbuttons = std::make_shared<GCButtonFactory>(gcadapter); 26 gcbuttons = std::make_shared<GCButtonFactory>(gcadapter);
26 Input::RegisterFactory<Input::ButtonDevice>("gcpad", gcbuttons); 27 Input::RegisterFactory<Input::ButtonDevice>("gcpad", gcbuttons);
27 gcanalog = std::make_shared<GCAnalogFactory>(gcadapter); 28 gcanalog = std::make_shared<GCAnalogFactory>(gcadapter);
@@ -40,7 +41,11 @@ struct InputSubsystem::Impl {
40 sdl = SDL::Init(); 41 sdl = SDL::Init();
41#endif 42#endif
42 43
43 udp = CemuhookUDP::Init(); 44 udp = std::make_shared<InputCommon::CemuhookUDP::Client>();
45 udpmotion = std::make_shared<UDPMotionFactory>(udp);
46 Input::RegisterFactory<Input::MotionDevice>("cemuhookudp", udpmotion);
47 udptouch = std::make_shared<UDPTouchFactory>(udp);
48 Input::RegisterFactory<Input::TouchDevice>("cemuhookudp", udptouch);
44 } 49 }
45 50
46 void Shutdown() { 51 void Shutdown() {
@@ -53,12 +58,17 @@ struct InputSubsystem::Impl {
53#ifdef HAVE_SDL2 58#ifdef HAVE_SDL2
54 sdl.reset(); 59 sdl.reset();
55#endif 60#endif
56 udp.reset();
57 Input::UnregisterFactory<Input::ButtonDevice>("gcpad"); 61 Input::UnregisterFactory<Input::ButtonDevice>("gcpad");
58 Input::UnregisterFactory<Input::AnalogDevice>("gcpad"); 62 Input::UnregisterFactory<Input::AnalogDevice>("gcpad");
59 63
60 gcbuttons.reset(); 64 gcbuttons.reset();
61 gcanalog.reset(); 65 gcanalog.reset();
66
67 Input::UnregisterFactory<Input::MotionDevice>("cemuhookudp");
68 Input::UnregisterFactory<Input::TouchDevice>("cemuhookudp");
69
70 udpmotion.reset();
71 udptouch.reset();
62 } 72 }
63 73
64 [[nodiscard]] std::vector<Common::ParamPackage> GetInputDevices() const { 74 [[nodiscard]] std::vector<Common::ParamPackage> GetInputDevices() const {
@@ -72,6 +82,8 @@ struct InputSubsystem::Impl {
72#endif 82#endif
73 auto udp_devices = udp->GetInputDevices(); 83 auto udp_devices = udp->GetInputDevices();
74 devices.insert(devices.end(), udp_devices.begin(), udp_devices.end()); 84 devices.insert(devices.end(), udp_devices.begin(), udp_devices.end());
85 auto gcpad_devices = gcadapter->GetInputDevices();
86 devices.insert(devices.end(), gcpad_devices.begin(), gcpad_devices.end());
75 return devices; 87 return devices;
76 } 88 }
77 89
@@ -84,6 +96,9 @@ struct InputSubsystem::Impl {
84 // TODO consider returning the SDL key codes for the default keybindings 96 // TODO consider returning the SDL key codes for the default keybindings
85 return {}; 97 return {};
86 } 98 }
99 if (params.Get("class", "") == "gcpad") {
100 return gcadapter->GetAnalogMappingForDevice(params);
101 }
87#ifdef HAVE_SDL2 102#ifdef HAVE_SDL2
88 if (params.Get("class", "") == "sdl") { 103 if (params.Get("class", "") == "sdl") {
89 return sdl->GetAnalogMappingForDevice(params); 104 return sdl->GetAnalogMappingForDevice(params);
@@ -101,6 +116,9 @@ struct InputSubsystem::Impl {
101 // TODO consider returning the SDL key codes for the default keybindings 116 // TODO consider returning the SDL key codes for the default keybindings
102 return {}; 117 return {};
103 } 118 }
119 if (params.Get("class", "") == "gcpad") {
120 return gcadapter->GetButtonMappingForDevice(params);
121 }
104#ifdef HAVE_SDL2 122#ifdef HAVE_SDL2
105 if (params.Get("class", "") == "sdl") { 123 if (params.Get("class", "") == "sdl") {
106 return sdl->GetButtonMappingForDevice(params); 124 return sdl->GetButtonMappingForDevice(params);
@@ -109,14 +127,29 @@ struct InputSubsystem::Impl {
109 return {}; 127 return {};
110 } 128 }
111 129
130 [[nodiscard]] MotionMapping GetMotionMappingForDevice(
131 const Common::ParamPackage& params) const {
132 if (!params.Has("class") || params.Get("class", "") == "any") {
133 return {};
134 }
135 if (params.Get("class", "") == "cemuhookudp") {
136 // TODO return the correct motion device
137 return {};
138 }
139 return {};
140 }
141
112 std::shared_ptr<Keyboard> keyboard; 142 std::shared_ptr<Keyboard> keyboard;
113 std::shared_ptr<MotionEmu> motion_emu; 143 std::shared_ptr<MotionEmu> motion_emu;
114#ifdef HAVE_SDL2 144#ifdef HAVE_SDL2
115 std::unique_ptr<SDL::State> sdl; 145 std::unique_ptr<SDL::State> sdl;
116#endif 146#endif
117 std::unique_ptr<CemuhookUDP::State> udp;
118 std::shared_ptr<GCButtonFactory> gcbuttons; 147 std::shared_ptr<GCButtonFactory> gcbuttons;
119 std::shared_ptr<GCAnalogFactory> gcanalog; 148 std::shared_ptr<GCAnalogFactory> gcanalog;
149 std::shared_ptr<UDPMotionFactory> udpmotion;
150 std::shared_ptr<UDPTouchFactory> udptouch;
151 std::shared_ptr<CemuhookUDP::Client> udp;
152 std::shared_ptr<GCAdapter::Adapter> gcadapter;
120}; 153};
121 154
122InputSubsystem::InputSubsystem() : impl{std::make_unique<Impl>()} {} 155InputSubsystem::InputSubsystem() : impl{std::make_unique<Impl>()} {}
@@ -175,6 +208,22 @@ const GCButtonFactory* InputSubsystem::GetGCButtons() const {
175 return impl->gcbuttons.get(); 208 return impl->gcbuttons.get();
176} 209}
177 210
211UDPMotionFactory* InputSubsystem::GetUDPMotions() {
212 return impl->udpmotion.get();
213}
214
215const UDPMotionFactory* InputSubsystem::GetUDPMotions() const {
216 return impl->udpmotion.get();
217}
218
219UDPTouchFactory* InputSubsystem::GetUDPTouch() {
220 return impl->udptouch.get();
221}
222
223const UDPTouchFactory* InputSubsystem::GetUDPTouch() const {
224 return impl->udptouch.get();
225}
226
178void InputSubsystem::ReloadInputDevices() { 227void InputSubsystem::ReloadInputDevices() {
179 if (!impl->udp) { 228 if (!impl->udp) {
180 return; 229 return;
diff --git a/src/input_common/main.h b/src/input_common/main.h
index f3fbf696e..dded3f1ef 100644
--- a/src/input_common/main.h
+++ b/src/input_common/main.h
@@ -21,10 +21,14 @@ namespace Settings::NativeButton {
21enum Values : int; 21enum Values : int;
22} 22}
23 23
24namespace Settings::NativeMotion {
25enum Values : int;
26}
27
24namespace InputCommon { 28namespace InputCommon {
25namespace Polling { 29namespace Polling {
26 30
27enum class DeviceType { Button, AnalogPreferred }; 31enum class DeviceType { Button, AnalogPreferred, Motion };
28 32
29/** 33/**
30 * A class that can be used to get inputs from an input device like controllers without having to 34 * A class that can be used to get inputs from an input device like controllers without having to
@@ -50,6 +54,8 @@ public:
50 54
51class GCAnalogFactory; 55class GCAnalogFactory;
52class GCButtonFactory; 56class GCButtonFactory;
57class UDPMotionFactory;
58class UDPTouchFactory;
53class Keyboard; 59class Keyboard;
54class MotionEmu; 60class MotionEmu;
55 61
@@ -59,6 +65,7 @@ class MotionEmu;
59 */ 65 */
60using AnalogMapping = std::unordered_map<Settings::NativeAnalog::Values, Common::ParamPackage>; 66using AnalogMapping = std::unordered_map<Settings::NativeAnalog::Values, Common::ParamPackage>;
61using ButtonMapping = std::unordered_map<Settings::NativeButton::Values, Common::ParamPackage>; 67using ButtonMapping = std::unordered_map<Settings::NativeButton::Values, Common::ParamPackage>;
68using MotionMapping = std::unordered_map<Settings::NativeMotion::Values, Common::ParamPackage>;
62 69
63class InputSubsystem { 70class InputSubsystem {
64public: 71public:
@@ -103,6 +110,9 @@ public:
103 /// Retrieves the button mappings for the given device. 110 /// Retrieves the button mappings for the given device.
104 [[nodiscard]] ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& device) const; 111 [[nodiscard]] ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& device) const;
105 112
113 /// Retrieves the motion mappings for the given device.
114 [[nodiscard]] MotionMapping GetMotionMappingForDevice(const Common::ParamPackage& device) const;
115
106 /// Retrieves the underlying GameCube analog handler. 116 /// Retrieves the underlying GameCube analog handler.
107 [[nodiscard]] GCAnalogFactory* GetGCAnalogs(); 117 [[nodiscard]] GCAnalogFactory* GetGCAnalogs();
108 118
@@ -115,6 +125,18 @@ public:
115 /// Retrieves the underlying GameCube button handler. 125 /// Retrieves the underlying GameCube button handler.
116 [[nodiscard]] const GCButtonFactory* GetGCButtons() const; 126 [[nodiscard]] const GCButtonFactory* GetGCButtons() const;
117 127
128 /// Retrieves the underlying udp motion handler.
129 [[nodiscard]] UDPMotionFactory* GetUDPMotions();
130
131 /// Retrieves the underlying udp motion handler.
132 [[nodiscard]] const UDPMotionFactory* GetUDPMotions() const;
133
134 /// Retrieves the underlying udp touch handler.
135 [[nodiscard]] UDPTouchFactory* GetUDPTouch();
136
137 /// Retrieves the underlying udp touch handler.
138 [[nodiscard]] const UDPTouchFactory* GetUDPTouch() const;
139
118 /// Reloads the input devices 140 /// Reloads the input devices
119 void ReloadInputDevices(); 141 void ReloadInputDevices();
120 142
diff --git a/src/input_common/motion_emu.cpp b/src/input_common/motion_emu.cpp
index d4cdf76a3..69fd3c1d2 100644
--- a/src/input_common/motion_emu.cpp
+++ b/src/input_common/motion_emu.cpp
@@ -56,7 +56,7 @@ public:
56 is_tilting = false; 56 is_tilting = false;
57 } 57 }
58 58
59 std::tuple<Common::Vec3<float>, Common::Vec3<float>> GetStatus() { 59 Input::MotionStatus GetStatus() {
60 std::lock_guard guard{status_mutex}; 60 std::lock_guard guard{status_mutex};
61 return status; 61 return status;
62 } 62 }
@@ -76,7 +76,7 @@ private:
76 76
77 Common::Event shutdown_event; 77 Common::Event shutdown_event;
78 78
79 std::tuple<Common::Vec3<float>, Common::Vec3<float>> status; 79 Input::MotionStatus status;
80 std::mutex status_mutex; 80 std::mutex status_mutex;
81 81
82 // Note: always keep the thread declaration at the end so that other objects are initialized 82 // Note: always keep the thread declaration at the end so that other objects are initialized
@@ -113,10 +113,19 @@ private:
113 gravity = QuaternionRotate(inv_q, gravity); 113 gravity = QuaternionRotate(inv_q, gravity);
114 angular_rate = QuaternionRotate(inv_q, angular_rate); 114 angular_rate = QuaternionRotate(inv_q, angular_rate);
115 115
116 // TODO: Calculate the correct rotation vector and orientation matrix
117 const auto matrix4x4 = q.ToMatrix();
118 const auto rotation = Common::MakeVec(0.0f, 0.0f, 0.0f);
119 const std::array orientation{
120 Common::Vec3f(matrix4x4[0], matrix4x4[1], -matrix4x4[2]),
121 Common::Vec3f(matrix4x4[4], matrix4x4[5], -matrix4x4[6]),
122 Common::Vec3f(-matrix4x4[8], -matrix4x4[9], matrix4x4[10]),
123 };
124
116 // Update the sensor state 125 // Update the sensor state
117 { 126 {
118 std::lock_guard guard{status_mutex}; 127 std::lock_guard guard{status_mutex};
119 status = std::make_tuple(gravity, angular_rate); 128 status = std::make_tuple(gravity, angular_rate, rotation, orientation);
120 } 129 }
121 } 130 }
122 } 131 }
@@ -131,7 +140,7 @@ public:
131 device = std::make_shared<MotionEmuDevice>(update_millisecond, sensitivity); 140 device = std::make_shared<MotionEmuDevice>(update_millisecond, sensitivity);
132 } 141 }
133 142
134 std::tuple<Common::Vec3<float>, Common::Vec3<float>> GetStatus() const override { 143 Input::MotionStatus GetStatus() const override {
135 return device->GetStatus(); 144 return device->GetStatus();
136 } 145 }
137 146
diff --git a/src/input_common/sdl/sdl_impl.cpp b/src/input_common/sdl/sdl_impl.cpp
index a9e676f4b..27a96c18b 100644
--- a/src/input_common/sdl/sdl_impl.cpp
+++ b/src/input_common/sdl/sdl_impl.cpp
@@ -5,6 +5,7 @@
5#include <algorithm> 5#include <algorithm>
6#include <array> 6#include <array>
7#include <atomic> 7#include <atomic>
8#include <chrono>
8#include <cmath> 9#include <cmath>
9#include <functional> 10#include <functional>
10#include <mutex> 11#include <mutex>
@@ -78,6 +79,33 @@ public:
78 return state.axes.at(axis) / (32767.0f * range); 79 return state.axes.at(axis) / (32767.0f * range);
79 } 80 }
80 81
82 bool RumblePlay(f32 amp_low, f32 amp_high, int time) {
83 const u16 raw_amp_low = static_cast<u16>(amp_low * 0xFFFF);
84 const u16 raw_amp_high = static_cast<u16>(amp_high * 0xFFFF);
85 // Lower drastically the number of state changes
86 if (raw_amp_low >> 11 == last_state_rumble_low >> 11 &&
87 raw_amp_high >> 11 == last_state_rumble_high >> 11) {
88 if (raw_amp_low + raw_amp_high != 0 ||
89 last_state_rumble_low + last_state_rumble_high == 0) {
90 return false;
91 }
92 }
93 // Don't change state if last vibration was < 20ms
94 const auto now = std::chrono::system_clock::now();
95 if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_vibration) <
96 std::chrono::milliseconds(20)) {
97 return raw_amp_low + raw_amp_high == 0;
98 }
99
100 last_vibration = now;
101 last_state_rumble_low = raw_amp_low;
102 last_state_rumble_high = raw_amp_high;
103 if (sdl_joystick) {
104 SDL_JoystickRumble(sdl_joystick.get(), raw_amp_low, raw_amp_high, time);
105 }
106 return false;
107 }
108
81 std::tuple<float, float> GetAnalog(int axis_x, int axis_y, float range) const { 109 std::tuple<float, float> GetAnalog(int axis_x, int axis_y, float range) const {
82 float x = GetAxis(axis_x, range); 110 float x = GetAxis(axis_x, range);
83 float y = GetAxis(axis_y, range); 111 float y = GetAxis(axis_y, range);
@@ -139,6 +167,9 @@ private:
139 } state; 167 } state;
140 std::string guid; 168 std::string guid;
141 int port; 169 int port;
170 u16 last_state_rumble_high;
171 u16 last_state_rumble_low;
172 std::chrono::time_point<std::chrono::system_clock> last_vibration;
142 std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)> sdl_joystick; 173 std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)> sdl_joystick;
143 std::unique_ptr<SDL_GameController, decltype(&SDL_GameControllerClose)> sdl_controller; 174 std::unique_ptr<SDL_GameController, decltype(&SDL_GameControllerClose)> sdl_controller;
144 mutable std::mutex mutex; 175 mutable std::mutex mutex;
@@ -207,7 +238,7 @@ void SDLState::InitJoystick(int joystick_index) {
207 sdl_gamecontroller = SDL_GameControllerOpen(joystick_index); 238 sdl_gamecontroller = SDL_GameControllerOpen(joystick_index);
208 } 239 }
209 if (!sdl_joystick) { 240 if (!sdl_joystick) {
210 LOG_ERROR(Input, "failed to open joystick {}", joystick_index); 241 LOG_ERROR(Input, "Failed to open joystick {}", joystick_index);
211 return; 242 return;
212 } 243 }
213 const std::string guid = GetGUID(sdl_joystick); 244 const std::string guid = GetGUID(sdl_joystick);
@@ -303,6 +334,12 @@ public:
303 return joystick->GetButton(button); 334 return joystick->GetButton(button);
304 } 335 }
305 336
337 bool SetRumblePlay(f32 amp_high, f32 amp_low, f32 freq_high, f32 freq_low) const override {
338 const f32 new_amp_low = pow(amp_low, 0.5f) * (3.0f - 2.0f * pow(amp_low, 0.15f));
339 const f32 new_amp_high = pow(amp_high, 0.5f) * (3.0f - 2.0f * pow(amp_high, 0.15f));
340 return joystick->RumblePlay(new_amp_low, new_amp_high, 250);
341 }
342
306private: 343private:
307 std::shared_ptr<SDLJoystick> joystick; 344 std::shared_ptr<SDLJoystick> joystick;
308 int button; 345 int button;
diff --git a/src/input_common/settings.cpp b/src/input_common/settings.cpp
index 80c719cf4..b66c05856 100644
--- a/src/input_common/settings.cpp
+++ b/src/input_common/settings.cpp
@@ -14,6 +14,13 @@ const std::array<const char*, NumButtons> mapping = {{
14}}; 14}};
15} 15}
16 16
17namespace NativeMotion {
18const std::array<const char*, NumMotions> mapping = {{
19 "motionleft",
20 "motionright",
21}};
22}
23
17namespace NativeAnalog { 24namespace NativeAnalog {
18const std::array<const char*, NumAnalogs> mapping = {{ 25const std::array<const char*, NumAnalogs> mapping = {{
19 "lstick", 26 "lstick",
diff --git a/src/input_common/settings.h b/src/input_common/settings.h
index 2d258960b..ab0b95cf1 100644
--- a/src/input_common/settings.h
+++ b/src/input_common/settings.h
@@ -66,6 +66,21 @@ constexpr int NUM_STICKS_HID = NumAnalogs;
66extern const std::array<const char*, NumAnalogs> mapping; 66extern const std::array<const char*, NumAnalogs> mapping;
67} // namespace NativeAnalog 67} // namespace NativeAnalog
68 68
69namespace NativeMotion {
70enum Values : int {
71 MOTIONLEFT,
72 MOTIONRIGHT,
73
74 NumMotions,
75};
76
77constexpr int MOTION_HID_BEGIN = MOTIONLEFT;
78constexpr int MOTION_HID_END = NumMotions;
79constexpr int NUM_MOTION_HID = NumMotions;
80
81extern const std::array<const char*, NumMotions> mapping;
82} // namespace NativeMotion
83
69namespace NativeMouseButton { 84namespace NativeMouseButton {
70enum Values { 85enum Values {
71 Left, 86 Left,
@@ -292,6 +307,7 @@ constexpr int NUM_KEYBOARD_MODS_HID = NumKeyboardMods;
292 307
293using ButtonsRaw = std::array<std::string, NativeButton::NumButtons>; 308using ButtonsRaw = std::array<std::string, NativeButton::NumButtons>;
294using AnalogsRaw = std::array<std::string, NativeAnalog::NumAnalogs>; 309using AnalogsRaw = std::array<std::string, NativeAnalog::NumAnalogs>;
310using MotionRaw = std::array<std::string, NativeMotion::NumMotions>;
295using MouseButtonsRaw = std::array<std::string, NativeMouseButton::NumMouseButtons>; 311using MouseButtonsRaw = std::array<std::string, NativeMouseButton::NumMouseButtons>;
296using KeyboardKeysRaw = std::array<std::string, NativeKeyboard::NumKeyboardKeys>; 312using KeyboardKeysRaw = std::array<std::string, NativeKeyboard::NumKeyboardKeys>;
297using KeyboardModsRaw = std::array<std::string, NativeKeyboard::NumKeyboardMods>; 313using KeyboardModsRaw = std::array<std::string, NativeKeyboard::NumKeyboardMods>;
@@ -314,6 +330,7 @@ struct PlayerInput {
314 ControllerType controller_type; 330 ControllerType controller_type;
315 ButtonsRaw buttons; 331 ButtonsRaw buttons;
316 AnalogsRaw analogs; 332 AnalogsRaw analogs;
333 MotionRaw motions;
317 std::string lstick_mod; 334 std::string lstick_mod;
318 std::string rstick_mod; 335 std::string rstick_mod;
319 336
diff --git a/src/input_common/udp/client.cpp b/src/input_common/udp/client.cpp
index 3f4eaf448..2b6a68d4b 100644
--- a/src/input_common/udp/client.cpp
+++ b/src/input_common/udp/client.cpp
@@ -2,14 +2,13 @@
2// Licensed under GPLv2 or any later version 2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <algorithm>
6#include <array>
7#include <chrono> 5#include <chrono>
8#include <cstring> 6#include <cstring>
9#include <functional> 7#include <functional>
10#include <thread> 8#include <thread>
11#include <boost/asio.hpp> 9#include <boost/asio.hpp>
12#include "common/logging/log.h" 10#include "common/logging/log.h"
11#include "core/settings.h"
13#include "input_common/udp/client.h" 12#include "input_common/udp/client.h"
14#include "input_common/udp/protocol.h" 13#include "input_common/udp/protocol.h"
15 14
@@ -131,21 +130,59 @@ static void SocketLoop(Socket* socket) {
131 socket->Loop(); 130 socket->Loop();
132} 131}
133 132
134Client::Client(std::shared_ptr<DeviceStatus> status, const std::string& host, u16 port, 133Client::Client() {
135 u8 pad_index, u32 client_id) 134 LOG_INFO(Input, "Udp Initialization started");
136 : status(std::move(status)) { 135 for (std::size_t client = 0; client < clients.size(); client++) {
137 StartCommunication(host, port, pad_index, client_id); 136 u8 pad = client % 4;
137 StartCommunication(client, Settings::values.udp_input_address,
138 Settings::values.udp_input_port, pad, 24872);
139 // Set motion parameters
140 // SetGyroThreshold value should be dependent on GyroscopeZeroDriftMode
141 // Real HW values are unknown, 0.0001 is an approximate to Standard
142 clients[client].motion.SetGyroThreshold(0.0001f);
143 }
138} 144}
139 145
140Client::~Client() { 146Client::~Client() {
141 socket->Stop(); 147 Reset();
142 thread.join(); 148}
149
150std::vector<Common::ParamPackage> Client::GetInputDevices() const {
151 std::vector<Common::ParamPackage> devices;
152 for (std::size_t client = 0; client < clients.size(); client++) {
153 if (!DeviceConnected(client)) {
154 continue;
155 }
156 std::string name = fmt::format("UDP Controller {}", client);
157 devices.emplace_back(Common::ParamPackage{
158 {"class", "cemuhookudp"},
159 {"display", std::move(name)},
160 {"port", std::to_string(client)},
161 });
162 }
163 return devices;
143} 164}
144 165
166bool Client::DeviceConnected(std::size_t pad) const {
167 // Use last timestamp to detect if the socket has stopped sending data
168 const auto now = std::chrono::system_clock::now();
169 u64 time_difference =
170 std::chrono::duration_cast<std::chrono::milliseconds>(now - clients[pad].last_motion_update)
171 .count();
172 return time_difference < 1000 && clients[pad].active == 1;
173}
174
175void Client::ReloadUDPClient() {
176 for (std::size_t client = 0; client < clients.size(); client++) {
177 ReloadSocket(Settings::values.udp_input_address, Settings::values.udp_input_port, client);
178 }
179}
145void Client::ReloadSocket(const std::string& host, u16 port, u8 pad_index, u32 client_id) { 180void Client::ReloadSocket(const std::string& host, u16 port, u8 pad_index, u32 client_id) {
146 socket->Stop(); 181 // client number must be determined from host / port and pad index
147 thread.join(); 182 std::size_t client = pad_index;
148 StartCommunication(host, port, pad_index, client_id); 183 clients[client].socket->Stop();
184 clients[client].thread.join();
185 StartCommunication(client, host, port, pad_index, client_id);
149} 186}
150 187
151void Client::OnVersion(Response::Version data) { 188void Client::OnVersion(Response::Version data) {
@@ -157,23 +194,39 @@ void Client::OnPortInfo(Response::PortInfo data) {
157} 194}
158 195
159void Client::OnPadData(Response::PadData data) { 196void Client::OnPadData(Response::PadData data) {
197 // client number must be determined from host / port and pad index
198 std::size_t client = data.info.id;
160 LOG_TRACE(Input, "PadData packet received"); 199 LOG_TRACE(Input, "PadData packet received");
161 if (data.packet_counter <= packet_sequence) { 200 if (data.packet_counter == clients[client].packet_sequence) {
162 LOG_WARNING( 201 LOG_WARNING(
163 Input, 202 Input,
164 "PadData packet dropped because its stale info. Current count: {} Packet count: {}", 203 "PadData packet dropped because its stale info. Current count: {} Packet count: {}",
165 packet_sequence, data.packet_counter); 204 clients[client].packet_sequence, data.packet_counter);
166 return; 205 return;
167 } 206 }
168 packet_sequence = data.packet_counter; 207 clients[client].active = data.info.is_pad_active;
169 // TODO: Check how the Switch handles motions and how the CemuhookUDP motion 208 clients[client].packet_sequence = data.packet_counter;
170 // directions correspond to the ones of the Switch 209 const auto now = std::chrono::system_clock::now();
171 Common::Vec3f accel = Common::MakeVec<float>(data.accel.x, data.accel.y, data.accel.z); 210 u64 time_difference = std::chrono::duration_cast<std::chrono::microseconds>(
172 Common::Vec3f gyro = Common::MakeVec<float>(data.gyro.pitch, data.gyro.yaw, data.gyro.roll); 211 now - clients[client].last_motion_update)
173 { 212 .count();
174 std::lock_guard guard(status->update_mutex); 213 clients[client].last_motion_update = now;
214 Common::Vec3f raw_gyroscope = {data.gyro.pitch, data.gyro.roll, -data.gyro.yaw};
215 clients[client].motion.SetAcceleration({data.accel.x, -data.accel.z, data.accel.y});
216 // Gyroscope values are not it the correct scale from better joy.
217 // Dividing by 312 allows us to make one full turn = 1 turn
218 // This must be a configurable valued called sensitivity
219 clients[client].motion.SetGyroscope(raw_gyroscope / 312.0f);
220 clients[client].motion.UpdateRotation(time_difference);
221 clients[client].motion.UpdateOrientation(time_difference);
222 Common::Vec3f gyroscope = clients[client].motion.GetGyroscope();
223 Common::Vec3f accelerometer = clients[client].motion.GetAcceleration();
224 Common::Vec3f rotation = clients[client].motion.GetRotations();
225 std::array<Common::Vec3f, 3> orientation = clients[client].motion.GetOrientation();
175 226
176 status->motion_status = {accel, gyro}; 227 {
228 std::lock_guard guard(clients[client].status.update_mutex);
229 clients[client].status.motion_status = {accelerometer, gyroscope, rotation, orientation};
177 230
178 // TODO: add a setting for "click" touch. Click touch refers to a device that differentiates 231 // TODO: add a setting for "click" touch. Click touch refers to a device that differentiates
179 // between a simple "tap" and a hard press that causes the touch screen to click. 232 // between a simple "tap" and a hard press that causes the touch screen to click.
@@ -182,11 +235,11 @@ void Client::OnPadData(Response::PadData data) {
182 float x = 0; 235 float x = 0;
183 float y = 0; 236 float y = 0;
184 237
185 if (is_active && status->touch_calibration) { 238 if (is_active && clients[client].status.touch_calibration) {
186 const u16 min_x = status->touch_calibration->min_x; 239 const u16 min_x = clients[client].status.touch_calibration->min_x;
187 const u16 max_x = status->touch_calibration->max_x; 240 const u16 max_x = clients[client].status.touch_calibration->max_x;
188 const u16 min_y = status->touch_calibration->min_y; 241 const u16 min_y = clients[client].status.touch_calibration->min_y;
189 const u16 max_y = status->touch_calibration->max_y; 242 const u16 max_y = clients[client].status.touch_calibration->max_y;
190 243
191 x = (std::clamp(static_cast<u16>(data.touch_1.x), min_x, max_x) - min_x) / 244 x = (std::clamp(static_cast<u16>(data.touch_1.x), min_x, max_x) - min_x) /
192 static_cast<float>(max_x - min_x); 245 static_cast<float>(max_x - min_x);
@@ -194,17 +247,80 @@ void Client::OnPadData(Response::PadData data) {
194 static_cast<float>(max_y - min_y); 247 static_cast<float>(max_y - min_y);
195 } 248 }
196 249
197 status->touch_status = {x, y, is_active}; 250 clients[client].status.touch_status = {x, y, is_active};
251
252 if (configuring) {
253 UpdateYuzuSettings(client, accelerometer, gyroscope, is_active);
254 }
198 } 255 }
199} 256}
200 257
201void Client::StartCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id) { 258void Client::StartCommunication(std::size_t client, const std::string& host, u16 port, u8 pad_index,
259 u32 client_id) {
202 SocketCallback callback{[this](Response::Version version) { OnVersion(version); }, 260 SocketCallback callback{[this](Response::Version version) { OnVersion(version); },
203 [this](Response::PortInfo info) { OnPortInfo(info); }, 261 [this](Response::PortInfo info) { OnPortInfo(info); },
204 [this](Response::PadData data) { OnPadData(data); }}; 262 [this](Response::PadData data) { OnPadData(data); }};
205 LOG_INFO(Input, "Starting communication with UDP input server on {}:{}", host, port); 263 LOG_INFO(Input, "Starting communication with UDP input server on {}:{}", host, port);
206 socket = std::make_unique<Socket>(host, port, pad_index, client_id, callback); 264 clients[client].socket = std::make_unique<Socket>(host, port, pad_index, client_id, callback);
207 thread = std::thread{SocketLoop, this->socket.get()}; 265 clients[client].thread = std::thread{SocketLoop, clients[client].socket.get()};
266}
267
268void Client::Reset() {
269 for (std::size_t client = 0; client < clients.size(); client++) {
270 clients[client].socket->Stop();
271 clients[client].thread.join();
272 }
273}
274
275void Client::UpdateYuzuSettings(std::size_t client, const Common::Vec3<float>& acc,
276 const Common::Vec3<float>& gyro, bool touch) {
277 UDPPadStatus pad;
278 if (touch) {
279 pad.touch = PadTouch::Click;
280 pad_queue[client].Push(pad);
281 }
282 for (size_t i = 0; i < 3; ++i) {
283 if (gyro[i] > 6.0f || gyro[i] < -6.0f) {
284 pad.motion = static_cast<PadMotion>(i);
285 pad.motion_value = gyro[i];
286 pad_queue[client].Push(pad);
287 }
288 if (acc[i] > 2.0f || acc[i] < -2.0f) {
289 pad.motion = static_cast<PadMotion>(i + 3);
290 pad.motion_value = acc[i];
291 pad_queue[client].Push(pad);
292 }
293 }
294}
295
296void Client::BeginConfiguration() {
297 for (auto& pq : pad_queue) {
298 pq.Clear();
299 }
300 configuring = true;
301}
302
303void Client::EndConfiguration() {
304 for (auto& pq : pad_queue) {
305 pq.Clear();
306 }
307 configuring = false;
308}
309
310DeviceStatus& Client::GetPadState(std::size_t pad) {
311 return clients[pad].status;
312}
313
314const DeviceStatus& Client::GetPadState(std::size_t pad) const {
315 return clients[pad].status;
316}
317
318std::array<Common::SPSCQueue<UDPPadStatus>, 4>& Client::GetPadQueue() {
319 return pad_queue;
320}
321
322const std::array<Common::SPSCQueue<UDPPadStatus>, 4>& Client::GetPadQueue() const {
323 return pad_queue;
208} 324}
209 325
210void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id, 326void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id,
diff --git a/src/input_common/udp/client.h b/src/input_common/udp/client.h
index b8c654755..523dc6a7a 100644
--- a/src/input_common/udp/client.h
+++ b/src/input_common/udp/client.h
@@ -12,8 +12,12 @@
12#include <thread> 12#include <thread>
13#include <tuple> 13#include <tuple>
14#include "common/common_types.h" 14#include "common/common_types.h"
15#include "common/param_package.h"
15#include "common/thread.h" 16#include "common/thread.h"
17#include "common/threadsafe_queue.h"
16#include "common/vector_math.h" 18#include "common/vector_math.h"
19#include "core/frontend/input.h"
20#include "input_common/motion_input.h"
17 21
18namespace InputCommon::CemuhookUDP { 22namespace InputCommon::CemuhookUDP {
19 23
@@ -28,9 +32,30 @@ struct PortInfo;
28struct Version; 32struct Version;
29} // namespace Response 33} // namespace Response
30 34
35enum class PadMotion {
36 GyroX,
37 GyroY,
38 GyroZ,
39 AccX,
40 AccY,
41 AccZ,
42 Undefined,
43};
44
45enum class PadTouch {
46 Click,
47 Undefined,
48};
49
50struct UDPPadStatus {
51 PadTouch touch{PadTouch::Undefined};
52 PadMotion motion{PadMotion::Undefined};
53 f32 motion_value{0.0f};
54};
55
31struct DeviceStatus { 56struct DeviceStatus {
32 std::mutex update_mutex; 57 std::mutex update_mutex;
33 std::tuple<Common::Vec3<float>, Common::Vec3<float>> motion_status; 58 Input::MotionStatus motion_status;
34 std::tuple<float, float, bool> touch_status; 59 std::tuple<float, float, bool> touch_status;
35 60
36 // calibration data for scaling the device's touch area to 3ds 61 // calibration data for scaling the device's touch area to 3ds
@@ -45,22 +70,58 @@ struct DeviceStatus {
45 70
46class Client { 71class Client {
47public: 72public:
48 explicit Client(std::shared_ptr<DeviceStatus> status, const std::string& host = DEFAULT_ADDR, 73 // Initialize the UDP client capture and read sequence
49 u16 port = DEFAULT_PORT, u8 pad_index = 0, u32 client_id = 24872); 74 Client();
75
76 // Close and release the client
50 ~Client(); 77 ~Client();
78
79 // Used for polling
80 void BeginConfiguration();
81 void EndConfiguration();
82
83 std::vector<Common::ParamPackage> GetInputDevices() const;
84
85 bool DeviceConnected(std::size_t pad) const;
86 void ReloadUDPClient();
51 void ReloadSocket(const std::string& host = "127.0.0.1", u16 port = 26760, u8 pad_index = 0, 87 void ReloadSocket(const std::string& host = "127.0.0.1", u16 port = 26760, u8 pad_index = 0,
52 u32 client_id = 24872); 88 u32 client_id = 24872);
53 89
90 std::array<Common::SPSCQueue<UDPPadStatus>, 4>& GetPadQueue();
91 const std::array<Common::SPSCQueue<UDPPadStatus>, 4>& GetPadQueue() const;
92
93 DeviceStatus& GetPadState(std::size_t pad);
94 const DeviceStatus& GetPadState(std::size_t pad) const;
95
54private: 96private:
97 struct ClientData {
98 std::unique_ptr<Socket> socket;
99 DeviceStatus status;
100 std::thread thread;
101 u64 packet_sequence = 0;
102 u8 active;
103
104 // Realtime values
105 // motion is initalized with PID values for drift correction on joycons
106 InputCommon::MotionInput motion{0.3f, 0.005f, 0.0f};
107 std::chrono::time_point<std::chrono::system_clock> last_motion_update;
108 };
109
110 // For shutting down, clear all data, join all threads, release usb
111 void Reset();
112
55 void OnVersion(Response::Version); 113 void OnVersion(Response::Version);
56 void OnPortInfo(Response::PortInfo); 114 void OnPortInfo(Response::PortInfo);
57 void OnPadData(Response::PadData); 115 void OnPadData(Response::PadData);
58 void StartCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id); 116 void StartCommunication(std::size_t client, const std::string& host, u16 port, u8 pad_index,
117 u32 client_id);
118 void UpdateYuzuSettings(std::size_t client, const Common::Vec3<float>& acc,
119 const Common::Vec3<float>& gyro, bool touch);
120
121 bool configuring = false;
59 122
60 std::unique_ptr<Socket> socket; 123 std::array<ClientData, 4> clients;
61 std::shared_ptr<DeviceStatus> status; 124 std::array<Common::SPSCQueue<UDPPadStatus>, 4> pad_queue;
62 std::thread thread;
63 u64 packet_sequence = 0;
64}; 125};
65 126
66/// An async job allowing configuration of the touchpad calibration. 127/// An async job allowing configuration of the touchpad calibration.
diff --git a/src/input_common/udp/udp.cpp b/src/input_common/udp/udp.cpp
index 4b347e47e..eba077a36 100644
--- a/src/input_common/udp/udp.cpp
+++ b/src/input_common/udp/udp.cpp
@@ -1,105 +1,144 @@
1// Copyright 2018 Citra Emulator Project 1// Copyright 2020 yuzu Emulator Project
2// Licensed under GPLv2 or any later version 2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <atomic>
6#include <list>
5#include <mutex> 7#include <mutex>
6#include <optional> 8#include <utility>
7#include <tuple> 9#include "common/assert.h"
8 10#include "common/threadsafe_queue.h"
9#include "common/param_package.h"
10#include "core/frontend/input.h"
11#include "core/settings.h"
12#include "input_common/udp/client.h" 11#include "input_common/udp/client.h"
13#include "input_common/udp/udp.h" 12#include "input_common/udp/udp.h"
14 13
15namespace InputCommon::CemuhookUDP { 14namespace InputCommon {
16 15
17class UDPTouchDevice final : public Input::TouchDevice { 16class UDPMotion final : public Input::MotionDevice {
18public: 17public:
19 explicit UDPTouchDevice(std::shared_ptr<DeviceStatus> status_) : status(std::move(status_)) {} 18 UDPMotion(std::string ip_, int port_, int pad_, CemuhookUDP::Client* client_)
20 std::tuple<float, float, bool> GetStatus() const override { 19 : ip(ip_), port(port_), pad(pad_), client(client_) {}
21 std::lock_guard guard(status->update_mutex); 20
22 return status->touch_status; 21 Input::MotionStatus GetStatus() const override {
22 return client->GetPadState(pad).motion_status;
23 } 23 }
24 24
25private: 25private:
26 std::shared_ptr<DeviceStatus> status; 26 const std::string ip;
27 const int port;
28 const int pad;
29 CemuhookUDP::Client* client;
30 mutable std::mutex mutex;
27}; 31};
28 32
29class UDPMotionDevice final : public Input::MotionDevice { 33/// A motion device factory that creates motion devices from JC Adapter
30public: 34UDPMotionFactory::UDPMotionFactory(std::shared_ptr<CemuhookUDP::Client> client_)
31 explicit UDPMotionDevice(std::shared_ptr<DeviceStatus> status_) : status(std::move(status_)) {} 35 : client(std::move(client_)) {}
32 std::tuple<Common::Vec3<float>, Common::Vec3<float>> GetStatus() const override { 36
33 std::lock_guard guard(status->update_mutex); 37/**
34 return status->motion_status; 38 * Creates motion device
35 } 39 * @param params contains parameters for creating the device:
40 * - "port": the nth jcpad on the adapter
41 */
42std::unique_ptr<Input::MotionDevice> UDPMotionFactory::Create(const Common::ParamPackage& params) {
43 const std::string ip = params.Get("ip", "127.0.0.1");
44 const int port = params.Get("port", 26760);
45 const int pad = params.Get("pad_index", 0);
46
47 return std::make_unique<UDPMotion>(ip, port, pad, client.get());
48}
36 49
37private: 50void UDPMotionFactory::BeginConfiguration() {
38 std::shared_ptr<DeviceStatus> status; 51 polling = true;
39}; 52 client->BeginConfiguration();
53}
40 54
41class UDPTouchFactory final : public Input::Factory<Input::TouchDevice> { 55void UDPMotionFactory::EndConfiguration() {
42public: 56 polling = false;
43 explicit UDPTouchFactory(std::shared_ptr<DeviceStatus> status_) : status(std::move(status_)) {} 57 client->EndConfiguration();
44 58}
45 std::unique_ptr<Input::TouchDevice> Create(const Common::ParamPackage& params) override { 59
46 { 60Common::ParamPackage UDPMotionFactory::GetNextInput() {
47 std::lock_guard guard(status->update_mutex); 61 Common::ParamPackage params;
48 status->touch_calibration = DeviceStatus::CalibrationData{}; 62 CemuhookUDP::UDPPadStatus pad;
49 // These default values work well for DS4 but probably not other touch inputs 63 auto& queue = client->GetPadQueue();
50 status->touch_calibration->min_x = params.Get("min_x", 100); 64 for (std::size_t pad_number = 0; pad_number < queue.size(); ++pad_number) {
51 status->touch_calibration->min_y = params.Get("min_y", 50); 65 while (queue[pad_number].Pop(pad)) {
52 status->touch_calibration->max_x = params.Get("max_x", 1800); 66 if (pad.motion == CemuhookUDP::PadMotion::Undefined || std::abs(pad.motion_value) < 1) {
53 status->touch_calibration->max_y = params.Get("max_y", 850); 67 continue;
68 }
69 params.Set("engine", "cemuhookudp");
70 params.Set("ip", "127.0.0.1");
71 params.Set("port", 26760);
72 params.Set("pad_index", static_cast<int>(pad_number));
73 params.Set("motion", static_cast<u16>(pad.motion));
74 return params;
54 } 75 }
55 return std::make_unique<UDPTouchDevice>(status);
56 } 76 }
77 return params;
78}
57 79
58private: 80class UDPTouch final : public Input::TouchDevice {
59 std::shared_ptr<DeviceStatus> status;
60};
61
62class UDPMotionFactory final : public Input::Factory<Input::MotionDevice> {
63public: 81public:
64 explicit UDPMotionFactory(std::shared_ptr<DeviceStatus> status_) : status(std::move(status_)) {} 82 UDPTouch(std::string ip_, int port_, int pad_, CemuhookUDP::Client* client_)
83 : ip(std::move(ip_)), port(port_), pad(pad_), client(client_) {}
65 84
66 std::unique_ptr<Input::MotionDevice> Create(const Common::ParamPackage& params) override { 85 std::tuple<float, float, bool> GetStatus() const override {
67 return std::make_unique<UDPMotionDevice>(status); 86 return client->GetPadState(pad).touch_status;
68 } 87 }
69 88
70private: 89private:
71 std::shared_ptr<DeviceStatus> status; 90 const std::string ip;
91 const int port;
92 const int pad;
93 CemuhookUDP::Client* client;
94 mutable std::mutex mutex;
72}; 95};
73 96
74State::State() { 97/// A motion device factory that creates motion devices from JC Adapter
75 auto status = std::make_shared<DeviceStatus>(); 98UDPTouchFactory::UDPTouchFactory(std::shared_ptr<CemuhookUDP::Client> client_)
76 client = 99 : client(std::move(client_)) {}
77 std::make_unique<Client>(status, Settings::values.udp_input_address, 100
78 Settings::values.udp_input_port, Settings::values.udp_pad_index); 101/**
79 102 * Creates motion device
80 motion_factory = std::make_shared<UDPMotionFactory>(status); 103 * @param params contains parameters for creating the device:
81 touch_factory = std::make_shared<UDPTouchFactory>(status); 104 * - "port": the nth jcpad on the adapter
82 105 */
83 Input::RegisterFactory<Input::MotionDevice>("cemuhookudp", motion_factory); 106std::unique_ptr<Input::TouchDevice> UDPTouchFactory::Create(const Common::ParamPackage& params) {
84 Input::RegisterFactory<Input::TouchDevice>("cemuhookudp", touch_factory); 107 const std::string ip = params.Get("ip", "127.0.0.1");
108 const int port = params.Get("port", 26760);
109 const int pad = params.Get("pad_index", 0);
110
111 return std::make_unique<UDPTouch>(ip, port, pad, client.get());
85} 112}
86 113
87State::~State() { 114void UDPTouchFactory::BeginConfiguration() {
88 Input::UnregisterFactory<Input::TouchDevice>("cemuhookudp"); 115 polling = true;
89 Input::UnregisterFactory<Input::MotionDevice>("cemuhookudp"); 116 client->BeginConfiguration();
90} 117}
91 118
92std::vector<Common::ParamPackage> State::GetInputDevices() const { 119void UDPTouchFactory::EndConfiguration() {
93 // TODO support binding udp devices 120 polling = false;
94 return {}; 121 client->EndConfiguration();
95} 122}
96 123
97void State::ReloadUDPClient() { 124Common::ParamPackage UDPTouchFactory::GetNextInput() {
98 client->ReloadSocket(Settings::values.udp_input_address, Settings::values.udp_input_port, 125 Common::ParamPackage params;
99 Settings::values.udp_pad_index); 126 CemuhookUDP::UDPPadStatus pad;
127 auto& queue = client->GetPadQueue();
128 for (std::size_t pad_number = 0; pad_number < queue.size(); ++pad_number) {
129 while (queue[pad_number].Pop(pad)) {
130 if (pad.touch == CemuhookUDP::PadTouch::Undefined) {
131 continue;
132 }
133 params.Set("engine", "cemuhookudp");
134 params.Set("ip", "127.0.0.1");
135 params.Set("port", 26760);
136 params.Set("pad_index", static_cast<int>(pad_number));
137 params.Set("touch", static_cast<u16>(pad.touch));
138 return params;
139 }
140 }
141 return params;
100} 142}
101 143
102std::unique_ptr<State> Init() { 144} // namespace InputCommon
103 return std::make_unique<State>();
104}
105} // namespace InputCommon::CemuhookUDP
diff --git a/src/input_common/udp/udp.h b/src/input_common/udp/udp.h
index 672a5c812..ea3fd4175 100644
--- a/src/input_common/udp/udp.h
+++ b/src/input_common/udp/udp.h
@@ -1,32 +1,57 @@
1// Copyright 2018 Citra Emulator Project 1// Copyright 2020 yuzu Emulator Project
2// Licensed under GPLv2 or any later version 2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#pragma once 5#pragma once
6 6
7#include <memory> 7#include <memory>
8#include <vector> 8#include "core/frontend/input.h"
9#include "common/param_package.h" 9#include "input_common/udp/client.h"
10 10
11namespace InputCommon::CemuhookUDP { 11namespace InputCommon {
12 12
13class Client; 13/// A motion device factory that creates motion devices from udp clients
14class UDPMotionFactory; 14class UDPMotionFactory final : public Input::Factory<Input::MotionDevice> {
15class UDPTouchFactory;
16
17class State {
18public: 15public:
19 State(); 16 explicit UDPMotionFactory(std::shared_ptr<CemuhookUDP::Client> client_);
20 ~State(); 17
21 void ReloadUDPClient(); 18 std::unique_ptr<Input::MotionDevice> Create(const Common::ParamPackage& params) override;
22 std::vector<Common::ParamPackage> GetInputDevices() const; 19
20 Common::ParamPackage GetNextInput();
21
22 /// For device input configuration/polling
23 void BeginConfiguration();
24 void EndConfiguration();
25
26 bool IsPolling() const {
27 return polling;
28 }
23 29
24private: 30private:
25 std::unique_ptr<Client> client; 31 std::shared_ptr<CemuhookUDP::Client> client;
26 std::shared_ptr<UDPMotionFactory> motion_factory; 32 bool polling = false;
27 std::shared_ptr<UDPTouchFactory> touch_factory;
28}; 33};
29 34
30std::unique_ptr<State> Init(); 35/// A touch device factory that creates touch devices from udp clients
36class UDPTouchFactory final : public Input::Factory<Input::TouchDevice> {
37public:
38 explicit UDPTouchFactory(std::shared_ptr<CemuhookUDP::Client> client_);
39
40 std::unique_ptr<Input::TouchDevice> Create(const Common::ParamPackage& params) override;
41
42 Common::ParamPackage GetNextInput();
43
44 /// For device input configuration/polling
45 void BeginConfiguration();
46 void EndConfiguration();
47
48 bool IsPolling() const {
49 return polling;
50 }
51
52private:
53 std::shared_ptr<CemuhookUDP::Client> client;
54 bool polling = false;
55};
31 56
32} // namespace InputCommon::CemuhookUDP 57} // namespace InputCommon