summaryrefslogtreecommitdiff
path: root/src/input_common/gcadapter
diff options
context:
space:
mode:
authorGravatar Levi2021-01-10 22:09:56 -0700
committerGravatar Levi2021-01-10 22:09:56 -0700
commit7a3c884e39fccfbb498b855080bffabc9ce2e7f1 (patch)
tree5056f9406dec188439cb0deb87603498243a9412 /src/input_common/gcadapter
parentMore forgetting... duh (diff)
parentMerge pull request #5229 from Morph1984/fullscreen-opt (diff)
downloadyuzu-7a3c884e39fccfbb498b855080bffabc9ce2e7f1.tar.gz
yuzu-7a3c884e39fccfbb498b855080bffabc9ce2e7f1.tar.xz
yuzu-7a3c884e39fccfbb498b855080bffabc9ce2e7f1.zip
Merge remote-tracking branch 'upstream/master' into int-flags
Diffstat (limited to 'src/input_common/gcadapter')
-rw-r--r--src/input_common/gcadapter/gc_adapter.cpp457
-rw-r--r--src/input_common/gcadapter/gc_adapter.h146
-rw-r--r--src/input_common/gcadapter/gc_poller.cpp226
-rw-r--r--src/input_common/gcadapter/gc_poller.h11
4 files changed, 512 insertions, 328 deletions
diff --git a/src/input_common/gcadapter/gc_adapter.cpp b/src/input_common/gcadapter/gc_adapter.cpp
index 89c148aba..d80195c82 100644
--- a/src/input_common/gcadapter/gc_adapter.cpp
+++ b/src/input_common/gcadapter/gc_adapter.cpp
@@ -21,14 +21,6 @@
21 21
22namespace GCAdapter { 22namespace GCAdapter {
23 23
24/// Used to loop through and assign button in poller
25constexpr std::array<PadButton, 12> PadButtonArray{
26 PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, PadButton::PAD_BUTTON_DOWN,
27 PadButton::PAD_BUTTON_UP, PadButton::PAD_TRIGGER_Z, PadButton::PAD_TRIGGER_R,
28 PadButton::PAD_TRIGGER_L, PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B,
29 PadButton::PAD_BUTTON_X, PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_START,
30};
31
32Adapter::Adapter() { 24Adapter::Adapter() {
33 if (usb_adapter_handle != nullptr) { 25 if (usb_adapter_handle != nullptr) {
34 return; 26 return;
@@ -37,179 +29,261 @@ Adapter::Adapter() {
37 29
38 const int init_res = libusb_init(&libusb_ctx); 30 const int init_res = libusb_init(&libusb_ctx);
39 if (init_res == LIBUSB_SUCCESS) { 31 if (init_res == LIBUSB_SUCCESS) {
40 Setup(); 32 adapter_scan_thread = std::thread(&Adapter::AdapterScanThread, this);
41 } else { 33 } else {
42 LOG_ERROR(Input, "libusb could not be initialized. failed with error = {}", init_res); 34 LOG_ERROR(Input, "libusb could not be initialized. failed with error = {}", init_res);
43 } 35 }
44} 36}
45 37
46GCPadStatus Adapter::GetPadStatus(std::size_t port, const std::array<u8, 37>& adapter_payload) { 38Adapter::~Adapter() {
47 GCPadStatus pad = {}; 39 Reset();
48 const std::size_t offset = 1 + (9 * port); 40}
49 41
50 adapter_controllers_status[port] = static_cast<ControllerTypes>(adapter_payload[offset] >> 4); 42void Adapter::AdapterInputThread() {
43 LOG_DEBUG(Input, "GC Adapter input thread started");
44 s32 payload_size{};
45 AdapterPayload adapter_payload{};
51 46
52 static constexpr std::array<PadButton, 8> b1_buttons{ 47 if (adapter_scan_thread.joinable()) {
53 PadButton::PAD_BUTTON_A, PadButton::PAD_BUTTON_B, PadButton::PAD_BUTTON_X, 48 adapter_scan_thread.join();
54 PadButton::PAD_BUTTON_Y, PadButton::PAD_BUTTON_LEFT, PadButton::PAD_BUTTON_RIGHT, 49 }
55 PadButton::PAD_BUTTON_DOWN, PadButton::PAD_BUTTON_UP,
56 };
57 50
58 static constexpr std::array<PadButton, 4> b2_buttons{ 51 while (adapter_input_thread_running) {
59 PadButton::PAD_BUTTON_START, 52 libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(),
60 PadButton::PAD_TRIGGER_Z, 53 static_cast<s32>(adapter_payload.size()), &payload_size, 16);
61 PadButton::PAD_TRIGGER_R, 54 if (IsPayloadCorrect(adapter_payload, payload_size)) {
62 PadButton::PAD_TRIGGER_L, 55 UpdateControllers(adapter_payload);
63 }; 56 UpdateVibrations();
57 }
58 std::this_thread::yield();
59 }
64 60
65 static constexpr std::array<PadAxes, 6> axes{ 61 if (restart_scan_thread) {
66 PadAxes::StickX, PadAxes::StickY, PadAxes::SubstickX, 62 adapter_scan_thread = std::thread(&Adapter::AdapterScanThread, this);
67 PadAxes::SubstickY, PadAxes::TriggerLeft, PadAxes::TriggerRight, 63 restart_scan_thread = false;
68 }; 64 }
65}
69 66
70 if (adapter_controllers_status[port] == ControllerTypes::None && !get_origin[port]) { 67bool Adapter::IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size) {
71 // Controller may have been disconnected, recalibrate if reconnected. 68 if (payload_size != static_cast<s32>(adapter_payload.size()) ||
72 get_origin[port] = true; 69 adapter_payload[0] != LIBUSB_DT_HID) {
70 LOG_DEBUG(Input, "Error reading payload (size: {}, type: {:02x})", payload_size,
71 adapter_payload[0]);
72 if (input_error_counter++ > 20) {
73 LOG_ERROR(Input, "GC adapter timeout, Is the adapter connected?");
74 adapter_input_thread_running = false;
75 restart_scan_thread = true;
76 }
77 return false;
73 } 78 }
74 79
75 if (adapter_controllers_status[port] != ControllerTypes::None) { 80 input_error_counter = 0;
76 const u8 b1 = adapter_payload[offset + 1]; 81 return true;
77 const u8 b2 = adapter_payload[offset + 2]; 82}
78 83
79 for (std::size_t i = 0; i < b1_buttons.size(); ++i) { 84void Adapter::UpdateControllers(const AdapterPayload& adapter_payload) {
80 if ((b1 & (1U << i)) != 0) { 85 for (std::size_t port = 0; port < pads.size(); ++port) {
81 pad.button |= static_cast<u16>(b1_buttons[i]); 86 const std::size_t offset = 1 + (9 * port);
87 const auto type = static_cast<ControllerTypes>(adapter_payload[offset] >> 4);
88 UpdatePadType(port, type);
89 if (DeviceConnected(port)) {
90 const u8 b1 = adapter_payload[offset + 1];
91 const u8 b2 = adapter_payload[offset + 2];
92 UpdateStateButtons(port, b1, b2);
93 UpdateStateAxes(port, adapter_payload);
94 if (configuring) {
95 UpdateYuzuSettings(port);
82 } 96 }
83 } 97 }
98 }
99}
84 100
85 for (std::size_t j = 0; j < b2_buttons.size(); ++j) { 101void Adapter::UpdatePadType(std::size_t port, ControllerTypes pad_type) {
86 if ((b2 & (1U << j)) != 0) { 102 if (pads[port].type == pad_type) {
87 pad.button |= static_cast<u16>(b2_buttons[j]); 103 return;
88 } 104 }
89 } 105 // Device changed reset device and set new type
90 for (PadAxes axis : axes) { 106 ResetDevice(port);
91 const std::size_t index = static_cast<std::size_t>(axis); 107 pads[port].type = pad_type;
92 pad.axis_values[index] = adapter_payload[offset + 3 + index]; 108}
109
110void Adapter::UpdateStateButtons(std::size_t port, u8 b1, u8 b2) {
111 if (port >= pads.size()) {
112 return;
113 }
114
115 static constexpr std::array<PadButton, 8> b1_buttons{
116 PadButton::ButtonA, PadButton::ButtonB, PadButton::ButtonX, PadButton::ButtonY,
117 PadButton::ButtonLeft, PadButton::ButtonRight, PadButton::ButtonDown, PadButton::ButtonUp,
118 };
119
120 static constexpr std::array<PadButton, 4> b2_buttons{
121 PadButton::ButtonStart,
122 PadButton::TriggerZ,
123 PadButton::TriggerR,
124 PadButton::TriggerL,
125 };
126 pads[port].buttons = 0;
127 for (std::size_t i = 0; i < b1_buttons.size(); ++i) {
128 if ((b1 & (1U << i)) != 0) {
129 pads[port].buttons =
130 static_cast<u16>(pads[port].buttons | static_cast<u16>(b1_buttons[i]));
131 pads[port].last_button = b1_buttons[i];
93 } 132 }
133 }
94 134
95 if (get_origin[port]) { 135 for (std::size_t j = 0; j < b2_buttons.size(); ++j) {
96 origin_status[port].axis_values = pad.axis_values; 136 if ((b2 & (1U << j)) != 0) {
97 get_origin[port] = false; 137 pads[port].buttons =
138 static_cast<u16>(pads[port].buttons | static_cast<u16>(b2_buttons[j]));
139 pads[port].last_button = b2_buttons[j];
98 } 140 }
99 } 141 }
100 return pad;
101} 142}
102 143
103void Adapter::PadToState(const GCPadStatus& pad, GCState& state) { 144void Adapter::UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload) {
104 for (const auto& button : PadButtonArray) { 145 if (port >= pads.size()) {
105 const u16 button_value = static_cast<u16>(button); 146 return;
106 state.buttons.insert_or_assign(button_value, pad.button & button_value);
107 } 147 }
108 148
109 for (size_t i = 0; i < pad.axis_values.size(); ++i) { 149 const std::size_t offset = 1 + (9 * port);
110 state.axes.insert_or_assign(static_cast<u8>(i), pad.axis_values[i]); 150 static constexpr std::array<PadAxes, 6> axes{
151 PadAxes::StickX, PadAxes::StickY, PadAxes::SubstickX,
152 PadAxes::SubstickY, PadAxes::TriggerLeft, PadAxes::TriggerRight,
153 };
154
155 for (const PadAxes axis : axes) {
156 const auto index = static_cast<std::size_t>(axis);
157 const u8 axis_value = adapter_payload[offset + 3 + index];
158 if (pads[port].axis_origin[index] == 255) {
159 pads[port].axis_origin[index] = axis_value;
160 }
161 pads[port].axis_values[index] =
162 static_cast<s16>(axis_value - pads[port].axis_origin[index]);
111 } 163 }
112} 164}
113 165
114void Adapter::Read() { 166void Adapter::UpdateYuzuSettings(std::size_t port) {
115 LOG_DEBUG(Input, "GC Adapter Read() thread started"); 167 if (port >= pads.size()) {
168 return;
169 }
116 170
117 int payload_size; 171 constexpr u8 axis_threshold = 50;
118 std::array<u8, 37> adapter_payload; 172 GCPadStatus pad_status = {.port = port};
119 std::array<GCPadStatus, 4> pads;
120 173
121 while (adapter_thread_running) { 174 if (pads[port].buttons != 0) {
122 libusb_interrupt_transfer(usb_adapter_handle, input_endpoint, adapter_payload.data(), 175 pad_status.button = pads[port].last_button;
123 sizeof(adapter_payload), &payload_size, 16); 176 pad_queue.Push(pad_status);
124 177 }
125 if (payload_size != sizeof(adapter_payload) || adapter_payload[0] != LIBUSB_DT_HID) {
126 LOG_ERROR(Input,
127 "Error reading payload (size: {}, type: {:02x}) Is the adapter connected?",
128 payload_size, adapter_payload[0]);
129 adapter_thread_running = false; // error reading from adapter, stop reading.
130 break;
131 }
132 for (std::size_t port = 0; port < pads.size(); ++port) {
133 pads[port] = GetPadStatus(port, adapter_payload);
134 if (DeviceConnected(port) && configuring) {
135 if (pads[port].button != 0) {
136 pad_queue[port].Push(pads[port]);
137 }
138 178
139 // Accounting for a threshold here to ensure an intentional press 179 // Accounting for a threshold here to ensure an intentional press
140 for (size_t i = 0; i < pads[port].axis_values.size(); ++i) { 180 for (std::size_t i = 0; i < pads[port].axis_values.size(); ++i) {
141 const u8 value = pads[port].axis_values[i]; 181 const s16 value = pads[port].axis_values[i];
142 const u8 origin = origin_status[port].axis_values[i]; 182
143 183 if (value > axis_threshold || value < -axis_threshold) {
144 if (value > origin + pads[port].THRESHOLD || 184 pad_status.axis = static_cast<PadAxes>(i);
145 value < origin - pads[port].THRESHOLD) { 185 pad_status.axis_value = value;
146 pads[port].axis = static_cast<PadAxes>(i); 186 pad_status.axis_threshold = axis_threshold;
147 pads[port].axis_value = pads[port].axis_values[i]; 187 pad_queue.Push(pad_status);
148 pad_queue[port].Push(pads[port]);
149 }
150 }
151 }
152 PadToState(pads[port], state[port]);
153 } 188 }
154 std::this_thread::yield();
155 } 189 }
156} 190}
157 191
158void Adapter::Setup() { 192void Adapter::UpdateVibrations() {
159 // Initialize all controllers as unplugged 193 // Use 8 states to keep the switching between on/off fast enough for
160 adapter_controllers_status.fill(ControllerTypes::None); 194 // a human to not notice the difference between switching from on/off
161 // Initialize all ports to store axis origin values 195 // More states = more rumble strengths = slower update time
162 get_origin.fill(true); 196 constexpr u8 vibration_states = 8;
163 197
164 // pointer to list of connected usb devices 198 vibration_counter = (vibration_counter + 1) % vibration_states;
165 libusb_device** devices{}; 199
166 200 for (GCController& pad : pads) {
167 // populate the list of devices, get the count 201 const bool vibrate = pad.rumble_amplitude > vibration_counter;
168 const ssize_t device_count = libusb_get_device_list(libusb_ctx, &devices); 202 vibration_changed |= vibrate != pad.enable_vibration;
169 if (device_count < 0) { 203 pad.enable_vibration = vibrate;
170 LOG_ERROR(Input, "libusb_get_device_list failed with error: {}", device_count);
171 return;
172 } 204 }
205 SendVibrations();
206}
173 207
174 if (devices != nullptr) { 208void Adapter::SendVibrations() {
175 for (std::size_t index = 0; index < static_cast<std::size_t>(device_count); ++index) { 209 if (!rumble_enabled || !vibration_changed) {
176 if (CheckDeviceAccess(devices[index])) { 210 return;
177 // GC Adapter found and accessible, registering it 211 }
178 GetGCEndpoint(devices[index]); 212 s32 size{};
179 break; 213 constexpr u8 rumble_command = 0x11;
180 } 214 const u8 p1 = pads[0].enable_vibration;
215 const u8 p2 = pads[1].enable_vibration;
216 const u8 p3 = pads[2].enable_vibration;
217 const u8 p4 = pads[3].enable_vibration;
218 std::array<u8, 5> payload = {rumble_command, p1, p2, p3, p4};
219 const int err = libusb_interrupt_transfer(usb_adapter_handle, output_endpoint, payload.data(),
220 static_cast<s32>(payload.size()), &size, 16);
221 if (err) {
222 LOG_DEBUG(Input, "Adapter libusb write failed: {}", libusb_error_name(err));
223 if (output_error_counter++ > 5) {
224 LOG_ERROR(Input, "GC adapter output timeout, Rumble disabled");
225 rumble_enabled = false;
181 } 226 }
182 libusb_free_device_list(devices, 1); 227 return;
183 } 228 }
229 output_error_counter = 0;
230 vibration_changed = false;
184} 231}
185 232
186bool Adapter::CheckDeviceAccess(libusb_device* device) { 233bool Adapter::RumblePlay(std::size_t port, u8 amplitude) {
187 libusb_device_descriptor desc; 234 pads[port].rumble_amplitude = amplitude;
188 const int get_descriptor_error = libusb_get_device_descriptor(device, &desc); 235
189 if (get_descriptor_error) { 236 return rumble_enabled;
190 // could not acquire the descriptor, no point in trying to use it. 237}
191 LOG_ERROR(Input, "libusb_get_device_descriptor failed with error: {}", 238
192 get_descriptor_error); 239void Adapter::AdapterScanThread() {
193 return false; 240 adapter_scan_thread_running = true;
241 adapter_input_thread_running = false;
242 if (adapter_input_thread.joinable()) {
243 adapter_input_thread.join();
194 } 244 }
245 ClearLibusbHandle();
246 ResetDevices();
247 while (adapter_scan_thread_running && !adapter_input_thread_running) {
248 Setup();
249 std::this_thread::sleep_for(std::chrono::seconds(1));
250 }
251}
195 252
196 if (desc.idVendor != 0x057e || desc.idProduct != 0x0337) { 253void Adapter::Setup() {
197 // This isn't the device we are looking for. 254 usb_adapter_handle = libusb_open_device_with_vid_pid(libusb_ctx, 0x057e, 0x0337);
198 return false; 255
256 if (usb_adapter_handle == NULL) {
257 return;
258 }
259 if (!CheckDeviceAccess()) {
260 ClearLibusbHandle();
261 return;
199 } 262 }
200 const int open_error = libusb_open(device, &usb_adapter_handle);
201 263
202 if (open_error == LIBUSB_ERROR_ACCESS) { 264 libusb_device* device = libusb_get_device(usb_adapter_handle);
203 LOG_ERROR(Input, "Yuzu can not gain access to this device: ID {:04X}:{:04X}.", 265
204 desc.idVendor, desc.idProduct); 266 LOG_INFO(Input, "GC adapter is now connected");
205 return false; 267 // GC Adapter found and accessible, registering it
268 if (GetGCEndpoint(device)) {
269 adapter_scan_thread_running = false;
270 adapter_input_thread_running = true;
271 rumble_enabled = true;
272 input_error_counter = 0;
273 output_error_counter = 0;
274 adapter_input_thread = std::thread(&Adapter::AdapterInputThread, this);
206 } 275 }
207 if (open_error) { 276}
208 LOG_ERROR(Input, "libusb_open failed to open device with error = {}", open_error); 277
209 return false; 278bool Adapter::CheckDeviceAccess() {
279 // This fixes payload problems from offbrand GCAdapters
280 const s32 control_transfer_error =
281 libusb_control_transfer(usb_adapter_handle, 0x21, 11, 0x0001, 0, nullptr, 0, 1000);
282 if (control_transfer_error < 0) {
283 LOG_ERROR(Input, "libusb_control_transfer failed with error= {}", control_transfer_error);
210 } 284 }
211 285
212 int kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle, 0); 286 s32 kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle, 0);
213 if (kernel_driver_error == 1) { 287 if (kernel_driver_error == 1) {
214 kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle, 0); 288 kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle, 0);
215 if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) { 289 if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
@@ -235,13 +309,13 @@ bool Adapter::CheckDeviceAccess(libusb_device* device) {
235 return true; 309 return true;
236} 310}
237 311
238void Adapter::GetGCEndpoint(libusb_device* device) { 312bool Adapter::GetGCEndpoint(libusb_device* device) {
239 libusb_config_descriptor* config = nullptr; 313 libusb_config_descriptor* config = nullptr;
240 const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config); 314 const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config);
241 if (config_descriptor_return != LIBUSB_SUCCESS) { 315 if (config_descriptor_return != LIBUSB_SUCCESS) {
242 LOG_ERROR(Input, "libusb_get_config_descriptor failed with error = {}", 316 LOG_ERROR(Input, "libusb_get_config_descriptor failed with error = {}",
243 config_descriptor_return); 317 config_descriptor_return);
244 return; 318 return false;
245 } 319 }
246 320
247 for (u8 ic = 0; ic < config->bNumInterfaces; ic++) { 321 for (u8 ic = 0; ic < config->bNumInterfaces; ic++) {
@@ -250,7 +324,7 @@ void Adapter::GetGCEndpoint(libusb_device* device) {
250 const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i]; 324 const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i];
251 for (u8 e = 0; e < interface->bNumEndpoints; e++) { 325 for (u8 e = 0; e < interface->bNumEndpoints; e++) {
252 const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e]; 326 const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e];
253 if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) { 327 if ((endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) != 0) {
254 input_endpoint = endpoint->bEndpointAddress; 328 input_endpoint = endpoint->bEndpointAddress;
255 } else { 329 } else {
256 output_endpoint = endpoint->bEndpointAddress; 330 output_endpoint = endpoint->bEndpointAddress;
@@ -263,31 +337,51 @@ void Adapter::GetGCEndpoint(libusb_device* device) {
263 unsigned char clear_payload = 0x13; 337 unsigned char clear_payload = 0x13;
264 libusb_interrupt_transfer(usb_adapter_handle, output_endpoint, &clear_payload, 338 libusb_interrupt_transfer(usb_adapter_handle, output_endpoint, &clear_payload,
265 sizeof(clear_payload), nullptr, 16); 339 sizeof(clear_payload), nullptr, 16);
266 340 return true;
267 adapter_thread_running = true;
268 adapter_input_thread = std::thread(&Adapter::Read, this);
269} 341}
270 342
271Adapter::~Adapter() { 343void Adapter::JoinThreads() {
272 Reset(); 344 restart_scan_thread = false;
273} 345 adapter_input_thread_running = false;
346 adapter_scan_thread_running = false;
274 347
275void Adapter::Reset() { 348 if (adapter_scan_thread.joinable()) {
276 if (adapter_thread_running) { 349 adapter_scan_thread.join();
277 adapter_thread_running = false;
278 } 350 }
351
279 if (adapter_input_thread.joinable()) { 352 if (adapter_input_thread.joinable()) {
280 adapter_input_thread.join(); 353 adapter_input_thread.join();
281 } 354 }
355}
282 356
283 adapter_controllers_status.fill(ControllerTypes::None); 357void Adapter::ClearLibusbHandle() {
284 get_origin.fill(true);
285
286 if (usb_adapter_handle) { 358 if (usb_adapter_handle) {
287 libusb_release_interface(usb_adapter_handle, 1); 359 libusb_release_interface(usb_adapter_handle, 1);
288 libusb_close(usb_adapter_handle); 360 libusb_close(usb_adapter_handle);
289 usb_adapter_handle = nullptr; 361 usb_adapter_handle = nullptr;
290 } 362 }
363}
364
365void Adapter::ResetDevices() {
366 for (std::size_t i = 0; i < pads.size(); ++i) {
367 ResetDevice(i);
368 }
369}
370
371void Adapter::ResetDevice(std::size_t port) {
372 pads[port].type = ControllerTypes::None;
373 pads[port].enable_vibration = false;
374 pads[port].rumble_amplitude = 0;
375 pads[port].buttons = 0;
376 pads[port].last_button = PadButton::Undefined;
377 pads[port].axis_values.fill(0);
378 pads[port].axis_origin.fill(255);
379}
380
381void Adapter::Reset() {
382 JoinThreads();
383 ClearLibusbHandle();
384 ResetDevices();
291 385
292 if (libusb_ctx) { 386 if (libusb_ctx) {
293 libusb_exit(libusb_ctx); 387 libusb_exit(libusb_ctx);
@@ -296,11 +390,11 @@ void Adapter::Reset() {
296 390
297std::vector<Common::ParamPackage> Adapter::GetInputDevices() const { 391std::vector<Common::ParamPackage> Adapter::GetInputDevices() const {
298 std::vector<Common::ParamPackage> devices; 392 std::vector<Common::ParamPackage> devices;
299 for (std::size_t port = 0; port < state.size(); ++port) { 393 for (std::size_t port = 0; port < pads.size(); ++port) {
300 if (!DeviceConnected(port)) { 394 if (!DeviceConnected(port)) {
301 continue; 395 continue;
302 } 396 }
303 std::string name = fmt::format("Gamecube Controller {}", port); 397 std::string name = fmt::format("Gamecube Controller {}", port + 1);
304 devices.emplace_back(Common::ParamPackage{ 398 devices.emplace_back(Common::ParamPackage{
305 {"class", "gcpad"}, 399 {"class", "gcpad"},
306 {"display", std::move(name)}, 400 {"display", std::move(name)},
@@ -317,18 +411,18 @@ InputCommon::ButtonMapping Adapter::GetButtonMappingForDevice(
317 // This list also excludes any button that can't be really mapped 411 // This list also excludes any button that can't be really mapped
318 static constexpr std::array<std::pair<Settings::NativeButton::Values, PadButton>, 12> 412 static constexpr std::array<std::pair<Settings::NativeButton::Values, PadButton>, 12>
319 switch_to_gcadapter_button = { 413 switch_to_gcadapter_button = {
320 std::pair{Settings::NativeButton::A, PadButton::PAD_BUTTON_A}, 414 std::pair{Settings::NativeButton::A, PadButton::ButtonA},
321 {Settings::NativeButton::B, PadButton::PAD_BUTTON_B}, 415 {Settings::NativeButton::B, PadButton::ButtonB},
322 {Settings::NativeButton::X, PadButton::PAD_BUTTON_X}, 416 {Settings::NativeButton::X, PadButton::ButtonX},
323 {Settings::NativeButton::Y, PadButton::PAD_BUTTON_Y}, 417 {Settings::NativeButton::Y, PadButton::ButtonY},
324 {Settings::NativeButton::Plus, PadButton::PAD_BUTTON_START}, 418 {Settings::NativeButton::Plus, PadButton::ButtonStart},
325 {Settings::NativeButton::DLeft, PadButton::PAD_BUTTON_LEFT}, 419 {Settings::NativeButton::DLeft, PadButton::ButtonLeft},
326 {Settings::NativeButton::DUp, PadButton::PAD_BUTTON_UP}, 420 {Settings::NativeButton::DUp, PadButton::ButtonUp},
327 {Settings::NativeButton::DRight, PadButton::PAD_BUTTON_RIGHT}, 421 {Settings::NativeButton::DRight, PadButton::ButtonRight},
328 {Settings::NativeButton::DDown, PadButton::PAD_BUTTON_DOWN}, 422 {Settings::NativeButton::DDown, PadButton::ButtonDown},
329 {Settings::NativeButton::SL, PadButton::PAD_TRIGGER_L}, 423 {Settings::NativeButton::SL, PadButton::TriggerL},
330 {Settings::NativeButton::SR, PadButton::PAD_TRIGGER_R}, 424 {Settings::NativeButton::SR, PadButton::TriggerR},
331 {Settings::NativeButton::R, PadButton::PAD_TRIGGER_Z}, 425 {Settings::NativeButton::R, PadButton::TriggerZ},
332 }; 426 };
333 if (!params.Has("port")) { 427 if (!params.Has("port")) {
334 return {}; 428 return {};
@@ -351,8 +445,10 @@ InputCommon::ButtonMapping Adapter::GetButtonMappingForDevice(
351 for (const auto& [switch_button, gcadapter_axis] : switch_to_gcadapter_axis) { 445 for (const auto& [switch_button, gcadapter_axis] : switch_to_gcadapter_axis) {
352 Common::ParamPackage button_params({{"engine", "gcpad"}}); 446 Common::ParamPackage button_params({{"engine", "gcpad"}});
353 button_params.Set("port", params.Get("port", 0)); 447 button_params.Set("port", params.Get("port", 0));
354 button_params.Set("button", static_cast<int>(PadButton::PAD_STICK)); 448 button_params.Set("button", static_cast<s32>(PadButton::Stick));
355 button_params.Set("axis", static_cast<int>(gcadapter_axis)); 449 button_params.Set("axis", static_cast<s32>(gcadapter_axis));
450 button_params.Set("threshold", 0.5f);
451 button_params.Set("direction", "+");
356 mapping.insert_or_assign(switch_button, std::move(button_params)); 452 mapping.insert_or_assign(switch_button, std::move(button_params));
357 } 453 }
358 return mapping; 454 return mapping;
@@ -381,46 +477,33 @@ InputCommon::AnalogMapping Adapter::GetAnalogMappingForDevice(
381} 477}
382 478
383bool Adapter::DeviceConnected(std::size_t port) const { 479bool Adapter::DeviceConnected(std::size_t port) const {
384 return adapter_controllers_status[port] != ControllerTypes::None; 480 return pads[port].type != ControllerTypes::None;
385}
386
387void Adapter::ResetDeviceType(std::size_t port) {
388 adapter_controllers_status[port] = ControllerTypes::None;
389} 481}
390 482
391void Adapter::BeginConfiguration() { 483void Adapter::BeginConfiguration() {
392 get_origin.fill(true); 484 pad_queue.Clear();
393 for (auto& pq : pad_queue) {
394 pq.Clear();
395 }
396 configuring = true; 485 configuring = true;
397} 486}
398 487
399void Adapter::EndConfiguration() { 488void Adapter::EndConfiguration() {
400 for (auto& pq : pad_queue) { 489 pad_queue.Clear();
401 pq.Clear();
402 }
403 configuring = false; 490 configuring = false;
404} 491}
405 492
406std::array<Common::SPSCQueue<GCPadStatus>, 4>& Adapter::GetPadQueue() { 493Common::SPSCQueue<GCPadStatus>& Adapter::GetPadQueue() {
407 return pad_queue; 494 return pad_queue;
408} 495}
409 496
410const std::array<Common::SPSCQueue<GCPadStatus>, 4>& Adapter::GetPadQueue() const { 497const Common::SPSCQueue<GCPadStatus>& Adapter::GetPadQueue() const {
411 return pad_queue; 498 return pad_queue;
412} 499}
413 500
414std::array<GCState, 4>& Adapter::GetPadState() { 501GCController& Adapter::GetPadState(std::size_t port) {
415 return state; 502 return pads.at(port);
416}
417
418const std::array<GCState, 4>& Adapter::GetPadState() const {
419 return state;
420} 503}
421 504
422int Adapter::GetOriginValue(int port, int axis) const { 505const GCController& Adapter::GetPadState(std::size_t port) const {
423 return origin_status[port].axis_values[axis]; 506 return pads.at(port);
424} 507}
425 508
426} // namespace GCAdapter 509} // namespace GCAdapter
diff --git a/src/input_common/gcadapter/gc_adapter.h b/src/input_common/gcadapter/gc_adapter.h
index 75bf9fe74..7a6c545bd 100644
--- a/src/input_common/gcadapter/gc_adapter.h
+++ b/src/input_common/gcadapter/gc_adapter.h
@@ -19,24 +19,23 @@ struct libusb_device_handle;
19namespace GCAdapter { 19namespace GCAdapter {
20 20
21enum class PadButton { 21enum class PadButton {
22 PAD_BUTTON_LEFT = 0x0001, 22 Undefined = 0x0000,
23 PAD_BUTTON_RIGHT = 0x0002, 23 ButtonLeft = 0x0001,
24 PAD_BUTTON_DOWN = 0x0004, 24 ButtonRight = 0x0002,
25 PAD_BUTTON_UP = 0x0008, 25 ButtonDown = 0x0004,
26 PAD_TRIGGER_Z = 0x0010, 26 ButtonUp = 0x0008,
27 PAD_TRIGGER_R = 0x0020, 27 TriggerZ = 0x0010,
28 PAD_TRIGGER_L = 0x0040, 28 TriggerR = 0x0020,
29 PAD_BUTTON_A = 0x0100, 29 TriggerL = 0x0040,
30 PAD_BUTTON_B = 0x0200, 30 ButtonA = 0x0100,
31 PAD_BUTTON_X = 0x0400, 31 ButtonB = 0x0200,
32 PAD_BUTTON_Y = 0x0800, 32 ButtonX = 0x0400,
33 PAD_BUTTON_START = 0x1000, 33 ButtonY = 0x0800,
34 ButtonStart = 0x1000,
34 // Below is for compatibility with "AxisButton" type 35 // Below is for compatibility with "AxisButton" type
35 PAD_STICK = 0x2000, 36 Stick = 0x2000,
36}; 37};
37 38
38extern const std::array<PadButton, 12> PadButtonArray;
39
40enum class PadAxes : u8 { 39enum class PadAxes : u8 {
41 StickX, 40 StickX,
42 StickY, 41 StickY,
@@ -47,89 +46,122 @@ enum class PadAxes : u8 {
47 Undefined, 46 Undefined,
48}; 47};
49 48
49enum class ControllerTypes {
50 None,
51 Wired,
52 Wireless,
53};
54
50struct GCPadStatus { 55struct GCPadStatus {
51 u16 button{}; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits 56 std::size_t port{};
52 57
53 std::array<u8, 6> axis_values{}; // Triggers and sticks, following indices defined in PadAxes 58 PadButton button{PadButton::Undefined}; // Or-ed PAD_BUTTON_* and PAD_TRIGGER_* bits
54 static constexpr u8 THRESHOLD = 50; // Threshold for axis press for polling
55 59
56 u8 port{};
57 PadAxes axis{PadAxes::Undefined}; 60 PadAxes axis{PadAxes::Undefined};
58 u8 axis_value{255}; 61 s16 axis_value{};
62 u8 axis_threshold{50};
59}; 63};
60 64
61struct GCState { 65struct GCController {
62 std::unordered_map<int, bool> buttons; 66 ControllerTypes type{};
63 std::unordered_map<int, u16> axes; 67 bool enable_vibration{};
68 u8 rumble_amplitude{};
69 u16 buttons{};
70 PadButton last_button{};
71 std::array<s16, 6> axis_values{};
72 std::array<u8, 6> axis_origin{};
64}; 73};
65 74
66enum class ControllerTypes { None, Wired, Wireless };
67
68class Adapter { 75class Adapter {
69public: 76public:
70 /// Initialize the GC Adapter capture and read sequence
71 Adapter(); 77 Adapter();
72
73 /// Close the adapter read thread and release the adapter
74 ~Adapter(); 78 ~Adapter();
79
80 /// Request a vibration for a controller
81 bool RumblePlay(std::size_t port, u8 amplitude);
82
75 /// Used for polling 83 /// Used for polling
76 void BeginConfiguration(); 84 void BeginConfiguration();
77 void EndConfiguration(); 85 void EndConfiguration();
78 86
87 Common::SPSCQueue<GCPadStatus>& GetPadQueue();
88 const Common::SPSCQueue<GCPadStatus>& GetPadQueue() const;
89
90 GCController& GetPadState(std::size_t port);
91 const GCController& GetPadState(std::size_t port) const;
92
93 /// Returns true if there is a device connected to port
94 bool DeviceConnected(std::size_t port) const;
95
96 /// Used for automapping features
79 std::vector<Common::ParamPackage> GetInputDevices() const; 97 std::vector<Common::ParamPackage> GetInputDevices() const;
80 InputCommon::ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& params) const; 98 InputCommon::ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& params) const;
81 InputCommon::AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) const; 99 InputCommon::AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) const;
82 100
83 /// Returns true if there is a device connected to port 101private:
84 bool DeviceConnected(std::size_t port) const; 102 using AdapterPayload = std::array<u8, 37>;
85 103
86 std::array<Common::SPSCQueue<GCPadStatus>, 4>& GetPadQueue(); 104 void UpdatePadType(std::size_t port, ControllerTypes pad_type);
87 const std::array<Common::SPSCQueue<GCPadStatus>, 4>& GetPadQueue() const; 105 void UpdateControllers(const AdapterPayload& adapter_payload);
106 void UpdateYuzuSettings(std::size_t port);
107 void UpdateStateButtons(std::size_t port, u8 b1, u8 b2);
108 void UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload);
109 void UpdateVibrations();
88 110
89 std::array<GCState, 4>& GetPadState(); 111 void AdapterInputThread();
90 const std::array<GCState, 4>& GetPadState() const;
91 112
92 int GetOriginValue(int port, int axis) const; 113 void AdapterScanThread();
93 114
94private: 115 bool IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size);
95 GCPadStatus GetPadStatus(std::size_t port, const std::array<u8, 37>& adapter_payload); 116
117 // Updates vibration state of all controllers
118 void SendVibrations();
96 119
97 void PadToState(const GCPadStatus& pad, GCState& state); 120 /// For use in initialization, querying devices to find the adapter
121 void Setup();
98 122
99 void Read(); 123 /// Resets status of all GC controller devices to a disconnected state
124 void ResetDevices();
100 125
101 /// Resets status of device connected to port 126 /// Resets status of device connected to a disconnected state
102 void ResetDeviceType(std::size_t port); 127 void ResetDevice(std::size_t port);
103 128
104 /// Returns true if we successfully gain access to GC Adapter 129 /// Returns true if we successfully gain access to GC Adapter
105 bool CheckDeviceAccess(libusb_device* device); 130 bool CheckDeviceAccess();
106 131
107 /// Captures GC Adapter endpoint address, 132 /// Captures GC Adapter endpoint address
108 void GetGCEndpoint(libusb_device* device); 133 /// Returns true if the endpoint was set correctly
134 bool GetGCEndpoint(libusb_device* device);
109 135
110 /// For shutting down, clear all data, join all threads, release usb 136 /// For shutting down, clear all data, join all threads, release usb
111 void Reset(); 137 void Reset();
112 138
113 /// For use in initialization, querying devices to find the adapter 139 // Join all threads
114 void Setup(); 140 void JoinThreads();
141
142 // Release usb handles
143 void ClearLibusbHandle();
115 144
116 libusb_device_handle* usb_adapter_handle = nullptr; 145 libusb_device_handle* usb_adapter_handle = nullptr;
146 std::array<GCController, 4> pads;
147 Common::SPSCQueue<GCPadStatus> pad_queue;
117 148
118 std::thread adapter_input_thread; 149 std::thread adapter_input_thread;
119 bool adapter_thread_running; 150 std::thread adapter_scan_thread;
151 bool adapter_input_thread_running;
152 bool adapter_scan_thread_running;
153 bool restart_scan_thread;
120 154
121 libusb_context* libusb_ctx; 155 libusb_context* libusb_ctx;
122 156
123 u8 input_endpoint = 0; 157 u8 input_endpoint{0};
124 u8 output_endpoint = 0; 158 u8 output_endpoint{0};
125 159 u8 input_error_counter{0};
126 bool configuring = false; 160 u8 output_error_counter{0};
161 int vibration_counter{0};
127 162
128 std::array<GCState, 4> state; 163 bool configuring{false};
129 std::array<bool, 4> get_origin; 164 bool rumble_enabled{true};
130 std::array<GCPadStatus, 4> origin_status; 165 bool vibration_changed{true};
131 std::array<Common::SPSCQueue<GCPadStatus>, 4> pad_queue;
132 std::array<ControllerTypes, 4> adapter_controllers_status{};
133}; 166};
134
135} // namespace GCAdapter 167} // namespace GCAdapter
diff --git a/src/input_common/gcadapter/gc_poller.cpp b/src/input_common/gcadapter/gc_poller.cpp
index 92e9e8e89..9670bdeb2 100644
--- a/src/input_common/gcadapter/gc_poller.cpp
+++ b/src/input_common/gcadapter/gc_poller.cpp
@@ -15,36 +15,35 @@ namespace InputCommon {
15 15
16class GCButton final : public Input::ButtonDevice { 16class GCButton final : public Input::ButtonDevice {
17public: 17public:
18 explicit GCButton(int port_, int button_, const GCAdapter::Adapter* adapter) 18 explicit GCButton(u32 port_, s32 button_, const GCAdapter::Adapter* adapter)
19 : port(port_), button(button_), gcadapter(adapter) {} 19 : port(port_), button(button_), gcadapter(adapter) {}
20 20
21 ~GCButton() override; 21 ~GCButton() override;
22 22
23 bool GetStatus() const override { 23 bool GetStatus() const override {
24 if (gcadapter->DeviceConnected(port)) { 24 if (gcadapter->DeviceConnected(port)) {
25 return gcadapter->GetPadState()[port].buttons.at(button); 25 return (gcadapter->GetPadState(port).buttons & button) != 0;
26 } 26 }
27 return false; 27 return false;
28 } 28 }
29 29
30private: 30private:
31 const int port; 31 const u32 port;
32 const int button; 32 const s32 button;
33 const GCAdapter::Adapter* gcadapter; 33 const GCAdapter::Adapter* gcadapter;
34}; 34};
35 35
36class GCAxisButton final : public Input::ButtonDevice { 36class GCAxisButton final : public Input::ButtonDevice {
37public: 37public:
38 explicit GCAxisButton(int port_, int axis_, float threshold_, bool trigger_if_greater_, 38 explicit GCAxisButton(u32 port_, u32 axis_, float threshold_, bool trigger_if_greater_,
39 const GCAdapter::Adapter* adapter) 39 const GCAdapter::Adapter* adapter)
40 : port(port_), axis(axis_), threshold(threshold_), trigger_if_greater(trigger_if_greater_), 40 : port(port_), axis(axis_), threshold(threshold_), trigger_if_greater(trigger_if_greater_),
41 gcadapter(adapter), 41 gcadapter(adapter) {}
42 origin_value(static_cast<float>(adapter->GetOriginValue(port_, axis_))) {}
43 42
44 bool GetStatus() const override { 43 bool GetStatus() const override {
45 if (gcadapter->DeviceConnected(port)) { 44 if (gcadapter->DeviceConnected(port)) {
46 const float current_axis_value = gcadapter->GetPadState()[port].axes.at(axis); 45 const float current_axis_value = gcadapter->GetPadState(port).axis_values.at(axis);
47 const float axis_value = (current_axis_value - origin_value) / 128.0f; 46 const float axis_value = current_axis_value / 128.0f;
48 if (trigger_if_greater) { 47 if (trigger_if_greater) {
49 // TODO: Might be worthwile to set a slider for the trigger threshold. It is 48 // TODO: Might be worthwile to set a slider for the trigger threshold. It is
50 // currently always set to 0.5 in configure_input_player.cpp ZL/ZR HandleClick 49 // currently always set to 0.5 in configure_input_player.cpp ZL/ZR HandleClick
@@ -56,12 +55,11 @@ public:
56 } 55 }
57 56
58private: 57private:
59 const int port; 58 const u32 port;
60 const int axis; 59 const u32 axis;
61 float threshold; 60 float threshold;
62 bool trigger_if_greater; 61 bool trigger_if_greater;
63 const GCAdapter::Adapter* gcadapter; 62 const GCAdapter::Adapter* gcadapter;
64 const float origin_value;
65}; 63};
66 64
67GCButtonFactory::GCButtonFactory(std::shared_ptr<GCAdapter::Adapter> adapter_) 65GCButtonFactory::GCButtonFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
@@ -70,10 +68,10 @@ GCButtonFactory::GCButtonFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
70GCButton::~GCButton() = default; 68GCButton::~GCButton() = default;
71 69
72std::unique_ptr<Input::ButtonDevice> GCButtonFactory::Create(const Common::ParamPackage& params) { 70std::unique_ptr<Input::ButtonDevice> GCButtonFactory::Create(const Common::ParamPackage& params) {
73 const int button_id = params.Get("button", 0); 71 const auto button_id = params.Get("button", 0);
74 const int port = params.Get("port", 0); 72 const auto port = static_cast<u32>(params.Get("port", 0));
75 73
76 constexpr int PAD_STICK_ID = static_cast<u16>(GCAdapter::PadButton::PAD_STICK); 74 constexpr s32 PAD_STICK_ID = static_cast<s32>(GCAdapter::PadButton::Stick);
77 75
78 // button is not an axis/stick button 76 // button is not an axis/stick button
79 if (button_id != PAD_STICK_ID) { 77 if (button_id != PAD_STICK_ID) {
@@ -98,7 +96,6 @@ std::unique_ptr<Input::ButtonDevice> GCButtonFactory::Create(const Common::Param
98 adapter.get()); 96 adapter.get());
99 } 97 }
100 98
101 UNREACHABLE();
102 return nullptr; 99 return nullptr;
103} 100}
104 101
@@ -106,32 +103,25 @@ Common::ParamPackage GCButtonFactory::GetNextInput() const {
106 Common::ParamPackage params; 103 Common::ParamPackage params;
107 GCAdapter::GCPadStatus pad; 104 GCAdapter::GCPadStatus pad;
108 auto& queue = adapter->GetPadQueue(); 105 auto& queue = adapter->GetPadQueue();
109 for (std::size_t port = 0; port < queue.size(); ++port) { 106 while (queue.Pop(pad)) {
110 while (queue[port].Pop(pad)) { 107 // This while loop will break on the earliest detected button
111 // This while loop will break on the earliest detected button 108 params.Set("engine", "gcpad");
112 params.Set("engine", "gcpad"); 109 params.Set("port", static_cast<s32>(pad.port));
113 params.Set("port", static_cast<int>(port)); 110 if (pad.button != GCAdapter::PadButton::Undefined) {
114 for (const auto& button : GCAdapter::PadButtonArray) { 111 params.Set("button", static_cast<u16>(pad.button));
115 const u16 button_value = static_cast<u16>(button); 112 }
116 if (pad.button & button_value) {
117 params.Set("button", button_value);
118 break;
119 }
120 }
121 113
122 // For Axis button implementation 114 // For Axis button implementation
123 if (pad.axis != GCAdapter::PadAxes::Undefined) { 115 if (pad.axis != GCAdapter::PadAxes::Undefined) {
124 params.Set("axis", static_cast<u8>(pad.axis)); 116 params.Set("axis", static_cast<u8>(pad.axis));
125 params.Set("button", static_cast<u16>(GCAdapter::PadButton::PAD_STICK)); 117 params.Set("button", static_cast<u16>(GCAdapter::PadButton::Stick));
126 if (pad.axis_value > 128) { 118 params.Set("threshold", "0.25");
127 params.Set("direction", "+"); 119 if (pad.axis_value > 0) {
128 params.Set("threshold", "0.25"); 120 params.Set("direction", "+");
129 } else { 121 } else {
130 params.Set("direction", "-"); 122 params.Set("direction", "-");
131 params.Set("threshold", "-0.25");
132 }
133 break;
134 } 123 }
124 break;
135 } 125 }
136 } 126 }
137 return params; 127 return params;
@@ -149,26 +139,30 @@ void GCButtonFactory::EndConfiguration() {
149 139
150class GCAnalog final : public Input::AnalogDevice { 140class GCAnalog final : public Input::AnalogDevice {
151public: 141public:
152 GCAnalog(int port_, int axis_x_, int axis_y_, float deadzone_, 142 explicit GCAnalog(u32 port_, u32 axis_x_, u32 axis_y_, bool invert_x_, bool invert_y_,
153 const GCAdapter::Adapter* adapter, float range_) 143 float deadzone_, float range_, const GCAdapter::Adapter* adapter)
154 : port(port_), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_), gcadapter(adapter), 144 : port(port_), axis_x(axis_x_), axis_y(axis_y_), invert_x(invert_x_), invert_y(invert_y_),
155 origin_value_x(static_cast<float>(adapter->GetOriginValue(port_, axis_x_))), 145 deadzone(deadzone_), range(range_), gcadapter(adapter) {}
156 origin_value_y(static_cast<float>(adapter->GetOriginValue(port_, axis_y_))), 146
157 range(range_) {} 147 float GetAxis(u32 axis) const {
158
159 float GetAxis(int axis) const {
160 if (gcadapter->DeviceConnected(port)) { 148 if (gcadapter->DeviceConnected(port)) {
161 std::lock_guard lock{mutex}; 149 std::lock_guard lock{mutex};
162 const auto origin_value = axis % 2 == 0 ? origin_value_x : origin_value_y; 150 const auto axis_value =
163 return (gcadapter->GetPadState()[port].axes.at(axis) - origin_value) / (100.0f * range); 151 static_cast<float>(gcadapter->GetPadState(port).axis_values.at(axis));
152 return (axis_value) / (100.0f * range);
164 } 153 }
165 return 0.0f; 154 return 0.0f;
166 } 155 }
167 156
168 std::pair<float, float> GetAnalog(int axis_x, int axis_y) const { 157 std::pair<float, float> GetAnalog(u32 analog_axis_x, u32 analog_axis_y) const {
169 float x = GetAxis(axis_x); 158 float x = GetAxis(analog_axis_x);
170 float y = GetAxis(axis_y); 159 float y = GetAxis(analog_axis_y);
171 160 if (invert_x) {
161 x = -x;
162 }
163 if (invert_y) {
164 y = -y;
165 }
172 // Make sure the coordinates are in the unit circle, 166 // Make sure the coordinates are in the unit circle,
173 // otherwise normalize it. 167 // otherwise normalize it.
174 float r = x * x + y * y; 168 float r = x * x + y * y;
@@ -208,14 +202,14 @@ public:
208 } 202 }
209 203
210private: 204private:
211 const int port; 205 const u32 port;
212 const int axis_x; 206 const u32 axis_x;
213 const int axis_y; 207 const u32 axis_y;
208 const bool invert_x;
209 const bool invert_y;
214 const float deadzone; 210 const float deadzone;
215 const GCAdapter::Adapter* gcadapter;
216 const float origin_value_x;
217 const float origin_value_y;
218 const float range; 211 const float range;
212 const GCAdapter::Adapter* gcadapter;
219 mutable std::mutex mutex; 213 mutable std::mutex mutex;
220}; 214};
221 215
@@ -231,13 +225,18 @@ GCAnalogFactory::GCAnalogFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
231 * - "axis_y": the index of the axis to be bind as y-axis 225 * - "axis_y": the index of the axis to be bind as y-axis
232 */ 226 */
233std::unique_ptr<Input::AnalogDevice> GCAnalogFactory::Create(const Common::ParamPackage& params) { 227std::unique_ptr<Input::AnalogDevice> GCAnalogFactory::Create(const Common::ParamPackage& params) {
234 const int port = params.Get("port", 0); 228 const auto port = static_cast<u32>(params.Get("port", 0));
235 const int axis_x = params.Get("axis_x", 0); 229 const auto axis_x = static_cast<u32>(params.Get("axis_x", 0));
236 const int axis_y = params.Get("axis_y", 1); 230 const auto axis_y = static_cast<u32>(params.Get("axis_y", 1));
237 const float deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, 1.0f); 231 const auto deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, 1.0f);
238 const float range = std::clamp(params.Get("range", 1.0f), 0.50f, 1.50f); 232 const auto range = std::clamp(params.Get("range", 1.0f), 0.50f, 1.50f);
239 233 const std::string invert_x_value = params.Get("invert_x", "+");
240 return std::make_unique<GCAnalog>(port, axis_x, axis_y, deadzone, adapter.get(), range); 234 const std::string invert_y_value = params.Get("invert_y", "+");
235 const bool invert_x = invert_x_value == "-";
236 const bool invert_y = invert_y_value == "-";
237
238 return std::make_unique<GCAnalog>(port, axis_x, axis_y, invert_x, invert_y, deadzone, range,
239 adapter.get());
241} 240}
242 241
243void GCAnalogFactory::BeginConfiguration() { 242void GCAnalogFactory::BeginConfiguration() {
@@ -252,31 +251,51 @@ void GCAnalogFactory::EndConfiguration() {
252 251
253Common::ParamPackage GCAnalogFactory::GetNextInput() { 252Common::ParamPackage GCAnalogFactory::GetNextInput() {
254 GCAdapter::GCPadStatus pad; 253 GCAdapter::GCPadStatus pad;
254 Common::ParamPackage params;
255 auto& queue = adapter->GetPadQueue(); 255 auto& queue = adapter->GetPadQueue();
256 for (std::size_t port = 0; port < queue.size(); ++port) { 256 while (queue.Pop(pad)) {
257 while (queue[port].Pop(pad)) { 257 if (pad.button != GCAdapter::PadButton::Undefined) {
258 if (pad.axis == GCAdapter::PadAxes::Undefined || 258 params.Set("engine", "gcpad");
259 std::abs((pad.axis_value - 128.0f) / 128.0f) < 0.1) { 259 params.Set("port", static_cast<s32>(pad.port));
260 continue; 260 params.Set("button", static_cast<u16>(pad.button));
261 } 261 return params;
262 // An analog device needs two axes, so we need to store the axis for later and wait for 262 }
263 // a second input event. The axes also must be from the same joystick. 263 if (pad.axis == GCAdapter::PadAxes::Undefined ||
264 const u8 axis = static_cast<u8>(pad.axis); 264 std::abs(static_cast<float>(pad.axis_value) / 128.0f) < 0.1f) {
265 if (analog_x_axis == -1) { 265 continue;
266 analog_x_axis = axis; 266 }
267 controller_number = static_cast<int>(port); 267 // An analog device needs two axes, so we need to store the axis for later and wait for
268 } else if (analog_y_axis == -1 && analog_x_axis != axis && 268 // a second input event. The axes also must be from the same joystick.
269 controller_number == static_cast<int>(port)) { 269 const u8 axis = static_cast<u8>(pad.axis);
270 analog_y_axis = axis; 270 if (axis == 0 || axis == 1) {
271 } 271 analog_x_axis = 0;
272 analog_y_axis = 1;
273 controller_number = static_cast<s32>(pad.port);
274 break;
275 }
276 if (axis == 2 || axis == 3) {
277 analog_x_axis = 2;
278 analog_y_axis = 3;
279 controller_number = static_cast<s32>(pad.port);
280 break;
281 }
282
283 if (analog_x_axis == -1) {
284 analog_x_axis = axis;
285 controller_number = static_cast<s32>(pad.port);
286 } else if (analog_y_axis == -1 && analog_x_axis != axis &&
287 controller_number == static_cast<s32>(pad.port)) {
288 analog_y_axis = axis;
289 break;
272 } 290 }
273 } 291 }
274 Common::ParamPackage params;
275 if (analog_x_axis != -1 && analog_y_axis != -1) { 292 if (analog_x_axis != -1 && analog_y_axis != -1) {
276 params.Set("engine", "gcpad"); 293 params.Set("engine", "gcpad");
277 params.Set("port", controller_number); 294 params.Set("port", controller_number);
278 params.Set("axis_x", analog_x_axis); 295 params.Set("axis_x", analog_x_axis);
279 params.Set("axis_y", analog_y_axis); 296 params.Set("axis_y", analog_y_axis);
297 params.Set("invert_x", "+");
298 params.Set("invert_y", "+");
280 analog_x_axis = -1; 299 analog_x_axis = -1;
281 analog_y_axis = -1; 300 analog_y_axis = -1;
282 controller_number = -1; 301 controller_number = -1;
@@ -285,4 +304,43 @@ Common::ParamPackage GCAnalogFactory::GetNextInput() {
285 return params; 304 return params;
286} 305}
287 306
307class GCVibration final : public Input::VibrationDevice {
308public:
309 explicit GCVibration(u32 port_, GCAdapter::Adapter* adapter)
310 : port(port_), gcadapter(adapter) {}
311
312 u8 GetStatus() const override {
313 return gcadapter->RumblePlay(port, 0);
314 }
315
316 bool SetRumblePlay(f32 amp_low, [[maybe_unused]] f32 freq_low, f32 amp_high,
317 [[maybe_unused]] f32 freq_high) const override {
318 const auto mean_amplitude = (amp_low + amp_high) * 0.5f;
319 const auto processed_amplitude =
320 static_cast<u8>((mean_amplitude + std::pow(mean_amplitude, 0.3f)) * 0.5f * 0x8);
321
322 return gcadapter->RumblePlay(port, processed_amplitude);
323 }
324
325private:
326 const u32 port;
327 GCAdapter::Adapter* gcadapter;
328};
329
330/// An vibration device factory that creates vibration devices from GC Adapter
331GCVibrationFactory::GCVibrationFactory(std::shared_ptr<GCAdapter::Adapter> adapter_)
332 : adapter(std::move(adapter_)) {}
333
334/**
335 * Creates a vibration device from a joystick
336 * @param params contains parameters for creating the device:
337 * - "port": the nth gcpad on the adapter
338 */
339std::unique_ptr<Input::VibrationDevice> GCVibrationFactory::Create(
340 const Common::ParamPackage& params) {
341 const auto port = static_cast<u32>(params.Get("port", 0));
342
343 return std::make_unique<GCVibration>(port, adapter.get());
344}
345
288} // namespace InputCommon 346} // namespace InputCommon
diff --git a/src/input_common/gcadapter/gc_poller.h b/src/input_common/gcadapter/gc_poller.h
index 0527f328f..d1271e3ea 100644
--- a/src/input_common/gcadapter/gc_poller.h
+++ b/src/input_common/gcadapter/gc_poller.h
@@ -64,4 +64,15 @@ private:
64 bool polling = false; 64 bool polling = false;
65}; 65};
66 66
67/// A vibration device factory creates vibration devices from GC Adapter
68class GCVibrationFactory final : public Input::Factory<Input::VibrationDevice> {
69public:
70 explicit GCVibrationFactory(std::shared_ptr<GCAdapter::Adapter> adapter_);
71
72 std::unique_ptr<Input::VibrationDevice> Create(const Common::ParamPackage& params) override;
73
74private:
75 std::shared_ptr<GCAdapter::Adapter> adapter;
76};
77
67} // namespace InputCommon 78} // namespace InputCommon