summaryrefslogtreecommitdiff
path: root/src/input_common/gcadapter
diff options
context:
space:
mode:
Diffstat (limited to 'src/input_common/gcadapter')
-rw-r--r--src/input_common/gcadapter/gc_adapter.cpp398
-rw-r--r--src/input_common/gcadapter/gc_adapter.h161
-rw-r--r--src/input_common/gcadapter/gc_poller.cpp272
-rw-r--r--src/input_common/gcadapter/gc_poller.h67
4 files changed, 898 insertions, 0 deletions
diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp
new file mode 100644
index 000000000..6d9f4d9eb
--- /dev/null
+++ b/src/input_common/gcadapter/gc_adapter.cpp
@@ -0,0 +1,398 @@
1// Copyright 2014 Dolphin Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#include <chrono>
6#include <thread>
7#include "common/logging/log.h"
8#include "input_common/gcadapter/gc_adapter.h"
9
10namespace GCAdapter {
11
12/// Used to loop through and assign button in poller
13constexpr std::array<PadButton, 12> PadButtonArray{
14 PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, PadButton::PAD_BUTTON_DOWN,
15 PadButton::PAD_BUTTON_UP, PadButton::PAD_TRIGGER_Z, PadButton::PAD_TRIGGER_R,
16 PadButton::PAD_TRIGGER_L, PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B,
17 PadButton::PAD_BUTTON_X, PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_START,
18};
19
20Adapter::Adapter() {
21 if (usb_adapter_handle != nullptr) {
22 return;
23 }
24 LOG_INFO(Input, "GC Adapter Initialization started");
25
26 current_status = NO_ADAPTER_DETECTED;
27
28 const int init_res = libusb_init(&libusb_ctx);
29 if (init_res == LIBUSB_SUCCESS) {
30 StartScanThread();
31 } else {
32 LOG_ERROR(Input, "libusb could not be initialized. failed with error = {}", init_res);
33 }
34}
35
36GCPadStatus Adapter::GetPadStatus(int port, const std::array<u8, 37>& adapter_payload) {
37 GCPadStatus pad = {};
38 bool get_origin = false;
39
40 ControllerTypes type = ControllerTypes(adapter_payload[1 + (9 * port)] >> 4);
41 if (type != ControllerTypes::None) {
42 get_origin = true;
43 }
44
45 adapter_controllers_status[port] = type;
46
47 static constexpr std::array<PadButton, 8> b1_buttons{
48 PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B, PadButton::PAD_BUTTON_X,
49 PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT,
50 PadButton::PAD_BUTTON_DOWN, PadButton::PAD_BUTTON_UP,
51 };
52
53 static constexpr std::array<PadButton, 4> b2_buttons{
54 PadButton::PAD_BUTTON_START,
55 PadButton::PAD_TRIGGER_Z,
56 PadButton::PAD_TRIGGER_R,
57 PadButton::PAD_TRIGGER_L,
58 };
59
60 if (adapter_controllers_status[port] != ControllerTypes::None) {
61 const u8 b1 = adapter_payload[1 + (9 * port) + 1];
62 const u8 b2 = adapter_payload[1 + (9 * port) + 2];
63
64 for (std::size_t i = 0; i < b1_buttons.size(); ++i) {
65 if ((b1 & (1U << i)) != 0) {
66 pad.button |= static_cast<u16>(b1_buttons[i]);
67 }
68 }
69
70 for (std::size_t j = 0; j < b2_buttons.size(); ++j) {
71 if ((b2 & (1U << j)) != 0) {
72 pad.button |= static_cast<u16>(b2_buttons[j]);
73 }
74 }
75
76 if (get_origin) {
77 pad.button |= PAD_GET_ORIGIN;
78 }
79
80 pad.stick_x = adapter_payload[1 + (9 * port) + 3];
81 pad.stick_y = adapter_payload[1 + (9 * port) + 4];
82 pad.substick_x = adapter_payload[1 + (9 * port) + 5];
83 pad.substick_y = adapter_payload[1 + (9 * port) + 6];
84 pad.trigger_left = adapter_payload[1 + (9 * port) + 7];
85 pad.trigger_right = adapter_payload[1 + (9 * port) + 8];
86 }
87 return pad;
88}
89
90void Adapter::PadToState(const GCPadStatus& pad, GCState& state) {
91 for (const auto& button : PadButtonArray) {
92 const u16 button_value = static_cast<u16>(button);
93 state.buttons.insert_or_assign(button_value, pad.button & button_value);
94 }
95
96 state.axes.insert_or_assign(static_cast<u8>(PadAxes::StickX), pad.stick_x);
97 state.axes.insert_or_assign(static_cast<u8>(PadAxes::StickY), pad.stick_y);
98 state.axes.insert_or_assign(static_cast<u8>(PadAxes::SubstickX), pad.substick_x);
99 state.axes.insert_or_assign(static_cast<u8>(PadAxes::SubstickY), pad.substick_y);
100 state.axes.insert_or_assign(static_cast<u8>(PadAxes::TriggerLeft), pad.trigger_left);
101 state.axes.insert_or_assign(static_cast<u8>(PadAxes::TriggerRight), pad.trigger_right);
102}
103
104void Adapter::Read() {
105 LOG_DEBUG(Input, "GC Adapter Read() thread started");
106
107 int payload_size_in, payload_size_copy;
108 std::array<u8, 37> adapter_payload;
109 std::array<u8, 37> adapter_payload_copy;
110 std::array<GCPadStatus, 4> pads;
111
112 while (adapter_thread_running) {
113 libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(),
114 sizeof(adapter_payload), &payload_size_in, 16);
115 payload_size_copy = 0;
116 // this mutex might be redundant?
117 {
118 std::lock_guard<std::mutex> lk(s_mutex);
119 std::copy(std::begin(adapter_payload), std::end(adapter_payload),
120 std::begin(adapter_payload_copy));
121 payload_size_copy = payload_size_in;
122 }
123
124 if (payload_size_copy != sizeof(adapter_payload_copy) ||
125 adapter_payload_copy[0] != LIBUSB_DT_HID) {
126 LOG_ERROR(Input, "error reading payload (size: {}, type: {:02x})", payload_size_copy,
127 adapter_payload_copy[0]);
128 adapter_thread_running = false; // error reading from adapter, stop reading.
129 break;
130 }
131 for (std::size_t port = 0; port < pads.size(); ++port) {
132 pads[port] = GetPadStatus(port, adapter_payload_copy);
133 if (DeviceConnected(port) && configuring) {
134 if (pads[port].button != PAD_GET_ORIGIN) {
135 pad_queue[port].Push(pads[port]);
136 }
137
138 // Accounting for a threshold here because of some controller variance
139 if (pads[port].stick_x > pads[port].MAIN_STICK_CENTER_X + pads[port].THRESHOLD ||
140 pads[port].stick_x < pads[port].MAIN_STICK_CENTER_X - pads[port].THRESHOLD) {
141 pads[port].axis = GCAdapter::PadAxes::StickX;
142 pads[port].axis_value = pads[port].stick_x;
143 pad_queue[port].Push(pads[port]);
144 }
145 if (pads[port].stick_y > pads[port].MAIN_STICK_CENTER_Y + pads[port].THRESHOLD ||
146 pads[port].stick_y < pads[port].MAIN_STICK_CENTER_Y - pads[port].THRESHOLD) {
147 pads[port].axis = GCAdapter::PadAxes::StickY;
148 pads[port].axis_value = pads[port].stick_y;
149 pad_queue[port].Push(pads[port]);
150 }
151 if (pads[port].substick_x > pads[port].C_STICK_CENTER_X + pads[port].THRESHOLD ||
152 pads[port].substick_x < pads[port].C_STICK_CENTER_X - pads[port].THRESHOLD) {
153 pads[port].axis = GCAdapter::PadAxes::SubstickX;
154 pads[port].axis_value = pads[port].substick_x;
155 pad_queue[port].Push(pads[port]);
156 }
157 if (pads[port].substick_y > pads[port].C_STICK_CENTER_Y + pads[port].THRESHOLD ||
158 pads[port].substick_y < pads[port].C_STICK_CENTER_Y - pads[port].THRESHOLD) {
159 pads[port].axis = GCAdapter::PadAxes::SubstickY;
160 pads[port].axis_value = pads[port].substick_y;
161 pad_queue[port].Push(pads[port]);
162 }
163 if (pads[port].trigger_left > pads[port].TRIGGER_THRESHOLD) {
164 pads[port].axis = GCAdapter::PadAxes::TriggerLeft;
165 pads[port].axis_value = pads[port].trigger_left;
166 pad_queue[port].Push(pads[port]);
167 }
168 if (pads[port].trigger_right > pads[port].TRIGGER_THRESHOLD) {
169 pads[port].axis = GCAdapter::PadAxes::TriggerRight;
170 pads[port].axis_value = pads[port].trigger_right;
171 pad_queue[port].Push(pads[port]);
172 }
173 }
174 PadToState(pads[port], state[port]);
175 }
176 std::this_thread::yield();
177 }
178}
179
180void Adapter::ScanThreadFunc() {
181 LOG_INFO(Input, "GC Adapter scanning thread started");
182
183 while (detect_thread_running) {
184 if (usb_adapter_handle == nullptr) {
185 std::lock_guard<std::mutex> lk(initialization_mutex);
186 Setup();
187 }
188 std::this_thread::sleep_for(std::chrono::milliseconds(500));
189 }
190}
191
192void Adapter::StartScanThread() {
193 if (detect_thread_running) {
194 return;
195 }
196 if (!libusb_ctx) {
197 return;
198 }
199
200 detect_thread_running = true;
201 detect_thread = std::thread([=] { ScanThreadFunc(); });
202}
203
204void Adapter::StopScanThread() {
205 detect_thread_running = false;
206 detect_thread.join();
207}
208
209void Adapter::Setup() {
210 // Reset the error status in case the adapter gets unplugged
211 if (current_status < 0) {
212 current_status = NO_ADAPTER_DETECTED;
213 }
214
215 adapter_controllers_status.fill(ControllerTypes::None);
216
217 // pointer to list of connected usb devices
218 libusb_device** devices{};
219
220 // populate the list of devices, get the count
221 const ssize_t device_count = libusb_get_device_list(libusb_ctx, &devices);
222 if (device_count < 0) {
223 LOG_ERROR(Input, "libusb_get_device_list failed with error: {}", device_count);
224 detect_thread_running = false; // Stop the loop constantly checking for gc adapter
225 // TODO: For hotplug+gc adapter checkbox implementation, revert this.
226 return;
227 }
228
229 if (devices != nullptr) {
230 for (std::size_t index = 0; index < device_count; ++index) {
231 if (CheckDeviceAccess(devices[index])) {
232 // GC Adapter found and accessible, registering it
233 GetGCEndpoint(devices[index]);
234 break;
235 }
236 }
237 libusb_free_device_list(devices, 1);
238 }
239}
240
241bool Adapter::CheckDeviceAccess(libusb_device* device) {
242 libusb_device_descriptor desc;
243 const int get_descriptor_error = libusb_get_device_descriptor(device, &desc);
244 if (get_descriptor_error) {
245 // could not acquire the descriptor, no point in trying to use it.
246 LOG_ERROR(Input, "libusb_get_device_descriptor failed with error: {}",
247 get_descriptor_error);
248 return false;
249 }
250
251 if (desc.idVendor != 0x057e || desc.idProduct != 0x0337) {
252 // This isn't the device we are looking for.
253 return false;
254 }
255 const int open_error = libusb_open(device, &usb_adapter_handle);
256
257 if (open_error == LIBUSB_ERROR_ACCESS) {
258 LOG_ERROR(Input, "Yuzu can not gain access to this device: ID {:04X}:{:04X}.",
259 desc.idVendor, desc.idProduct);
260 return false;
261 }
262 if (open_error) {
263 LOG_ERROR(Input, "libusb_open failed to open device with error = {}", open_error);
264 return false;
265 }
266
267 int kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle, 0);
268 if (kernel_driver_error == 1) {
269 kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle, 0);
270 if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
271 LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}",
272 kernel_driver_error);
273 }
274 }
275
276 if (kernel_driver_error && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
277 libusb_close(usb_adapter_handle);
278 usb_adapter_handle = nullptr;
279 return false;
280 }
281
282 const int interface_claim_error = libusb_claim_interface(usb_adapter_handle, 0);
283 if (interface_claim_error) {
284 LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error);
285 libusb_close(usb_adapter_handle);
286 usb_adapter_handle = nullptr;
287 return false;
288 }
289
290 return true;
291}
292
293void Adapter::GetGCEndpoint(libusb_device* device) {
294 libusb_config_descriptor* config = nullptr;
295 const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config);
296 if (config_descriptor_return != LIBUSB_SUCCESS) {
297 LOG_ERROR(Input, "libusb_get_config_descriptor failed with error = {}",
298 config_descriptor_return);
299 return;
300 }
301
302 for (u8 ic = 0; ic < config->bNumInterfaces; ic++) {
303 const libusb_interface* interfaceContainer = &config->interface[ic];
304 for (int i = 0; i < interfaceContainer->num_altsetting; i++) {
305 const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i];
306 for (u8 e = 0; e < interface->bNumEndpoints; e++) {
307 const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e];
308 if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) {
309 input_endpoint = endpoint->bEndpointAddress;
310 } else {
311 output_endpoint = endpoint->bEndpointAddress;
312 }
313 }
314 }
315 }
316 // This transfer seems to be responsible for clearing the state of the adapter
317 // Used to clear the "busy" state of when the device is unexpectedly unplugged
318 unsigned char clear_payload = 0x13;
319 libusb_interrupt_transfer(usb_adapter_handle, output_endpoint, &clear_payload,
320 sizeof(clear_payload), nullptr, 16);
321
322 adapter_thread_running = true;
323 current_status = ADAPTER_DETECTED;
324 adapter_input_thread = std::thread([=] { Read(); }); // Read input
325}
326
327Adapter::~Adapter() {
328 StopScanThread();
329 Reset();
330}
331
332void Adapter::Reset() {
333 std::unique_lock<std::mutex> lock(initialization_mutex, std::defer_lock);
334 if (!lock.try_lock()) {
335 return;
336 }
337 if (current_status != ADAPTER_DETECTED) {
338 return;
339 }
340
341 if (adapter_thread_running) {
342 adapter_thread_running = false;
343 }
344 adapter_input_thread.join();
345
346 adapter_controllers_status.fill(ControllerTypes::None);
347 current_status = NO_ADAPTER_DETECTED;
348
349 if (usb_adapter_handle) {
350 libusb_release_interface(usb_adapter_handle, 1);
351 libusb_close(usb_adapter_handle);
352 usb_adapter_handle = nullptr;
353 }
354
355 if (libusb_ctx) {
356 libusb_exit(libusb_ctx);
357 }
358}
359
360bool Adapter::DeviceConnected(int port) {
361 return adapter_controllers_status[port] != ControllerTypes::None;
362}
363
364void Adapter::ResetDeviceType(int port) {
365 adapter_controllers_status[port] = ControllerTypes::None;
366}
367
368void Adapter::BeginConfiguration() {
369 for (auto& pq : pad_queue) {
370 pq.Clear();
371 }
372 configuring = true;
373}
374
375void Adapter::EndConfiguration() {
376 for (auto& pq : pad_queue) {
377 pq.Clear();
378 }
379 configuring = false;
380}
381
382std::array<Common::SPSCQueue<GCPadStatus>, 4>& Adapter::GetPadQueue() {
383 return pad_queue;
384}
385
386const std::array<Common::SPSCQueue<GCPadStatus>, 4>& Adapter::GetPadQueue() const {
387 return pad_queue;
388}
389
390std::array<GCState, 4>& Adapter::GetPadState() {
391 return state;
392}
393
394const std::array<GCState, 4>& Adapter::GetPadState() const {
395 return state;
396}
397
398} // namespace GCAdapter
diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h
new file mode 100644
index 000000000..b1c2a1958
--- /dev/null
+++ b/src/input_common/gcadapter/gc_adapter.h
@@ -0,0 +1,161 @@
1// Copyright 2014 Dolphin Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#pragma once
6#include <algorithm>
7#include <functional>
8#include <mutex>
9#include <thread>
10#include <unordered_map>
11#include <libusb.h>
12#include "common/common_types.h"
13#include "common/threadsafe_queue.h"
14
15namespace GCAdapter {
16
17enum {
18 PAD_USE_ORIGIN = 0x0080,
19 PAD_GET_ORIGIN = 0x2000,
20 PAD_ERR_STATUS = 0x8000,
21};
22
23enum class PadButton {
24 PAD_BUTTON_LEFT = 0x0001,
25 PAD_BUTTON_RIGHT = 0x0002,
26 PAD_BUTTON_DOWN = 0x0004,
27 PAD_BUTTON_UP = 0x0008,
28 PAD_TRIGGER_Z = 0x0010,
29 PAD_TRIGGER_R = 0x0020,
30 PAD_TRIGGER_L = 0x0040,
31 PAD_BUTTON_A = 0x0100,
32 PAD_BUTTON_B = 0x0200,
33 PAD_BUTTON_X = 0x0400,
34 PAD_BUTTON_Y = 0x0800,
35 PAD_BUTTON_START = 0x1000,
36 // Below is for compatibility with "AxisButton" type
37 PAD_STICK = 0x2000,
38};
39
40extern const std::array<PadButton, 12> PadButtonArray;
41
42enum class PadAxes : u8 {
43 StickX,
44 StickY,
45 SubstickX,
46 SubstickY,
47 TriggerLeft,
48 TriggerRight,
49 Undefined,
50};
51
52struct GCPadStatus {
53 u16 button{}; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits
54 u8 stick_x{}; // 0 <= stick_x <= 255
55 u8 stick_y{}; // 0 <= stick_y <= 255
56 u8 substick_x{}; // 0 <= substick_x <= 255
57 u8 substick_y{}; // 0 <= substick_y <= 255
58 u8 trigger_left{}; // 0 <= trigger_left <= 255
59 u8 trigger_right{}; // 0 <= trigger_right <= 255
60
61 static constexpr u8 MAIN_STICK_CENTER_X = 0x80;
62 static constexpr u8 MAIN_STICK_CENTER_Y = 0x80;
63 static constexpr u8 MAIN_STICK_RADIUS = 0x7f;
64 static constexpr u8 C_STICK_CENTER_X = 0x80;
65 static constexpr u8 C_STICK_CENTER_Y = 0x80;
66 static constexpr u8 C_STICK_RADIUS = 0x7f;
67 static constexpr u8 THRESHOLD = 10;
68
69 // 256/4, at least a quarter press to count as a press. For polling mostly
70 static constexpr u8 TRIGGER_THRESHOLD = 64;
71
72 u8 port{};
73 PadAxes axis{PadAxes::Undefined};
74 u8 axis_value{255};
75};
76
77struct GCState {
78 std::unordered_map<int, bool> buttons;
79 std::unordered_map<int, u16> axes;
80};
81
82enum class ControllerTypes { None, Wired, Wireless };
83
84enum {
85 NO_ADAPTER_DETECTED = 0,
86 ADAPTER_DETECTED = 1,
87};
88
89class Adapter {
90public:
91 /// Initialize the GC Adapter capture and read sequence
92 Adapter();
93
94 /// Close the adapter read thread and release the adapter
95 ~Adapter();
96 /// Used for polling
97 void BeginConfiguration();
98 void EndConfiguration();
99
100 std::array<Common::SPSCQueue<GCPadStatus>, 4>& GetPadQueue();
101 const std::array<Common::SPSCQueue<GCPadStatus>, 4>& GetPadQueue() const;
102
103 std::array<GCState, 4>& GetPadState();
104 const std::array<GCState, 4>& GetPadState() const;
105
106private:
107 GCPadStatus GetPadStatus(int port, const std::array<u8, 37>& adapter_payload);
108
109 void PadToState(const GCPadStatus& pad, GCState& state);
110
111 void Read();
112 void ScanThreadFunc();
113 /// Begin scanning for the GC Adapter.
114 void StartScanThread();
115
116 /// Stop scanning for the adapter
117 void StopScanThread();
118
119 /// Returns true if there is a device connected to port
120 bool DeviceConnected(int port);
121
122 /// Resets status of device connected to port
123 void ResetDeviceType(int port);
124
125 /// Returns true if we successfully gain access to GC Adapter
126 bool CheckDeviceAccess(libusb_device* device);
127
128 /// Captures GC Adapter endpoint address,
129 void GetGCEndpoint(libusb_device* device);
130
131 /// For shutting down, clear all data, join all threads, release usb
132 void Reset();
133
134 /// For use in initialization, querying devices to find the adapter
135 void Setup();
136
137 int current_status = NO_ADAPTER_DETECTED;
138 libusb_device_handle* usb_adapter_handle = nullptr;
139 std::array<ControllerTypes, 4> adapter_controllers_status{};
140
141 std::mutex s_mutex;
142
143 std::thread adapter_input_thread;
144 bool adapter_thread_running;
145
146 std::mutex initialization_mutex;
147 std::thread detect_thread;
148 bool detect_thread_running = false;
149
150 libusb_context* libusb_ctx;
151
152 u8 input_endpoint = 0;
153 u8 output_endpoint = 0;
154
155 bool configuring = false;
156
157 std::array<Common::SPSCQueue<GCPadStatus>, 4> pad_queue;
158 std::array<GCState, 4> state;
159};
160
161} // namespace GCAdapter
diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp
new file mode 100644
index 000000000..385ce8430
--- /dev/null
+++ b/src/input_common/gcadapter/gc_poller.cpp
@@ -0,0 +1,272 @@
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 <atomic>
6#include <list>
7#include <mutex>
8#include <utility>
9#include "common/threadsafe_queue.h"
10#include "input_common/gcadapter/gc_adapter.h"
11#include "input_common/gcadapter/gc_poller.h"
12
13namespace InputCommon {
14
15class GCButton final : public Input::ButtonDevice {
16public:
17 explicit GCButton(int port_, int button_, GCAdapter::Adapter* adapter)
18 : port(port_), button(button_), gcadapter(adapter) {}
19
20 ~GCButton() override;
21
22 bool GetStatus() const override {
23 return gcadapter->GetPadState()[port].buttons.at(button);
24 }
25
26private:
27 const int port;
28 const int button;
29 GCAdapter::Adapter* gcadapter;
30};
31
32class GCAxisButton final : public Input::ButtonDevice {
33public:
34 explicit GCAxisButton(int port_, int axis_, float threshold_, bool trigger_if_greater_,
35 GCAdapter::Adapter* adapter)
36 : port(port_), axis(axis_), threshold(threshold_), trigger_if_greater(trigger_if_greater_),
37 gcadapter(adapter) {
38 // L/R triggers range is only in positive direction beginning near 0
39 // 0.0 threshold equates to near half trigger press, but threshold accounts for variability.
40 if (axis > 3) {
41 threshold *= -0.5;
42 }
43 }
44
45 bool GetStatus() const override {
46 const float axis_value = (gcadapter->GetPadState()[port].axes.at(axis) - 128.0f) / 128.0f;
47 if (trigger_if_greater) {
48 // TODO: Might be worthwile to set a slider for the trigger threshold. It is currently
49 // always set to 0.5 in configure_input_player.cpp ZL/ZR HandleClick
50 return axis_value > threshold;
51 }
52 return axis_value < -threshold;
53 }
54
55private:
56 const int port;
57 const int axis;
58 float threshold;
59 bool trigger_if_greater;
60 GCAdapter::Adapter* gcadapter;
61};
62
63GCButtonFactory::GCButtonFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
64 : adapter(std::move(adapter_)) {}
65
66GCButton::~GCButton() = default;
67
68std::unique_ptr<Input::ButtonDevice> GCButtonFactory::Create(const Common::ParamPackage& params) {
69 const int button_id = params.Get("button", 0);
70 const int port = params.Get("port", 0);
71
72 constexpr int PAD_STICK_ID = static_cast<u16>(GCAdapter::PadButton::PAD_STICK);
73
74 // button is not an axis/stick button
75 if (button_id != PAD_STICK_ID) {
76 auto button = std::make_unique<GCButton>(port, button_id, adapter.get());
77 return std::move(button);
78 }
79
80 // For Axis buttons, used by the binary sticks.
81 if (button_id == PAD_STICK_ID) {
82 const int axis = params.Get("axis", 0);
83 const float threshold = params.Get("threshold", 0.25f);
84 const std::string direction_name = params.Get("direction", "");
85 bool trigger_if_greater;
86 if (direction_name == "+") {
87 trigger_if_greater = true;
88 } else if (direction_name == "-") {
89 trigger_if_greater = false;
90 } else {
91 trigger_if_greater = true;
92 LOG_ERROR(Input, "Unknown direction {}", direction_name);
93 }
94 return std::make_unique<GCAxisButton>(port, axis, threshold, trigger_if_greater,
95 adapter.get());
96 }
97}
98
99Common::ParamPackage GCButtonFactory::GetNextInput() {
100 Common::ParamPackage params;
101 GCAdapter::GCPadStatus pad;
102 auto& queue = adapter->GetPadQueue();
103 for (std::size_t port = 0; port < queue.size(); ++port) {
104 while (queue[port].Pop(pad)) {
105 // This while loop will break on the earliest detected button
106 params.Set("engine", "gcpad");
107 params.Set("port", static_cast<int>(port));
108 for (const auto& button : GCAdapter::PadButtonArray) {
109 const u16 button_value = static_cast<u16>(button);
110 if (pad.button & button_value) {
111 params.Set("button", button_value);
112 break;
113 }
114 }
115
116 // For Axis button implementation
117 if (pad.axis != GCAdapter::PadAxes::Undefined) {
118 params.Set("axis", static_cast<u8>(pad.axis));
119 params.Set("button", static_cast<u16>(GCAdapter::PadButton::PAD_STICK));
120 if (pad.axis_value > 128) {
121 params.Set("direction", "+");
122 params.Set("threshold", "0.25");
123 } else {
124 params.Set("direction", "-");
125 params.Set("threshold", "-0.25");
126 }
127 break;
128 }
129 }
130 }
131 return params;
132}
133
134void GCButtonFactory::BeginConfiguration() {
135 polling = true;
136 adapter->BeginConfiguration();
137}
138
139void GCButtonFactory::EndConfiguration() {
140 polling = false;
141 adapter->EndConfiguration();
142}
143
144class GCAnalog final : public Input::AnalogDevice {
145public:
146 GCAnalog(int port_, int axis_x_, int axis_y_, float deadzone_, GCAdapter::Adapter* adapter)
147 : port(port_), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_), gcadapter(adapter) {}
148
149 float GetAxis(int axis) const {
150 std::lock_guard lock{mutex};
151 // division is not by a perfect 128 to account for some variance in center location
152 // e.g. my device idled at 131 in X, 120 in Y, and full range of motion was in range
153 // [20-230]
154 return (gcadapter->GetPadState()[port].axes.at(axis) - 128.0f) / 95.0f;
155 }
156
157 std::pair<float, float> GetAnalog(int axis_x, int axis_y) const {
158 float x = GetAxis(axis_x);
159 float y = GetAxis(axis_y);
160
161 // Make sure the coordinates are in the unit circle,
162 // otherwise normalize it.
163 float r = x * x + y * y;
164 if (r > 1.0f) {
165 r = std::sqrt(r);
166 x /= r;
167 y /= r;
168 }
169
170 return {x, y};
171 }
172
173 std::tuple<float, float> GetStatus() const override {
174 const auto [x, y] = GetAnalog(axis_x, axis_y);
175 const float r = std::sqrt((x * x) + (y * y));
176 if (r > deadzone) {
177 return {x / r * (r - deadzone) / (1 - deadzone),
178 y / r * (r - deadzone) / (1 - deadzone)};
179 }
180 return {0.0f, 0.0f};
181 }
182
183 bool GetAnalogDirectionStatus(Input::AnalogDirection direction) const override {
184 const auto [x, y] = GetStatus();
185 const float directional_deadzone = 0.4f;
186 switch (direction) {
187 case Input::AnalogDirection::RIGHT:
188 return x > directional_deadzone;
189 case Input::AnalogDirection::LEFT:
190 return x < -directional_deadzone;
191 case Input::AnalogDirection::UP:
192 return y > directional_deadzone;
193 case Input::AnalogDirection::DOWN:
194 return y < -directional_deadzone;
195 }
196 return false;
197 }
198
199private:
200 const int port;
201 const int axis_x;
202 const int axis_y;
203 const float deadzone;
204 mutable std::mutex mutex;
205 GCAdapter::Adapter* gcadapter;
206};
207
208/// An analog device factory that creates analog devices from GC Adapter
209GCAnalogFactory::GCAnalogFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
210 : adapter(std::move(adapter_)) {}
211
212/**
213 * Creates analog device from joystick axes
214 * @param params contains parameters for creating the device:
215 * - "port": the nth gcpad on the adapter
216 * - "axis_x": the index of the axis to be bind as x-axis
217 * - "axis_y": the index of the axis to be bind as y-axis
218 */
219std::unique_ptr<Input::AnalogDevice> GCAnalogFactory::Create(const Common::ParamPackage& params) {
220 const int port = params.Get("port", 0);
221 const int axis_x = params.Get("axis_x", 0);
222 const int axis_y = params.Get("axis_y", 1);
223 const float deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, .99f);
224
225 return std::make_unique<GCAnalog>(port, axis_x, axis_y, deadzone, adapter.get());
226}
227
228void GCAnalogFactory::BeginConfiguration() {
229 polling = true;
230 adapter->BeginConfiguration();
231}
232
233void GCAnalogFactory::EndConfiguration() {
234 polling = false;
235 adapter->EndConfiguration();
236}
237
238Common::ParamPackage GCAnalogFactory::GetNextInput() {
239 GCAdapter::GCPadStatus pad;
240 auto& queue = adapter->GetPadQueue();
241 for (std::size_t port = 0; port < queue.size(); ++port) {
242 while (queue[port].Pop(pad)) {
243 if (pad.axis == GCAdapter::PadAxes::Undefined ||
244 std::abs((pad.axis_value - 128.0f) / 128.0f) < 0.1) {
245 continue;
246 }
247 // An analog device needs two axes, so we need to store the axis for later and wait for
248 // a second input event. The axes also must be from the same joystick.
249 const u8 axis = static_cast<u8>(pad.axis);
250 if (analog_x_axis == -1) {
251 analog_x_axis = axis;
252 controller_number = port;
253 } else if (analog_y_axis == -1 && analog_x_axis != axis && controller_number == port) {
254 analog_y_axis = axis;
255 }
256 }
257 }
258 Common::ParamPackage params;
259 if (analog_x_axis != -1 && analog_y_axis != -1) {
260 params.Set("engine", "gcpad");
261 params.Set("port", controller_number);
262 params.Set("axis_x", analog_x_axis);
263 params.Set("axis_y", analog_y_axis);
264 analog_x_axis = -1;
265 analog_y_axis = -1;
266 controller_number = -1;
267 return params;
268 }
269 return params;
270}
271
272} // namespace InputCommon
diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h
new file mode 100644
index 000000000..e96af7d51
--- /dev/null
+++ b/src/input_common/gcadapter/gc_poller.h
@@ -0,0 +1,67 @@
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 <memory>
8#include "core/frontend/input.h"
9#include "input_common/gcadapter/gc_adapter.h"
10
11namespace InputCommon {
12
13/**
14 * A button device factory representing a gcpad. It receives gcpad events and forward them
15 * to all button devices it created.
16 */
17class GCButtonFactory final : public Input::Factory<Input::ButtonDevice> {
18public:
19 explicit GCButtonFactory(std::shared_ptr<GCAdapter::Adapter> adapter_);
20
21 /**
22 * Creates a button device from a button press
23 * @param params contains parameters for creating the device:
24 * - "code": the code of the key to bind with the button
25 */
26 std::unique_ptr<Input::ButtonDevice> Create(const Common::ParamPackage& params) override;
27
28 Common::ParamPackage GetNextInput();
29
30 /// For device input configuration/polling
31 void BeginConfiguration();
32 void EndConfiguration();
33
34 bool IsPolling() const {
35 return polling;
36 }
37
38private:
39 std::shared_ptr<GCAdapter::Adapter> adapter;
40 bool polling = false;
41};
42
43/// An analog device factory that creates analog devices from GC Adapter
44class GCAnalogFactory final : public Input::Factory<Input::AnalogDevice> {
45public:
46 explicit GCAnalogFactory(std::shared_ptr<GCAdapter::Adapter> adapter_);
47
48 std::unique_ptr<Input::AnalogDevice> Create(const Common::ParamPackage& params) override;
49 Common::ParamPackage GetNextInput();
50
51 /// For device input configuration/polling
52 void BeginConfiguration();
53 void EndConfiguration();
54
55 bool IsPolling() const {
56 return polling;
57 }
58
59private:
60 std::shared_ptr<GCAdapter::Adapter> adapter;
61 int analog_x_axis = -1;
62 int analog_y_axis = -1;
63 int controller_number = -1;
64 bool polling = false;
65};
66
67} // namespace InputCommon